我对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
答案 0 :(得分:0)
用于检查变量值的if语句要求该变量存在。
if ( ( $?enableThing1 && ($enableThing1 == 1) ) || \
# ^ this will fail if the variable is not defined.
如果条件变成了
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语句就不会掉下去。
希望这可以为您解决。