Could someone explain this try/catch alternative in bash?

ぐ巨炮叔叔 提交于 2019-12-06 18:26:19

问题


So I found out that bash does not handle exceptions (there is no try/catch). For my script, I would like to know if a command was successful or not.

This is the part of my code right now:

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

The things I don't understand are:

  • line 3, why do I have to put the 2 behind the $command?
  • line 5, what exactly is it with this $?

回答1:


$? means the return code of the last executed command.

2> means redirecting the stderr (standard error stream) output to /dev/null.




回答2:


Just FYI, this will also work:

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


来源:https://stackoverflow.com/questions/14964529/could-someone-explain-this-try-catch-alternative-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!