【问题标题】:variable substitution in if statementif语句中的变量替换
【发布时间】:2016-09-23 16:18:24
【问题描述】:

我正在尝试执行以下操作

if [[ $1 == 'R' ]]
then
    echo "Running the recovery steps..."
    for i in 1 2 3 4 5 6
    do
        head -${i} cons.txt | tail -1 | read -r r${i}f1 r${i}f2 r${i}f3 r${i}f4 r${i}f5 r${i}f6 r${i}f7 r${i}f8 r${i}f9;
        if (( ${Time} >= ${r${i}f1} && ${Time} < ${r${i}f2} ))
        then
            sed "s/$r$if3}/`echo $r$if3 | cut -c1-4`/;s/$r$if4/`echo $r$if4 | cut -c1-4`/;s/$r$if5/`echo $r$if5 | cut -c1-4`/;s/$r$if6/`echo $r$if6 | cut -c1-4`/;s/$r$if7/`echo $r$if7 | cut -c1-4`/;s/$r$if8/`echo $r$if8 | cut -c1-4`/;s/$r$if9/`echo $r$if9 | cut -c1-4`/" cons.txt > cons.txt.tmp && mv cons.txt.tmp cons.txt
        fi
    done
fi

但内部 if 条件给了我错误。我相信我在这里使用了错误的大括号,但似乎无法找出正确的方法

trim.sh[6]: " ${Time} >= ${r${i}f1} && ${Time} < ${r${i}f2} ": 0403-011 The specified substitution is not valid for this command.

【问题讨论】:

    标签: unix ksh aix


    【解决方案1】:

    你不能直接在变量引用中做变量。

    ${r${i}f2}
    

    你必须使用间接引用。试试下面的代码它会工作。使用 eval 我们可以做到这一点。

    if [[ $1 == 'R' ]]
    then
        echo "Running the recovery steps..."
        for i in 1 2 3 4 5 6
        do
            head -${i} cons.txt | tail -1 | read -r r${i}f1 r${i}f2 r${i}f3 r${i}f4 r${i}f5 r${i}f6 r${i}f7 r${i}f8 r${i}f9;
            eval var1=r${i}f1
            eval var2=r${i}f2
    
            eval val1=\$$var1
            eval val2=\$$var2
    
            if (( ${Time} >= $val1 && ${Time} < $val2 ))
            then
                sed "s/$r$if3}/`echo $r$if3 | cut -c1-4`/;s/$r$if4/`echo $r$if4 | cut -c1-4`/;s/$r$if5/`echo $r$if5 | cut -c1-4`/;s/$r$if6/`echo $r$if6 | cut -c1-4`/;s/$r$if7/`echo $r$if7 | cut -c1-4`/;s/$r$if8/`echo $r$if8 | cut -c1-4`/;s/$r$if9/`echo $r$if9 | cut -c1-4`/" cons.txt > cons.txt.tmp && mv cons.txt.tmp cons.txt
            fi
        done
    fi
    

    【讨论】:

      【解决方案2】:

      &lt; ${r${i}f2} 中的参数扩展不是递归的(或重复的,或由内而外),所以这是行不通的。

      您可以使用一些复杂的代码(使用eval)在展开之前构造变量名,但那是一堆蠕虫。简单地展开六元素循环怎么样?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-04
        • 2019-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-10
        • 1970-01-01
        • 2014-11-29
        相关资源
        最近更新 更多