Sometimes we want to execute more than one command in one line. Fortunately, there are a few operators that allows us to do this depending on successful or not execution of previous commands. Let's have a look.
Checking command exit code
First, let's prepare two helper scripts -
script_failure.sh - that will exit with exit codes
1. Successful script will exit with
0 and failing one will exit with
1, because non-zero exit code indicates an error.
echo "success" exit 0
echo "failure" exit 1
Remember to make them executable using
chmod +x command.
Next, check if exit codes are returned properly. We can check it using
echo $? command, that gives us exit status of last executed script.
Running second command regardless of success
If you want to always run second command, use
; operator, for example:
echo "first"; echo "second"
To check if second command always runs, let's use our
Running second command only if first succeded
For this, we will use
echo "first" && echo "second"
With this operator, we should only execute second command when running
success script, let's check.
Running second command only if first failed
For this case we have
echo "first" || echo "second"
Now we should only see execution of second command when running
This operator can be very useful for error handling.
Using operators when running scripts in the background
To run script in the background use
But how can we use these operators when running in the background? Let's modify our
script_failure.sh scripts to output to file.
echo "success" >> output exit 0
echo "failure" >> output exit 1
Using operators when running scripts in the background is simple. Let's assume we want to use
&& operator to run second command only if first succeded - we are going to use this syntax:
(first && second) &
Let's test this. First, let's run successful script first, so we should get both outputs in our file.
(./script_success.sh && ./script_failure.sh ) &
 + 48428 exit 1 ( ./script_success.sh && ./script_failure.sh; )
Now let's reverse, so first script fails. In that case we should only see first output in file. Before doing so, remember to remove output file with
(./script_failure.sh && ./script_success.sh ) &
 + 48483 exit 1 ( ./script_failure.sh && ./script_success.sh; )
And it's the same for
(./script_failure.sh || ./script_success.sh ) &
 + 48507 done ( ./script_failure.sh || ./script_success.sh; )
(./script_failure.sh; ./script_success.sh ) &
 + 48543 done ( ./script_failure.sh; ./script_success.sh; )