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:
2
behind the $command
?$
?The bash shell does not have any fancy exception swallowing mechanism like try/catch constructs.
In Bash scripting, $? prints the exit status. If it returns zero, it means there is no error. If it is non-zero, then you can conclude the earlier task has some issue.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
Handling errors based on exit codes is the standstill method for detecting failure in a command. This is especially true in the case of external commands. Curl in bash is a good example of how to handle errors based on known error codes.
$?
means the return code of the last executed command.
2>
means redirecting the stderr
(standard error stream) output to /dev/null
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With