问题
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