Introduction
Error handling helps you know when something goes wrong in your script. Without it, problems can happen quietly and cause bigger issues later.
Error handling helps you know when something goes wrong in your script. Without it, problems can happen quietly and cause bigger issues later.
command || { echo "Error: command failed"; exit 1; }cp file1.txt /backup/ || { echo "Copy failed"; exit 1; }mkdir /newfolder || echo "Could not create folder"grep 'hello' file.txt || echo "Text not found"
This script tries to copy a file named important.txt to /backup/. If the copy fails, it prints an error and stops. Otherwise, it confirms success.
#!/bin/bash # Try to copy a file cp important.txt /backup/ || { echo "Error: Failed to copy important.txt"; exit 1; } echo "File copied successfully!"
Always check commands that can fail to avoid silent problems.
Use meaningful error messages to help fix issues quickly.
Stopping the script on errors prevents running bad steps later.
Error handling shows when things go wrong.
It helps avoid silent failures that cause bigger problems.
Use simple checks with || and messages to catch errors early.
command || echo "Error occurred" prints the error message only if the command fails.mkdir /root/testdir || echo "Failed to create directory" echo "Script finished"
cp file1.txt /backup/ if [ $? -eq 0 ] then echo "Copy succeeded" else echo "Copy failed" fi
set -e makes the script exit immediately if any command fails, preventing silent failures.cp source dest || echo "Copy failed" shows a clear error message when a copy fails before exiting.set -e at the start and cp source dest || echo "Copy failed" for each copy -> Option APass the test and this pattern moves unknown