Govur University Logo
--> --> --> -->
...

Demonstrate how to handle errors and exit codes in a shell script.



Handling errors and exit codes in a shell script is crucial to ensure proper execution and error handling. By checking the exit codes of commands and implementing error handling mechanisms, you can gracefully handle errors, provide meaningful error messages, and control the script's behavior based on different exit statuses.

1. Checking Exit Codes:

* Every command executed in a shell script returns an exit code, which indicates the success or failure of the command.
* The exit code is stored in the special variable `$?`, which you can access immediately after the command execution.
* The convention is that an exit code of 0 indicates success, while a non-zero exit code indicates an error.
2. Conditional Execution Based on Exit Codes:

* You can use conditional statements, such as `if-else` or `case`, to check the exit code and perform different actions accordingly.
* Example using `if-else`:
```
bash`# Check if a command executed successfully
if [ $? -eq 0 ]; then
echo "Command executed successfully"
else
echo "Command failed with an error"
fi`
```
3. Exiting the Script with Custom Exit Codes:

* You can use the `exit` command to terminate the script and specify a custom exit code.
* By convention, an exit code of 0 indicates successful execution, while non-zero exit codes indicate various error conditions.
* Example:
```
bash`# Exit the script with a custom exit code
if [ $some\_condition ]; then
exit 0 # Successful execution
else
exit 1 # Error condition
fi`
```
4. Error Handling with Error Messages:

* When an error occurs, it is essential to provide meaningful error messages to help diagnose and troubleshoot issues.
* You can redirect error output (stderr) to display error messages or log them in a file.
* Example:
```
bash`# Execute a command and display error messages
command_name 2>&1 | tee error.log`
```
5. Graceful Error Recovery and Script Flow Control:

* Depending on the type of error, you may want to implement error recovery mechanisms or adjust the script's flow based on specific conditions.
* This can involve retrying failed commands, skipping certain steps, or exiting the script entirely.
* Example:
```
bash`# Retry a command multiple times until it succeeds or reaches the maximum retry count
max_retries=3
retries=0

while [ $retries -lt $max\_retries ]; do
command_name
if [ $? -eq 0 ]; then
break # Command executed successfully, exit the loop
fi
retries=$((retries + 1))
done

if [ $retries -eq $max\_retries ]; then
echo "Command failed after $max\_retries retries"
exit 1
fi`
```

By incorporating error handling techniques, you can ensure that your shell script gracefully handles errors, provides informative error messages, and responds appropriately to different exit codes. This enables better script reliability, easier troubleshooting, and improved script control in various error scenarios.