Commands Sequence
Explore how to structure Bash scripts with command sequences to automate tasks, handle failures properly using logical AND/OR operators, and control script termination with exit commands and braces. This lesson helps you understand script flow and error management techniques to create reliable automation scripts.
We'll cover the following...
The following demonstrates the script for making the photos backup:
#!/bin/bash
(tar -cjf ~/photo.tar.bz2 ~/photo &&
echo "tar - OK" > results.txt ||
! echo "tar - FAILS" > results.txt) &&
(cp -f ~/photo.tar.bz2 ~/backup &&
echo "cp - OK" >> results.txt ||
! echo "cp - FAILS" >> results.txt)
Click the Run button and then execute the bash script. We can observe the results by running cat results.txt.
#!/bin/bash (tar -cjf ~/photo.tar.bz2 ~/photo && echo "tar - OK" > results.txt || ! echo "tar - FAILS" > results.txt) && (cp -f ~/photo.tar.bz2 ~/backup && echo "cp - OK" >> results.txt || ! echo "cp - FAILS" >> results.txt)
Let’s modify
photo-backup.shwith the following changes. Click on the Run button and then execute the script.
The script contains one command that is too long. This makes it hard to read and modify. We can split the command into two parts. The following shows how it looks like:
#!/bin/bash
tar -cjf ~/photo.tar.bz2 ~/photo &&
echo "tar - OK" > results.txt ||
! echo "tar - FAILS" > ...