Junior — Middle
Why is it recommended to add the 'set -e' command at the beginning of a bash script?
sobes.tech AI
Answer from AI
The set -e command in a bash script causes the script to immediately exit if any command within it returns a non-zero exit code (i.e., an error). This is useful for preventing the script from continuing to execute when an error occurs, which could lead to unpredictable consequences.
For example, without set -e, the script might continue running even if one of the commands fails, making debugging more difficult and potentially leading to data corruption.
Example:
#!/bin/bash
set -e
cp important_file /backup/
rm important_file
If the cp command fails, the script will stop, and rm will not delete the file, protecting the data from loss.