【问题标题】:Why doesn't my if statement with backticks work properly?为什么我的带有反引号的 if 语句不能正常工作?
【发布时间】:2016-01-06 02:07:02
【问题描述】:

我正在尝试制作一个 Bash 脚本,用户可以在其中复制文件,并查看它是否成功完成。但是每次复制完成时,无论是否正确,都会显示第二个输出“复制未完成”。知道如何解决这个问题吗?

if [ `cp -i $files $destination` ];then
        echo "Copy successful."
else
        echo "Copy was not done"
fi

【问题讨论】:

    标签: bash if-statement backticks


    【解决方案1】:

    你想要的是

    if cp -i "$file" "$destination"; then #...
    

    Don't forget the quotes.


    你的版本:

    if [ `cp -i $files $destination` ];then #..
    

    将始终执行else 分支。

    shell 中的 if 语句接受一个命令。 如果该命令成功(返回0,它被分配到$?),则条件成功。

    如果你做if [ ... ]; then,那么它和 if test ... ; then 因为[ ]test 命令/内置的语法糖。

    在您的情况下,您将 cp 操作的 stdout* 的结果作为参数传递给 test

    cp 操作的 stdout 将为空(cp 通常只输出错误,而那些错误会转到 stderr)。带有空参数列表的 test 调用是错误的。该错误会导致非零退出状态,因此您始终会得到 else 分支。


    *$() 进程替换或反引号进程替换 slurp 他们运行的命令的 stdout

    【讨论】:

      【解决方案2】:

      使用反引号,您正在测试 cp 命令的输出,而不是它的状态。您也不需要此处的测试命令(方括号)。

      只需使用:

      if cp ... ; then
          ...
      

      【讨论】:

        【解决方案3】:

        除了测试 output 诗句 status 正如其他答案中正确指出的那样,您可以使用 compound command 来完全按照您的尝试做,而不需要完整的 if ... then ... else ... fi 语法。例如:

        cp -i "$files" "$destination" && echo "Copy successful." || echo "Copy was not done"
        

        本质上与if 语法完全相同。基本上:

        command && 'next cmd if 1st succeeded'
        

        command || 'next cmd if 1st failed'
        

        您只是将command && 'next cmd if 1st succeeded' 用作command || 'next cmd if 1st failed' 中的command。总之就是:

        command && 'next cmd if 1st succeeded' || 'next cmd if 1st failed'
        

        注意:确保始终引用变量以防止分词路径名扩展等...

        【讨论】:

        • 为了完整性,X && Y || Z 实际上并不是 shell 中的三元运算符。即使X 成功(如果Y 失败),Z 也可以运行。
        【解决方案4】:

        试试:

                        cp -i $files $destination
                        #check return value $? if cp command was successful
                        if [ "$?" == "0" ];then
                                echo "Copy successful."
        
                        else
                                echo "Copy was not done"
                        fi
        

        【讨论】:

        • if cp -i "$file" "destination"; then #...
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-14
        • 1970-01-01
        • 1970-01-01
        • 2023-02-03
        • 1970-01-01
        • 2022-12-03
        • 2011-03-14
        相关资源
        最近更新 更多