Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could someone explain this try/catch alternative in bash?

Tags:

bash

try-catch

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 $?
like image 798
Harrys Kavan Avatar asked Feb 19 '13 18:02

Harrys Kavan


People also ask

Is there a try catch in bash?

The bash shell does not have any fancy exception swallowing mechanism like try/catch constructs.

How do I see bash script errors?

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.

What does $_ mean in bash?

$_ (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.

What is error handling in Linux?

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.


2 Answers

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

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

like image 174
legrandviking Avatar answered Sep 24 '22 22:09

legrandviking


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
like image 20
William Avatar answered Sep 24 '22 22:09

William