# Error Handling in Shell Scripting 🛠️

## 🎯 Learning Objectives

Understanding how to handle errors in shell scripts is crucial for creating robust and reliable scripts. In this post, you’ll learn how to use various techniques to handle errors effectively in your bash scripts.

## 📋 Topics to Cover

* **Understanding Exit Status**:
    
    * Every command returns an exit status (0 for success and non-zero for failure).
        
    * Learn how to check and use exit statuses.
        
* **Using** `if` Statements for Error Checking:
    
    * Learn how to use `if` statements to handle errors.
        
* **Using** `trap` for Cleanup:
    
    * Understand how to use the `trap` command to handle unexpected errors and perform cleanup.
        
* **Redirecting Errors**:
    
    * Learn how to redirect errors to a file or `/dev/null`.
        
* **Creating Custom Error Messages**:
    
    * Understand how to create meaningful error messages for debugging and user information.
        

## 📝 Tasks

### Task 1: Checking Exit Status

* Write a script that attempts to create a directory and checks if the command was successful.
    
* If not, print an error message.
    

```bash
#!/bin/bash

mkdir my_directory
if [ $? -ne 0 ]; then
  echo "❌ Error: Failed to create directory!"
fi
```

### Task 2: Using `if` Statements for Error Checking

* Modify the script from Task 1 to include more commands (e.g., creating a file inside the directory) and use `if` statements to handle errors at each step.
    

```bash
#!/bin/bash

mkdir my_directory
if [ $? -ne 0 ]; then
  echo "❌ Error: Failed to create directory!"
  exit 1
fi

touch my_directory/my_file.txt
if [ $? -ne 0 ]; then
  echo "❌ Error: Failed to create file!"
  exit 1
fi
```

### Task 3: Using `trap` for Cleanup

* Write a script that creates a temporary file and sets a trap to delete the file if the script exits unexpectedly.
    

```bash
#!/bin/bash

temp_file=$(mktemp)
trap 'rm -f "$temp_file"' EXIT

echo "Temporary file created: $temp_file"
# Simulate an unexpected error
exit 1
```

### Task 4: Redirecting Errors

* Write a script that tries to read a non-existent file and redirects the error message to a file called `error.log`.
    

```bash
#!/bin/bash

cat non_existent_file.txt 2> error.log
echo "🔍 Error message redirected to error.log"
```

### Task 5: Creating Custom Error Messages

* Modify one of the previous scripts to include custom error messages that provide more context about what went wrong.
    

```bash
#!/bin/bash

file_name="non_existent_file.txt"
cat "$file_name" 2> error.log
if [ $? -ne 0 ]; then
  echo "❌ Error: Unable to read '$file_name'. Check if the file exists." >> error.log
fi
```

## 🏁 Conclusion

By understanding and implementing these error handling techniques, you can create more reliable and user-friendly shell scripts. Remember to always check exit statuses, use conditional statements, clean up with traps, redirect errors wisely, and provide meaningful error messages. Happy scripting! 🥳
