Junior — Middle
How is error handling performed when writing bash scripts?
sobes.tech AI
Answer from AI
Error handling in bash scripts can be done in several ways:
- Checking command return codes — after executing a command, you can check the
$?variable, which contains the return code (0 — success, any other value — error).
cp source.txt dest.txt
if [ $? -ne 0 ]; then
echo "File copy error"
exit 1
fi
- Using
set -e— the script will automatically terminate if any command fails.
set -e
cp source.txt dest.txt # if the command fails, the script will stop
- Error handling with
trap— allows executing specific actions when errors or signals occur.
trap 'echo "An error occurred!"; exit 1' ERR
- Using conditional operators and checks for more flexible error handling.
By combining these methods, you can effectively control and handle errors in bash scripts.