Mild Fuzz
Mild Fuzz

Reputation: 30813

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 just chain the commands together in with && but there is quite a chunk, it would not be terribly maintainable.

Upvotes: 7

Views: 11607

Answers (4)

fedorqui
fedorqui

Reputation: 290415

You can use $?. It returns:
- 0 if the command was successfully executed.
- !0 if the command was unsuccessful.

So you can do

#!/bin/bash

unzip myfile.zip

if [ "$?" -eq 0 ]; then
    #do stuff on unzip successful
fi

Test

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

Upvotes: 11

Grzegorz Żur
Grzegorz Żur

Reputation: 49241

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

#!/bin/sh

set -e

# here goes the rest

Upvotes: 4

user1019830
user1019830

Reputation:

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

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

Upvotes: 12

user166560
user166560

Reputation:

The variable $? contains the exit status of the previous command. A successful exit status for (most) commands is (usually) 0, so just check for that...

#!/bin/bash
unzip myfile.zip

if [ $? == 0 ]
then
    # Do something
fi

Upvotes: 5

Related Questions