Concept Flow - Why error handling prevents silent failures
Start Script
Run Command
Check Exit Status
Continue
End
End
The script runs a command, checks if it worked, and if not, shows an error and handles it to avoid silent failures.
cp source.txt dest.txt if [ $? -ne 0 ]; then echo "Copy failed!" fi
| Step | Action | Command Exit Status ($?) | Condition | Branch Taken | Output |
|---|---|---|---|---|---|
| 1 | Run cp source.txt dest.txt | 0 | 0 != 0? | No | |
| 2 | Check if last command failed | 0 | No | Continue | |
| 3 | Script ends |
| Variable | Start | After cp | After if check | Final |
|---|---|---|---|---|
| $? | N/A | 0 | 0 | 0 |
Run a command in bash. Check its exit status with $?. If non-zero, handle error (e.g., print message). Prevents silent failures by alerting user. Always check $? after important commands.
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