首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >$?tcsh脚本问题

$?tcsh脚本问题
EN

Stack Overflow用户
提问于 2019-02-07 14:13:55
回答 1查看 134关注 0票数 0

我对tcsh shell脚本问题感到困惑。(对于工作,在shell中没有选择,我被它卡住了)

下面的enableThingN项是在使用tcsh shell运行此csh脚本之前由其他人员设置的shell环境变量。这些在这里根本不是在同一个脚本中设置的,只是在这里求值。

错误消息为:

代码语言:javascript
复制
enableThing1: Undefined variable.

代码为:

代码语言:javascript
复制
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上都搜索过,但结果很少,也没有给我答案,比如:

代码语言:javascript
复制
https://stackoverflow.com/questions/16975968/what-does-var-mean-in-csh
EN

回答 1

Stack Overflow用户

发布于 2019-02-07 16:02:36

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

代码语言:javascript
复制
if ( ( $?enableThing1  &&  ($enableThing1 == 1) ) || \
#                             ^ this will fail if the variable is not defined.

所以if条件变成了

代码语言:javascript
复制
if ( ( 0  &&  don'tknowaboutthis ) || \

然后它就变得平坦了。

假设您不希望使用if梯子,并且不希望将功能添加到要检查的变量列表中,您可以尝试以下解决方案:

代码语言:javascript
复制
#!/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语句不会失效。

希望这能帮你解决这个问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54567322

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档