我对tcsh shell脚本问题感到困惑。(对于工作,在shell中没有选择,我被它卡住了)
下面的enableThingN项是在使用tcsh shell运行此csh脚本之前由其他人员设置的shell环境变量。这些在这里根本不是在同一个脚本中设置的,只是在这里求值。
错误消息为:
enableThing1: Undefined variable.代码为:
if ( ( $?enableThing1 && ($enableThing1 == 1) ) || \
( $?enableThing2 && ($enableThing2 == 1) ) || \
( $?enableThing3 && ($enableThing3 == 1) ) || \
( $?enableThing4 && ($enableThing4 == 1) ) ) then
set someScriptVar = FALSE
else
set someScriptVar = TRUE
endif因此,据我所知,大if条件的第一部分是使用$?enableThing1魔术检查是否定义了enableThing1。如果已定义,则继续检查该值是否为1或其他值。如果未定义,则跳过对同一外壳变量的==1部分的检查,继续查看是否定义了enableThing2,依此类推。
看起来我是在检查是否存在,如果值没有定义,我打算避免检查值,那么我哪里错了?
我在stackoverflow和Google上都搜索过,但结果很少,也没有给我答案,比如:
https://stackoverflow.com/questions/16975968/what-does-var-mean-in-csh发布于 2019-02-07 16:02:36
检查变量值的if语句要求变量存在。
if ( ( $?enableThing1 && ($enableThing1 == 1) ) || \
# ^ this will fail if the variable is not defined.所以if条件变成了
if ( ( 0 && don'tknowaboutthis ) || \然后它就变得平坦了。
假设您不希望使用if梯子,并且不希望将功能添加到要检查的变量列表中,您可以尝试以下解决方案:
#!/bin/csh -f
set enableThings = ( enableThing1 enableThing2 enableThing3 enableThing4 ... )
# setting to false initially
set someScriptVar = FALSE
foreach enableThing ($enableThings)
# since we can't use $'s in $? we'll have to do something like this.
set testEnableThing = `env | grep $enableThing`
# this part is for checking if it exists or not, and if it's enabled or not
if (($testEnableThing != "") && (`echo $testEnableThing | cut -d= -f2` == 1 )) then
# ^ this is to check if the variable is defined ^ this is to take the part after the =
# d stands for delimiter
# for example, the output of testEnableThing, if it exists, would be enableThing1=1
# then we take that and cut it to get the value of the variable, in our example it's 1
# if it exists and is enabled, set your someScriptVar
set someScriptVar = TRUE
# you can put a break here since it's irrelevant to check
# for other variables after this becomes true
break
endif
end这是因为我们只使用了一个变量"testEnableThing",由于它的工作方式,它总是被定义。它可以是一个空字符串,但它将被定义为使if语句不会失效。
希望这能帮你解决这个问题。
https://stackoverflow.com/questions/54567322
复制相似问题