【问题标题】:$? tcsh script issue美元? tcsh脚本问题
【发布时间】:2019-07-01 05:09:10
【问题描述】:

我对 tcsh shell 脚本问题感到困惑。 (为了工作,shell别无选择,我坚持)

下面的 enableThingN 项是其他东西在运行这个 csh 脚本之前使用 tcsh shell 设置的 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 或其他值。如果未定义,则跳过检查同一 shell 变量的 ==1 部分,继续查看 enableThing2 是否已定义,依此类推。

看起来我正在检查是否存在,如果根本没有定义值,我打算避免检查值,我哪里出错了?

我已经在 stackoverflow 和整个 Google 上进行了搜索,但结果很少,并且没有让我得到答案,例如:

https://stackoverflow.com/questions/16975968/what-does-var-mean-in-csh

【问题讨论】:

    标签: variables if-statement undefined csh tcsh


    【解决方案1】:

    检查变量值的 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 语句就不会落空。

    希望这能为您解决问题。

    【讨论】:

    • 脱机时,在 grep 中添加 -w 会更好,因为在没有 -w 的情况下会发生意外的 shell var 名称冲突,并且 grep 会为多个 var 输出多行,从而混淆 if语句并给出有关 if 语法的错误。谢谢!抱歉,我还没有足够的声望点来投票赞成这个解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 2011-11-01
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 2012-09-21
    • 2019-11-27
    相关资源
    最近更新 更多