Concept Flow - Error logging patterns
Start Script
Run Command
Check Exit Status
Log Error
End Script
The script runs a command, checks if it failed, logs an error if so, then continues or ends.
command_that_might_fail if [ $? -ne 0 ]; then echo "Error: command failed" >> error.log fi
| Step | Action | Command Exit Status ($?) | Condition | Log Action | Output |
|---|---|---|---|---|---|
| 1 | Run command_that_might_fail | 1 | 1 != 0 (True) | Append error message to error.log | error.log updated with 'Error: command failed' |
| 2 | Check condition again | 1 | No further action | No log | No change |
| 3 | End script | - | - | - | Script ends |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| $? | - | 1 | 1 | 1 |
| error.log | empty or previous content | added error message | unchanged | contains error message |
Error logging in bash: Run a command Check exit status with $? (0=success, non-zero=failure) If failure, append error message to a log file Use '>>' to keep previous logs This helps track failures without stopping script
2> operator do in a bash script?2>2> redirects the standard error stream to a file or location.2> means error redirect [OK]error.log?2> redirects standard error and overwrites the file; 2>> appends errors.2> error.log is correct.script.sh prints "Success" to standard output and "Error occurred" to standard error?./script.sh > output.log 2> error.log> output.log redirects standard output to output.log, 2> error.log redirects standard error to error.log.errors.log:command 2>2 errors.log2> filename. Here, 2>2 errors.log redirects stderr to file 2, treating errors.log as a command argument.2 instead of errors.log.> overwrites standard output, 2>> appends standard error to a file../script.sh > output.log 2>> error.log fits.Pass the test and this pattern moves unknown