w3resource

Bash Error Handling: Exercises, Solutions & Explanation

1.

Check if a File Exists:

Write a Bash script that checks if a file named "temp.txt" exists in the current directory. If it exists, echo "File exists", otherwise, echo "File not found".

Code:

#!/bin/bash

# Check if file exists
if [ -e "temp.txt" ]; then
    echo "File exists"
else
    echo "File not found"
fi

Output:

rg@DESKTOP-3KE0KU4:~$ ./test1.sh
File exists

Explanation:

In the exercise above,

  • if [ -e "temp.txt" ]; then: This line checks if a file named "temp.txt" exists in the current directory.
    • -e "temp.txt": Checks if "temp.txt" exists.
  • echo "File exists": If the file exists, this line is executed, printing "File exists".
  • else: If the file does not exist, the script executes the following line.
  • echo "File not found": This line is executed if the file does not exist, printing "File not found".

2.

Handle Division by Zero:

Write a Bash script that prompts the user to enter two numbers and divides them. Ensure that the script handles the case where the second number is zero by displaying an error message "Error: Division by zero".

Code:

#!/bin/bash

# Prompt the user to enter two numbers
read -p "Input the first number: " num1
read -p "Input the second number: " num2

# Check if the second number is zero
if [ "$num2" -eq 0 ]; then
    echo "Error: Division by zero"
else
    # Perform division and display the result
    result=$(echo "scale=2; $num1 / $num2" | bc)
    echo "Result of division: $result"
fi  

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Input the first number: 12
Input the second number: 7
Result of division: 1.71
ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Input the first number: 12
Input the second number: 0
Error: Division by zero 

Explanation:

In the exercise above,

  • read -p "Enter the first number: " num1: Prompts the user to enter the first number and stores it in the variable num1.
  • read -p "Enter the second number: " num2: Prompts the user to enter the second number and stores it in the variable 'num2'.
  • if [ "$num2" -eq 0 ]; then: Checks if the second number is zero.
    • -eq: Arithmetic comparison operator for equality.
  • echo "Error: Division by zero": If the second number is zero, this message is displayed.
  • else: If the second number is not zero, the script continues with the division operation.
  • result=$(echo "scale=2; $num1 / $num2" | bc): Performs the division operation, limiting the result to two decimal places using "bc".
  • echo "Result of division: $result": Displays the result of the division.

3.

Handle Invalid Input:

Write a Bash script that asks the user to input a number. If the input is not a number, display an error message "Invalid input. Please input a number" and prompt the user to input again until a valid number is provided.

Code:

#!/bin/bash

# Function to check if input is a number
is_number() {
    # Regular expression to match a number
    re='^[0-9]+$'
    if [[ $1 =~ $re ]]; then
        return 0   # Return success if it's a number
    else
        return 1   # Return failure if it's not a number
    fi
}

# Ask user to input a number
echo "Please input a number:"

# Loop until valid input is provided
while :
do
    read input   # Read user input

    # Check if input is a number
    if is_number "$input"; then
        echo "Input is a valid number."
        break   # Exit the loop if input is valid
    else
        echo "Invalid input. Please input a number:"   # Prompt user for valid input
    fi
done

Output:

rg@DESKTOP-3KE0KU4:~$ ./test1.sh
Please input a number:
12
Input is a valid number.
rg@DESKTOP-3KE0KU4:~$ ./test1.sh
Please input a number:
a
Invalid input. Please input a number:
10
Input is a valid number.

Explanation:

In the exercise above,

  • Function Definition: is_number() { ... }
    • This defines a Bash function named "is_number()" which checks whether a given input is a number or not.
  • Regular Expression: re='^[0-9]+$'
    • This variable "re" stores a regular expression pattern that matches a sequence of one or more digits.
  • Function Body:
    • Inside the function "is_number()", it checks if the input matches the regular expression pattern. If it does, it returns success (0), indicating that the input is a number. Otherwise, it returns failure (1), indicating that the input is not a number.
  • Prompting User Input: echo "Please input a number:"
    • This line prompts the user to input a number.
  • Loop for input validation:
    • The script enters a "while" loop that continues indefinitely (until explicitly terminated).
    • Inside the loop, it reads the user input using the "read" command.
  • Input validation:
    • It checks if the input provided by the user is a number by calling the "is_number()" function and passing the input as an argument.
    • If the input is a number, it prints a message "Input is a valid number" and breaks out of the loop.
    • If the input is not a number, it prints an error message "Invalid input. Please input a number:" and the loop continues, prompting the user for input again.

4.

Check for Required Arguments:

Write a Bash script that requires two arguments to be passed. If the required arguments are not provided, display an error message "Usage: script_name arg1 arg2" indicating the correct usage.

Code:

#!/bin/bash

# Check if two arguments are provided
if [ $# -ne 2 ]; then
    echo "Usage: $0 arg1 arg2"
    exit 1
fi

# If two arguments are provided, display them
echo "Argument 1: $1"
echo "Argument 2: $2"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh 12 100
Argument 1: 12
Argument 2: 100
ad@DESKTOP-3KE0KU4:~$ ./test1.sh 12
Usage: ./test1.sh arg1 arg2

Explanation:

In the exercise above,

  • $# represents the number of arguments passed to the script.
  • -ne is a comparison operator for "not equal".
  • $0 represents the name of the script itself.
  • exit 1 terminates the script with a non-zero exit code indicating an error.

5.

Check for Command Existence:

Write a Bash script that checks if a command (e.g., "gcc") exists on the system. If the command exists, echo "Command exists", otherwise, echo "Command not found".

Code:

#!/bin/bash

# Define the command to check
command_name="gcc"

# Check if the command exists
if command -v $command_name &> /dev/null; then
    echo "$command_name exists"
else
    echo "$command_name not found"
fi

Output:

ad@DESKTOP-3KE0KU4:~$ gcc
The program 'gcc' is currently not installed. You can install it by typing:
sudo apt install gcc
ad@DESKTOP-3KE0KU4:~$ ./test1.sh 12
gcc not found 

Explanation:

In the exercise above,

  • command -v $command_name checks if the command exists and outputs its path if found.
  • &> /dev/null redirects both stdout and stderr to /dev/null to suppress any output.
  • If the command is found, it prints "Command exists"; otherwise, it prints "Command not found".

6.

Handle File Permission Errors:

Write a Bash script that tries to read a file named "temp.txt". If the script encounters a permission error while reading the file, display an error message "Permission denied" and exit with a non-zero status code.

Code:

#!/bin/bash

# Define the file to read
file="temp.txt"

# Try to read the file
if [ -r "$file" ]; then
    # File is readable, so read it
    cat "$file"
else
    # Permission denied or file does not exist
    if [ ! -e "$file" ]; then
        echo "Error: File $file does not exist."
    else
        echo "Error: Permission denied while reading $file."
    fi
    # Exit with non-zero status code
    exit 1
fi

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
1. This is line 1
2. Another line with a digit at the beginning
3. Line starting with a letter
4. 12345 Some more text here
5. Line without a digit at the beginning
6. 67890 More text with a digit
7. Line 7 with some text
8. 42 The answer to everything
9. 9th line with a number
10. Line 10 with no number

Explanation:

In the exercise above,

  • -r "$file" checks if the file is readable.
  • -e "$file" checks if the file exists.
  • If the file is readable, it prints the contents using "cat".
  • If there's a permission error or the file doesn't exist, it prints an appropriate error message and exits with a non-zero status code using exit 1.

7.

Handle Unexpected Input:

Write a Bash script that expects the user to enter "yes" or "no". If the input is neither "yes" nor "no", display an error message "Invalid input. Please enter 'yes' or 'no'".

Code:

#!/bin/bash

# Prompt the user to enter "yes" or "no"
echo "Please input 'yes' or 'no':"

# Read user input
read input

# Check if the input is "yes" or "no"
if [ "$input" = "yes" ]; then
    echo "You entered 'yes'."
elif [ "$input" = "no" ]; then
    echo "You entered 'no'."
else
    # Display error message for invalid input
    echo "Invalid input. Please enter 'yes' or 'no'."
fi

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Please input 'yes' or 'no':
yes
You entered 'yes'.
ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Please input 'yes' or 'no':
no
You entered 'no'.
ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Please input 'yes' or 'no':
hello
Invalid input. Please enter 'yes' or 'no'.

Explanation:

In the exercise above,

  • The script prompts the user to enter "yes" or "no".
  • It reads the user input using "read".
  • It checks if the input is equal to "yes" or "no" using "if" and "elif".
  • If the input is neither "yes" nor "no", it displays an error message.

8.

Handle File Writing Errors:

Write a Bash script that appends a line to a file named "temp.txt". If the script encounters an error while writing to the file, display an error message "Error writing to file" and exit with a non-zero status code.

Code:

#!/bin/bash

# Append a line to temp.txt
echo "This is a new line" >> temp.txt

# Check if the previous command was successful
if [ $? -eq 0 ]; then
    echo "Line appended successfully."
else
    echo "Error writing to file."
    exit 1  # Exit with non-zero status code
fi 

Output:

ad@DESKTOP-3KE0KU4:~$ cat temp.txt
1. This is line 1
2. Another line with a digit at the beginning
3. Line starting with a letter
4. 12345 Some more text here
5. Line without a digit at the beginning
6. 67890 More text with a digit
7. Line 7 with some text
8. 42 The answer to everything
9. 9th line with a number
10. Line 10 with no number.
ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Line appended successfully.
ad@DESKTOP-3KE0KU4:~$ cat temp.txt
1. This is line 1
2. Another line with a digit at the beginning
3. Line starting with a letter
4. 12345 Some more text here
5. Line without a digit at the beginning
6. 67890 More text with a digit
7. Line 7 with some text
8. 42 The answer to everything
9. 9th line with a number
10. Line 10 with no number.
This is a new line

Explanation:

In the exercise above,

  • The script appends a line to "temp.txt" using "echo".
  • It checks if the previous command was successful by examining the exit status using "$?".
  • If the command succeeds (exit status 0), it prints a success message.
  • If there was an error (non-zero exit status), it prints an error message and exits with a non-zero status code.

9.

Check for Directory Existence:

Write a Bash script that checks if a directory named "data" exists. If the directory exists, display "Directory exists", otherwise, create the directory and display "Directory created".

Code:

#!/bin/bash

# Check if directory "workarea_1" exists
if [ -d "workarea_1" ]; then
    echo "Directory exists"
else
    # Create directory if it doesn't exist
    mkdir workarea_1
    echo "Directory created"
fi

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
Directory created

Explanation:

In the exercise above,

  • The script checks if the directory "workarea_1" exists using the -d flag with the if condition.
  • If the directory exists, it prints "Directory exists".
  • If the directory doesn't exist, it creates the directory using "mkdir" and prints "Directory created".

10.

Handle Command Execution Errors:

Write a Bash script that tries to execute a command (e.g., "ls -l file.txt"). If the command execution fails, display an error message "Command execution failed" and exit with a non-zero status code.

Code:

#!/bin/bash

# Command to execute
command_to_execute="ls -l file100.txt"

# Try executing the command
if ! $command_to_execute; then
    echo "Command execution failed"
    exit 1  # Exit with non-zero status code
fi

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
ls: cannot access 'file100.txt': No such file or directory
Command execution failed

Explanation:

In the exercise above,

  • The script stores the command to execute in a variable 'command_to_execute'.
  • It attempts to execute the command using if ! $command_to_execute. The ! negates the command, so the "if" block will execute if the command fails.
  • If the command fails, it prints "Command execution failed" and exits with a non-zero status code.

Bash Editor:


More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/bash-script-exercises/handling-errors-and-exceptions.php