【问题标题】:Could someone explain this try/catch alternative in bash?有人可以在 bash 中解释这个 try/catch 替代方案吗?
【发布时间】:2013-02-19 18:15:40
【问题描述】:

所以我发现 bash 不处理异常(没有 try/catch)。 对于我的脚本,我想知道命令是否成功。

这是我现在代码的一部分:

command = "scp -p$port $user:$password@$host:$from $to"
$command 2>/dev/null

if (( $? == 0 )); then
    echo 'command was successful'
else
    echo 'damn, there was an error'
fi

我不明白的事情是:

  • 第3行,为什么我必须把2放在$command后面?
  • 第 5 行,这个 $ 到底是什么?

【问题讨论】:

  • 如果你打算做 bash 脚本,谷歌“sh 教程”或“bash 教程”,或者更核心的 approacb man bash。这些是非常基本的细节,还有更多这样的小细节,你可以写出这样的问题......
  • if (( ... )); then ... 的目的是什么? cmd; if [ $? == 0 ] ... 有根本不同吗?

标签: bash try-catch


【解决方案1】:

$? 表示最后执行命令的返回码。

2> 表示将stderr(标准错误流)输出重定向到/dev/null

【讨论】:

    【解决方案2】:

    仅供参考,这也可以:

    if some_command 2>/dev/null ; then
        echo 'command was successful'
    else
        echo 'damn, there was an error'
    fi
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多