【问题标题】:Return value of redirected bash command [duplicate]重定向 bash 命令的返回值 [重复]
【发布时间】:2014-03-25 00:05:59
【问题描述】:

以下脚本尝试创建一个目录,但由于 temp1 不存在而失败。我想用“tee”重定向输出。问题是“$?”捕获成功的“tee”的返回值,而不是失败的“mkdir”的值。如何使用“tee”但检查“mkdir”的返回值

文件名:./test.sh

#!/bin/bash

mkdir temp1/temp2 | tee test_output.txt
if [ "$?" != 0 ]; then
    echo "Command failed"
else
    echo "Command successed"
fi

./test.sh

mkdir: 无法创建目录 `temp1/temp2': 没有这样的文件或目录

命令成功

【问题讨论】:

    标签: bash


    【解决方案1】:

    既然你声明了bash,你就可以使用PIPESTATUS。来自man 页面:

    管道状态
    包含出口列表的数组变量(请参阅下面的数组) 最近执行的进程的状态值 前台管道(可能只包含一个命令)。

    例如:

    #!/bin/bash
    
    mkdir temp1/temp2 | tee test_output.txt
    if [ "${PIPESTATUS[0]}" != 0 ]; then
        echo "Command failed"
    else
        echo "Command succeeded"
    fi
    

    【讨论】:

      【解决方案2】:

      有依赖终端的解决方案,但您可以通过将此命令包装在函数中来解决此问题。

      create_dir() {
        { mkdir temp1/temp2 || return 1; } | tee test_output.txt
        return $?
      }
      
      create_dir
      if [ "$?" != 0 ]; then
        echo "Command failed"
      else
        echo "Command successed"
      fi
      

      【讨论】:

        【解决方案3】:

        您能不能只使用mkdir -p 来强制创建目录?

        【讨论】:

          【解决方案4】:

          可能没有目录 temp1 将参数 -p 与 mkdir 一起使用:

          mkdir -p temp1/temp2 | tee test_output.txt
          

          【讨论】:

            猜你喜欢
            • 2015-10-19
            • 2019-04-22
            • 1970-01-01
            • 1970-01-01
            • 2016-05-05
            • 1970-01-01
            • 2013-02-28
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多