Occasionally there is a need in bash scripting to execute a series of commands in sequence conditionally. Command2 needs to be run after command1 if, and only if, the command1 succeeded (or failed).
One means of performing this is to execute the command, assign the return value to a variable, and evaluate the return value executing the subsequent command based on the value.
$ cat -n foo
1 #!/bin/bash
2
3 sleep 1
4 #sleep -1
5 rc=$?
6
7 echo $rc
8 if [ $rc == 0 ]; then
9 echo "run something else"
10 fi
11
Note, the above the script executes a sleep command, preserves the return code, and executes the subsequent command (e.g. echo) based on the return value. Note; we can force a failed return code by specifying a negative sleep duration.
An alternative shortened syntax is to specify the command sequence on a single line using a '&&' or '||' seperator, the seperator determing if the subsequent command should be exectued on success/failure of the preceeding command.
command1 && command2
This syntax issues command2 if, and only if, command1 returns an exit status of zero.
An OR list has the form
command1 ││ command2
Now, command2 is executed if and only if command1 returns a non-zero exit status. This can be used to readily define recovery, or notification, behaviors for a failed command.
The return status of AND and OR lists is the exit status of the last command executed in the list.
1 #!/bin/bash
2
3 sleep 1 && echo "run something else"; #--execute command2 if command1 was successful
4 sleep -1 || echo "run something else"; #--execute command2 if command1 failed
5 sleep -1 && echo "run something else"; #--execute command2 if command1 was successful
6
No comments:
Post a Comment