Verifying the Backup Command
Explore how to verify the backup command in Bash scripting and improve its logic for better error handling. Understand the role of boolean expressions in controlling command success, logging results clearly, and preventing faulty backups. This lesson helps you write cleaner and more reliable Bash scripts to automate tasks effectively.
We'll cover the following...
Let’s check if the following command works correctly.
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
We can replace each command call with a Latin letter. Then, we get a convenient form of the boolean expression. The expression looks like this:
B && O1 || F1 && C && O2 || F2
The B and C letters represent the tar and cp calls. O1 is the echo call that prints “tar - OK” line in the log file. F1 is the echo call to print the “tar - FAILS” line. Similarly, O2 and F2 are the commands to log the cp result.
If the tar call succeeds, the B operand of our expression equals true. Then, Bash performs the sequence of the following steps:
- B
- O1
- C
- O2 or F2
If the tar fails, the “B” operand equals false. Then Bash does the following steps:
- B
- F1
- C
- O2 or F2
This means that the shell calls the cp utility even when the archiving ...