Catch failure in shell script

Pretty new to shell scripting. I am trying to do the following:

#!/bin/bash unzip myfile.zip #do stuff if unzip successful 

I know that I can simply group the teams together with && , but there is quite a piece, it will not be terribly supported.

+6
source share
4 answers

You can use the exit status of the command explicitly in the test:

 if ! unzip myfile.zip &> /dev/null; then # handle error fi 
+12
source

Can you use $? . It returns:
- 0 if the command was successfully completed.
-! 0 if the team was unsuccessful.

So you can do

 #!/bin/bash unzip myfile.zip if [ $? -eq 0 ]; then #do stuff on unzip successful fi 

and in case of an error, you can even use this:

 [ $? ] && echo "error!" 

Test

 $ cat a hello $ echo $? 0 $ cat b cat: b: No such file or directory $ echo $? 1 
+10
source

Variable $? contains the exit status of the previous command. The successful exit status for (most) teams is (usually) 0, so just check this ...

 #!/bin/bash unzip myfile.zip if [ $? == 0 ] then # Do something fi 
+5
source

If you want the shell to check the result of executed commands and stop interpreting when something returns a non-zero value, you can add set -e , which means Exit immediately if the command exits with non-zero status. I often use this in scripts.

 #!/bin/sh set -e # here goes the rest 
+3
source

Source: https://habr.com/ru/post/946504/


All Articles