$? tcsh的脚本问题

问题描述 投票:0回答:1

我很困惑带tcsh shell脚本问题。 (工作,没有选择的外壳,我坚持了下来)

下面的enableThingN项目运行此脚本CSH使用tcsh外壳之前其他事情外壳设置环境变量。这些都不是同一个脚本在这里所有的,只有在这里评估内。

错误信息:

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

所以,我明白的事情,大的第一部分,如果条件是检查是否enableThing1在全部或没有定义,使用$?enableThing1魔术。如果它被定义,然后继续前进,并检查该值是1或别的东西。如果没有定义,则跳过检查对于同一外壳变量的== 1部分,并继续前进,以查看是否enableThing2在所有定义的与否,等等。

因为它看起来像我检查的存在,并打算避免检查,如果它是不是在所有定义,我在哪里出了错价值?

我在这里搜索了计算器和谷歌的大,但也有少数结果,不会让我一个答案,如:

https://stackoverflow.com/questions/16975968/what-does-var-mean-in-csh
variables if-statement undefined csh tcsh
1个回答
0
投票

if语句来检查变量的值要求变量存在。

if ( ( $?enableThing1  &&  ($enableThing1 == 1) ) || \
#                             ^ this will fail if the variable is not defined.

所以,如果条件变成

if ( ( 0  &&  don'tknowaboutthis ) || \

和败笔。

假设你如果阶梯不想的,和功能添加到的变量来检查,你可以尝试以下解决这个列表:

#!/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语句不会落空。

希望这解决了它。

© www.soinside.com 2019 - 2024. All rights reserved.