Error Handling in Shell Scripting

Error Handling in Shell Scripting

  1. Task 1 : Checking Exit Status

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

#!/bin/bash

# User input to create directory
read -p "Enter directory that you want to create: " dir

# Create directory
mkdir $dir

# Check if previous command executed or not
if [ $? -ne '0' ]; then
        echo "Sorry :( Failed to create directory $dir"
        exit 1
else
        echo "Directory '$dir' created successfully:)"
fi
# Output

linux$ ./Create_Dir.sh
Enter directory that you want to create: Demo_Directory
Directory 'Demo_Directory' created successfully:)

linux$ ./Create_Dir.sh
Enter directory that you want to create: Demo_Directory
mkdir: cannot create directory ‘Demo_Directory’: File exists
Sorry :( Failed to create directory Demo_Directory

  1. Task 2 : Using if Statements for Error Checking

    Q. 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.

#!/bin/bash

# User input to create file
read -p "Enter filename with absolute path that you want to create: " file

# Create file
touch $file

# Check if previous command executed or not
if [ $? -ne '0' ]; then
        echo "Sorry :( Failed to create file $file"
        exit 1
else
        echo "File '$file' created successfully:)"
fi
linux$ ./Create_file.sh
Enter filename with absolute path that you want to create: /home/shuhari/linux/demo.txt
File '/home/shuhari/linux/demo.txt' created successfully:)

  1. Task 3 : Using trap for Cleanup

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

#!/bin/bash

# Create a temporary file
TEMP_FILE=$(mktemp)

# Ensure the temporary file is deleted upon script exit
trap "rm -f $TEMP_FILE" EXIT

echo "Temporary file created: $TEMP_FILE"

# Simulate some operations
echo "Performing some operations..."
sleep 3

# Simulate an unexpected exit
echo "Simulating an unexpected exit..."
exit 1

# Normal script exit point (this won't be reached due to the simulated exit)

echo "Script completed successfully."
# Output

linux$ ./trap.sh
Temporary file created: /tmp/tmp.BQqhnnNvlk
Performing some operations...
Simulating an unexpected exit...

Refer more for trap command.


  1. Task 4 : Redirecting Errors

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

#!/bin/bash

# Declare variables for file and error.log
read -p "Enter file name that your want to read: " file
error_file="error.log"

# Attempt to read non_existing file and redirect error message to error.log
cat "$file" 2> "$error_file"

# Check is error was logged?
if [ -s "$error_file" ]; then
        echo "An error occurred. Check $error_file for details."
else
        echo "File read successfully."
fi
# Output

linux$ ls
Create_Dir.sh  Create_file.sh  redirect_errors.sh  trap.sh

/linux$ ./redirect_errors.sh
Enter file name that your want to read: demoFile.txt
An error occurred. Check error.log for details.

linux$ ls
Create_Dir.sh  Create_file.sh  error.log  redirect_errors.sh  trap.sh

linux$ cat error.log
cat: demoFile.txt: No such file or directory

-----------------------------------------------------------------------------

linux$ ls
Create_Dir.sh  Create_file.sh  redirect_errors.sh  temp.txt  trap.sh

linux$ ./redirect_errors.sh
Enter file name that your want to read: temp.txt
This is tempFile
File read successfully.

  1. Task 5 : Creating Custom Error Messages

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

#!/bin/bash

# Prompt the user for the file name to read
read -p "Enter the file name you want to read: " file
error_file="error.log"

# Attempt to read the specified file and redirect error messages to error.log
cat "$file" 2> "$error_file"

# Check if an error was logged
if [ -s "$error_file" ]; then
    # Check specific error conditions
    if [ ! -f "$file" ]; then
        echo "Error: The file '$file' does not exist."
    # Check if file have read permission or not
    elif [ ! -r "$file" ]; then
        echo "Error: Permission denied. Unable to read the file '$file'."
    else
        echo "An unknown error occurred. Check $error_file for details."
    fi
else
    echo "File '$file' read successfully."
fi
# Output

linux$ ls
adv_errors.sh  Create_Dir.sh  Create_file.sh  demo.xtxt  redirect_errors.sh  trap.sh

linux$ ./adv_errors.sh
Enter the file name you want to read: file.txt
Error: The file 'file.txt' does not exist.

linux$ ls
adv_errors.sh  Create_Dir.sh  Create_file.sh  demo.xtxt  error.log  redirect_errors.sh  trap.sh

linux$ cat error.log
cat: file.txt: No such file or directory

linux$ ./adv_errors.sh
Enter the file name you want to read: demo.xtxt
Hii
File 'demo.xtxt' read successfully.

linux$ cat error.log
linux$

Connect me

LinkedIn | GitHub

Follow me for more amazing content :)