w3resource

Bash Exit Codes: Exercises, Solutions & Explanation

1.

Write a Bash script that executes a command and prints its exit status code.

Code:

#!/bin/bash

# Command to execute
command_to_execute="ls /new_dir"

# Execute the command
$command_to_execute

# Get the exit status code
exit_status=$?

# Print the exit status code
echo "Exit status code: $exit_status"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh
ls: cannot access '/new_dir': No such file or directory
Exit status code: 2

Explanation:

In the exercise above,

  • Define the command to execute:
    • command_to_execute="ls /new_dir"
    • Assigns the command "ls /new_dir" to the variable 'command_to_execute'. This command lists the contents of the directory /new_dir.
  • Execute the command:
    • $command_to_execute
    • Executes the command stored in the variable 'command_to_execute'.
    • In this case, it runs the "ls /new_dir" command, listing the contents of the directory /new_dir.
  • Get the exit status code:
    • exit_status=$?
    • Captures the exit status code of the previously executed command.
    • $? is a special variable that holds the exit status of the last executed command.
    • Stores the exit status in the variable 'exit_status'.
  • Print the exit status code:
    • echo "Exit status code: $exit_status"
    • Prints the exit status code along with a descriptive message.
    • $exit_status is the value of the exit status code captured in step 3.

2.

Write a Bash script that checks if a file exists. Print "File exists" if it does and "File not found" otherwise, using appropriate exit status codes.

Code:

#!/bin/bash

# File to check
file_to_check="temp.txt"

# Check if file exists
if [ -e "$file_to_check" ]; then
    echo "File exists"
    exit 0  # Exit with code 0 indicating success
else
    echo "File not found"
    exit 1  # Exit with code 1 indicating failure
fi

Output:

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

Explanation:

In the exercise above,

  • The variable 'file_to_check' holds the name of the file we want to check.
  • The "if" statement checks if the file exists using the -e test operator.
  • If the file exists, it prints "File exists" and exits with code 0, indicating success.
  • If the file does not exist, it prints "File not found" and exits with code 1, indicating failure.

3.

Write a Bash script that divides two numbers. If division is successful, print the result; otherwise, print an error message with an appropriate exit status code.

Code:

#!/bin/bash

# Function to perform division
divide_numbers() {
    if [ $2 -eq 0 ]; then
        echo "Error: Division by zero"
        exit 1  # Exit with code 1 indicating failure
    fi
    result=$(bc <<< "scale=2; $1 / $2")  # Using 'bc' for floating-point division
    echo "Result of division: $result"
}

# Main script
if [ $# -ne 2 ]; then
    echo "Usage: $0 <dividend> <divisor>"
    exit 1  # Exit with code 1 indicating incorrect usage
fi

dividend=$1
divisor=$2

divide_numbers $dividend $divisor
exit 0  # Exit with code 0 indicating success

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh  12 3
Result of division: 4.00
ad@DESKTOP-3KE0KU4:~$ ./test1.sh  12 0
Error: Division by zero
ad@DESKTOP-3KE0KU4:~$ ./test1.sh  0 12
Result of division: 0

Explanation:

In the exercise above,

  • Define a function "divide_numbers()" to perform division.
  • Inside the function, we check if the divisor is 0, if so, we print an error message and exit with code 1.
  • We use bc, an arbitrary-precision arithmetic language, to perform floating-point division.
  • The scale=2 setting in bc ensures two decimal places in the result.
  • In the main script:
    • Check if there are exactly two arguments provided (dividend and divisor).
    • If not, we print usage information and exit with code 1.
    • Next assign the arguments to variables 'dividend' and 'divisor'.
    • Finally, call the "divide_numbers()" function with the provided arguments.
  • The script exits with code 0 indicating success after the division is performed.

4.

Write a Bash script that checks if a given user exists on the system. Print "User exists" if the user is found and "User not found" otherwise, with corresponding exit status codes.

Code:

#!/bin/bash

# Function to check if user exists
check_user_existence() {
    if id "$1" &>/dev/null; then
        echo "User exists"
        exit 0  # Exit with code 0 indicating success
    else
        echo "User not found"
        exit 1  # Exit with code 1 indicating failure
    fi
}

# Main script
if [ $# -ne 1 ]; then
    echo "Usage: $0 <username>"
    exit 1  # Exit with code 1 indicating incorrect usage
fi

username=$1

check_user_existence "$username"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh user1
User not found
ad@DESKTOP-3KE0KU4:~$ ./test1.sh ad
User exists

Explanation:

In the exercise above,

  • Define a function "check_user_existence()" to check if the given user exists on the system.
  • Inside the function:
    • Use the "id" command to check if the user exists. If the user exists, the "id" command will return successfully (exit code 0), otherwise, it will return an error (exit code 1).
    • Redirect the output of 'id' to /dev/null to suppress any output.
  • In the main script:
    • Check if there is exactly one argument provided (the username).
    • If not, print usage information and exit with code 1.
    • Next assign the provided username to the variable 'username'.
    • Finally, call the "check_user_existence()" function with the provided username.
  • The script exits with code 0 indicating success if the user exists, and with code 1 indicating failure if the user does not exist.

5.

Write a Bash script that compiles a C program. If compilation succeeds, print "Compilation successful"; otherwise, print an error message with an appropriate exit status code.

Code:

#!/bin/bash

# Function to compile C program
compile_program() {
    # Compilation command
    gcc -o "$1" "$2"
    
    # Check compilation result
    if [ $? -eq 0 ]; then
        echo "Compilation successful"
        exit 0  # Exit with code 0 indicating success
    else
        echo "Compilation failed: check errors"
        exit 1  # Exit with code 1 indicating failure
    fi
}

# Main script
if [ $# -ne 2 ]; then
    echo "Usage: $0 <output_executable> <source_file>"
    exit 1  # Exit with code 1 indicating incorrect usage
fi

output_executable="$1"
source_file="$2"

# Get the absolute path of the source file
source_file=$(realpath "$source_file")

compile_program "./$output_executable" "$source_file"

Output:

ad@DESKTOP-3KE0KU4:~$ cat hello.c
#include <stdio.h>

int main()
{
    // Print Name
    printf("Name   : Alexandra Abramov\n");

    // Print Date of Birth
    printf("DOB    : July 14, 1975\n");

    // Print Mobile Number
    printf("Mobile : 99-9999999999\n");

    // Indicate successful execution
    return(0);
}

ad@DESKTOP-3KE0KU4:~$ ./test1.sh hello hello.c
Compilation successful
ad@DESKTOP-3KE0KU4:~$ ./hello
Name   : Alexandra Abramov
DOB    : July 14, 1975
Mobile : 99-9999999999

Explanation:

In the exercise above,

  • Function to compile a C program:
    • compile_program(): Defines a function named "compile_program()" to compile a C program.
    • Inside this function:
      • gcc -o "$1" "$2": Compiles the C program. '$1' is the output executable name, and '$2' is the source file.
      • if [ $? -eq 0 ]; then ... else ... fi: Checks the exit status of the compilation command.
        • $? holds the exit status of the last command.
        • If the exit status is 0, it indicates successful compilation.
        • If the exit status is non-zero, it indicates compilation failure.
      • exit 0: Exits the script with code 0 if compilation is successful.
      • exit 1: Exits the script with code 1 if compilation fails.
  • Main script:
    • Checks if the number of command-line arguments is not equal to 2.
      • If the condition is true, it prints a usage message and exits with code 1.
    • Assign the first argument to 'output_executable' and the second argument to 'source_file'.
    • Use 'realpath' to get the absolute path of the source file.
    • Calls the "compile_program()" function with the output executable and the source file as arguments.

6.

Write a Bash script that pings a given host. Print "Host is reachable" if the ping is successful and "Host is unreachable" otherwise, with appropriate exit status codes.

Code:

#!/bin/bash

# Function to ping the host
ping_host() {
    ping -c 1 "$1" &>/dev/null  # Send only 1 ping packet and redirect output to /dev/null
    if [ $? -eq 0 ]; then
        echo "Host is reachable"
        exit 0  # Exit with code 0 indicating success
    else
        echo "Host is unreachable"
        exit 1  # Exit with code 1 indicating failure
    fi
}

# Main script
if [ $# -ne 1 ]; then
    echo "Usage: $0 <hostname>"
    exit 1  # Exit with code 1 indicating incorrect usage
fi

hostname="$1"

ping_host "$hostname" 

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh example.com
Host is reachable
ad@DESKTOP-3KE0KU4:~$ ./test1.sh w3resource.com
Host is reachable
ad@DESKTOP-3KE0KU4:~$ ./test1.sh google.com
Host is reachable
ad@DESKTOP-3KE0KU4:~$ ./test1.sh google.abc
Host is unreachable 

Explanation:

In the exercise above,

  • The "ping_host()" function pings the given hostname.
  • Inside the function:
    • ping -c 1 "$1" &>/dev/null: Sends only one ping packet to the given hostname and redirects output to /dev/null to suppress output.
    • if [ $? -eq 0 ]; then ... else ... fi: Checks the exit status of the ping command.
      • If the exit status is 0, it means the ping was successful, and the host is reachable.
      • If the exit status is non-zero, it means the ping failed, and the host is unreachable.
  • In the main script,
    • Check if there is exactly one argument provided (the hostname).
    • If not, print the usage information and exit with code 1.
    • Next assign the provided hostname to the variable 'hostname'.
    • Finally, call the "ping_host()" function with the provided hostname.
  • The script exits with code 0 indicating success if the host is reachable, and with code 1 indicating failure if the host is unreachable.

7.

Write a Bash script that checks if a directory exists. Print "Directory exists" if it exists and "Directory not found" otherwise, with corresponding exit status codes.

Code:

#!/bin/bash

# Function to check if directory exists
check_directory_existence() {
    if [ -d "$1" ]; then
        echo "Directory exists"
        exit 0  # Exit with code 0 indicating success
    else
        echo "Directory not found"
        exit 1  # Exit with code 1 indicating failure
    fi
}

# Main script
if [ $# -ne 1 ]; then
    echo "Usage: $0 "
    exit 1  # Exit with code 1 indicating incorrect usage
fi

directory="$1"

check_directory_existence "$directory" 

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh workarea
Directory exists
ad@DESKTOP-3KE0KU4:~$ ./test1.sh workarea_1
Directory exists
ad@DESKTOP-3KE0KU4:~$ ./test1.sh workarea_2
Directory not found

Explanation:

In the exercise above,

  • The "check_directory_existence()" function checks if the given directory exists.
  • Inside the function:
    • We use the -d test to check if the directory exists.
    • If the directory exists, it prints "Directory exists" and exits with code 0.
    • If the directory does not exist, it prints "Directory not found" and exits with code 1.
  • In the main script,
    • Check if there is exactly one argument provided (the directory name).
    • If not, print the usage information and exit with code 1.
    • Next assign the provided directory name to the variable 'directory'.
    • Finally, call the "check_directory_existence()" function with the provided directory name.
  • The script exits with code 0 indicating success if the directory exists, and with code 1 indicating failure if the directory does not exist.

8.

Write a Bash script that renames a file. Print "File renamed successfully" if the renaming is successful and an error message otherwise, with appropriate exit status codes.

Code:

#!/bin/bash

# Function to rename file
rename_file() {
    if mv "$1" "$2" &>/dev/null; then
        echo "File renamed successfully"
        exit 0  # Exit with code 0 indicating success
    else
        echo "Error: Failed to rename file"
        exit 1  # Exit with code 1 indicating failure
    fi
}

# Main script
if [ $# -ne 2 ]; then
    echo "Usage: $0 <current_name> <new_name>"
    exit 1  # Exit with code 1 indicating incorrect usage
fi

current_name="$1"
new_name="$2"

rename_file "$current_name" "$new_name"

Output:

ad@DESKTOP-3KE0KU4:~$ dir c*.txt
cp_document.txt
ad@DESKTOP-3KE0KU4:~$ ./test1.sh cp_document.txt document.txt
File renamed successfully
ad@DESKTOP-3KE0KU4:~$ dir do*.txt
document.txt

Explanation:

In the exercise above,

  • The "rename_file()" function renames a file from the given current name to the new name.
  • Inside the function:
    • We use "mv" command to rename the file. If the renaming is successful, "mv" returns true (exit code 0).
    • If the renaming is successful, it prints "File renamed successfully" and exits with code 0.
    • If the renaming fails, it prints an error message and exits with code 1.
  • In the main script,
    • We check if there are exactly two arguments provided (current name and new name).
    • If not, print the usage information and exit with code 1.
    • We then assign the provided current name and new name to the variables 'current_name' and 'new_name'.
    • Finally, we call the "rename_file()" function with the provided current and new name.
  • The script exits with code 0 indicating success if the renaming is successful, and with code 1 indicating failure if the renaming fails.

9.

Write a Bash script that checks if a process is running. Print "Process is running" if it's found and "Process not found" otherwise, with corresponding exit status codes.

Code:

#!/bin/bash

# Function to check if process is running
check_process() {
    if pgrep "$1" &>/dev/null; then
        echo "Process is running"
        exit 0  # Exit with code 0 indicating success
    else
        echo "Process not found"
        exit 1  # Exit with code 1 indicating failure
    fi
}

# Main script
if [ $# -ne 1 ]; then
    echo "Usage: $0 <process_name>"
    exit 1  # Exit with code 1 indicating incorrect usage
fi

process_name="$1"

check_process "$process_name"

Output:

ad@DESKTOP-3KE0KU4:~$ ./test1.sh bash
Process is running
ad@DESKTOP-3KE0KU4:~$ ./test1.sh htop
Process not found

Explanation:

In the exercise above,

  • The "check_process()" function checks if the given process is running.
  • Inside the function:
    • We use "pgrep" to search for processes by name. If the process is found, "pgrep" returns true (exit code 0).
    • If the process is found, it prints "Process is running" and exits with code 0.
    • If the process is not found, it prints "Process not found" and exits with code 1.
  • In the main script:
    • We check if there is exactly one argument provided (the process name).
    • If not, print the usage information and exit with code 1.
    • We then assign the provided process name to the variable 'process_name'.
    • Finally, we call the "check_process()" function with the provided process name.
  • The script exits with code 0 indicating success if the process is running, and with code 1 indicating failure if the process is not running.

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.



Follow us on Facebook and Twitter for latest update.