w3resource

Bash Conditional Statements - Exercises, Solution and Explanation

1.

Write a Bash script that checks if a number is greater than 10 and prints a message accordingly.

Code:

#!/bin/bash
# Shebang line: Indicates the path to the shell interpreter (in this case, bash)

# Prompt the user to enter a number
echo "Input a number:"
read n

# Check if the number is greater than 100
if [ "$n" -gt 100 ]; then
    echo "The number is greater than 100."
else
    echo "The number is not greater than 100."
fi

Output:

Input a number:
120
The number is greater than 100.

Explanation:

In the exercise above,

  • The user is prompted to input a number using the "echo" command followed by "read".
  • The entered number is stored in the variable '$n'.
  • An "if" statement is used to check if the number is greater than 100. The condition [ "$n" -gt 100 ] checks if the value of '$n' is greater than 100.
  • If the condition evaluates to true, the script prints "The number is greater than 100." using "echo".
  • If the condition evaluates to false, the script prints "The number is not greater than 100.".
  • The "fi" statement marks the end of the "if" block.

2.

Write a Bash script that checks if a file named "test.txt" exists in the current directory, and if it does, prints "File exists", otherwise prints "File does not exist".

Code:

#!/bin/bash
# Shebang line: Indicates the path to the shell interpreter (in this case, bash)

# Check if the file "test.txt" exists in the current directory
if [ -f "test.txt" ]; then
    echo "File exists"
else
    echo "File does not exist"
fi

Output:

File does not exist

Explanation:

In the exercise above,

  • The -f option in the [ -f "test.txt" ] condition checks if "test.txt" is a regular file in the current directory.
  • If the condition is true (i.e., "test.txt" exists as a regular file), the script prints "File exists" using "echo".
  • If the condition is false (i.e., "test.txt" does not exist or is not a regular file), the script prints "File does not exist".
  • The "fi" statement marks the end of the "if" block.

3.

Write a Bash script that prompts the user to enter their age, and then checks if the age is greater than or equal to 18. If it is, print "You are an adult", otherwise print "You are a minor".

Code:

#!/bin/bash
# Shebang line: Indicates the path to the shell interpreter (in this case, bash)

# Prompt the user to enter their age
echo "Input your age:"
read age

# Check if the age is greater than or equal to 18
if [ "$age" -ge 18 ]; then
    echo "You are an adult"
else
    echo "You are a minor"
fi

Output:

Input your age:
12
You are a minor
Input your age:
18
You are an adult
Input your age:
19
You are an adult

Explanation:

In the exercise above,

  • The user is prompted to enter their age using the "echo" command followed by "read".
  • The entered age is stored in the variable '$age'.
  • An if statement checks if the age is greater than or equal to 18. The condition [ "$age" -ge 18 ] checks if the value of '$age' is greater than or equal to 18.
  • If the condition evaluates to true, the script prints "You are an adult" using "echo".
  • If the condition evaluates to false, the script prints "You are a minor".
  • The "fi" statement marks the end of the "if" block.

4.

Write a Bash script that checks if a given string is empty and prints a message accordingly.

Code:

#!/bin/bash
# Shebang line: Indicates the path to the shell interpreter (in this case, bash)

# Define a string
input_str=""

# Check if the string is empty
if [ -z "$input_str" ]; then
    echo "The string is empty"
else
    echo "The string is not empty"
fi

Output:

The string is empty

Explanation:

In the exercise above,

  • The variable 'input_str' is defined as an empty string.
  • An if statement checks if the length of '$input_str' is zero using the -z test operator.
  • If the string is empty, the script prints "The string is empty" using the "echo" command.
  • If the string is not empty, the script prints "The string is not empty".
  • The "fi" statement marks the end of the "if" block.

5.

Write a Bash script that prompts the user to input a password, and then checks if the password matches a predefined value. If it does, print "Access granted", otherwise print "Access denied".

Code:

#!/bin/sh

# Predefined password
my_password="Pass0123$"

# Prompting the user to input a password
printf "Please input your password: "
stty -echo
read user_password
stty echo
printf "\n"

# Checking if the entered password matches the predefined value
if [ "$user_password" = "$my_password" ]; then
    echo "Access granted"
else
    echo "Access denied"
fi

Output:

Please input your password:
Access denied
Please input your password:
Access granted

Explanation:

In the exercise above,

  • my_password="Pass0123$": This line initializes a variable named my_password with the value "Pass0123$". This is the predefined password against which the user's input will be compared.
  • printf "Please input your password: ": This line prints a prompt asking the user to input their password using "printf", which is more portable than "echo".
  • stty -echo: This command disables echoing of characters, so the password input is not displayed on the screen.
  • read user_password: This command reads the user's input and stores it in the variable 'user_password'.
  • stty echo: This command re-enables echoing of characters after the password has been entered.
  • printf "\n": This line prints a newline character to ensure the next output starts on a new line.
  • if [ "$user_password" = "$my_password" ]; then: This line starts a conditional statement that checks if the entered password ('$user_password') matches the predefined password ('$my_password').
  • echo "Access granted": If the passwords match, this line prints "Access granted".
  • else: This keyword marks the beginning of the code block that should be executed if the condition in the "if" statement is not met.
  • echo "Access denied": If the passwords do not match, this line prints "Access denied".

6.

Write a Bash script that checks if a given number is even or odd and prints a message accordingly.

Code:

#!/bin/bash
# Prompting the user to input a number
echo "Please input a number:"
read number

# Checking if the input is a valid number
if [[ ! "$number" =~ ^[0-9]+$ ]]; then
    echo "Invalid input. Please enter a valid number."
    exit 1
fi

# Checking if the number is even or odd
if (( number % 2 == 0 )); then
    echo "$number is even."
else
    echo "$number is odd."
fi

Output:

Please input a number:
100
100 is even.
Please input a number:
101
101 is odd.

Explanation:

In the exercise above,

  • #!/bin/bash: Specifies the interpreter to use, in this case, Bash.
  • echo "Please input a number:": Displays a message prompting the user to input a number.
  • read number: Reads the input from the user and stores it in the variable 'number'.
  • if [[ ! "$number" =~ ^[0-9]+$ ]]; then ... fi: Checks if the input ($number) is a valid integer. The [[ ... ]] construct is used for conditional expressions. The ! operator negates the condition, so it checks if the input does not match the pattern ^[0-9]+$, which means one or more digits from 0 to 9.
  • if (( number % 2 0 )); then ... fi: If the input is a valid number, it checks if the number is even or odd using the arithmetic expression (( ... )). The expression number % 2 0 checks if the remainder of dividing the number by 2 is equal to 0. This indicates that the number is even. If the condition is true, it prints a message indicating that the number is even; otherwise, it prints a message showing that the number is odd.

7.

Write a Bash script that checks if a file named "abc.sh" is executable and if it is, runs the script, otherwise prints "Script is not executable".

Code:

#!/bin/bash

# Check if the file "abc.sh" exists
if [ -e "abc.sh" ]; then
    # Check if the file is executable
    if [ -x "abc.sh" ]; then
        # If executable, run the script
        ./abc.sh
    else
        # If not executable, print message
        echo "Script is not executable"
    fi
else
    # If the file does not exist, print message
    echo "File 'abc.sh' does not exist"
fi

Output:

Script is not executable

Explanation:

In the exercise above,

  • #!/bin/bash: Specifies the interpreter to use, in this case, Bash.
  • [ -e "abc.sh" ]: Checks if the file "abc.sh" exists.
  • [ -x "abc.sh" ]: Checks if the file "abc.sh" is executable.
  • ./abc.sh: Executes the script "abc.sh" if it is executable.
  • echo "Script is not executable": Prints a message indicating that the script is not executable.
  • echo "File 'abc.sh' does not exist": Prints a message indicating that the file "abc.sh" does not exist.

8.

Write a Bash script that prompts the user to enter a number and checks if it is positive, negative, or zero, and prints a message accordingly.

Code:

#!/bin/bash

# Prompting the user to enter a number
echo "Input a number:"
read n

# Checking if the number is positive, negative, or zero
if (( n > 0 )); then
    echo "The number is positive."
elif (( n < 0 )); then
    echo "The number is negative."
else
    echo "The number is zero."
fi

Output:

Input a number:
12
The number is positive.
Input a number:
0
The number is zero.
Input a number:
-23
The number is negative.

Explanation:

In the exercise above,

  • echo "Input a number:": Prompts the user to enter a number.
  • read number: Reads the input number from the user.
  • if (( number > 0 )); then: Checks if the number is greater than 0, indicating a positive number.
  • elif (( number < 0 )); then: Checks if the number is less than 0, indicating a negative number.
  • else: If none of the above conditions are met, it means the number is 0.
  • echo "The number is positive.", echo "The number is negative.", echo "The number is zero.": Prints the corresponding message based on the condition met.

9.

Write a Bash script that checks if a given string is a palindrome (reads the same forwards and backwards) and prints a message accordingly.

Code:

#!/bin/bash

# Prompting the user to enter a string
echo "Input a string:"
read input_str

# Removing non-alphanumeric characters and converting to lowercase
new_string=$(echo "$input_str" | tr -dc '[:alnum:]' | tr '[:upper:]' '[:lower:]')

# Reversing the string
reversed_string=$(echo "$new_string" | rev)

# Checking if the string is a palindrome
if [ "$new_string" = "$reversed_string" ]; then
    echo "The string \"$input_str\" is a palindrome."
else
    echo "The string \"$input_str\" is not a palindrome."
fi

Output:

Input a string:
madam
The string "madam" is a palindrome.
 
Input a string:
abcd
The string "abcd" is not a palindrome.

Explanation:

In the exercise above,

  • echo "Input a string:": Prompts the user to input a string.
  • read input_str: Reads the input string from the user.
  • new_string=$(echo "$input_string" | tr -dc '[:alnum:]' | tr '[:upper:]' '[:lower:]'): Removes non-alphanumeric characters and converts the string to lowercase using the "tr" command.
  • reversed_string=$(echo "$clean_string" | rev): Reverses the new string using the "rev" command.
  • if [ "$clean_string" = "$reversed_string" ]; then: Checks if the new string is equal to its reverse.
  • echo "The string \"$input_str\" is a palindrome.": Prints a message indicating that the input string is a palindrome if the condition is true.
  • echo "The string \"$input_str\" is not a palindrome.": Prints a message indicating that the input string is not a palindrome if the condition is false.

10.

Write a Bash script that checks if a user is logged in and if they are, prints their username, otherwise prints "User is not logged in".

Code:

#!/bin/bash

# Getting the username of the logged-in user
logged_in_user=$(whoami)

# Checking if the user is logged in
if [ -n "$logged_in_user" ]; then
    echo "The logged-in user is: $logged_in_user"
else
    echo "User is not logged in"
fi

Output:

The logged-in user is: admin

Explanation:

In the exercise above,

  • #!/bin/bash: Specifies the interpreter to use, in this case, Bash.
  • logged_in_user=$(whoami): Retrieves the username of the currently logged-in user using the "whoami" command.
  • if [ -n "$logged_in_user" ]; then: Checks if the '$logged_in_user' variable is not empty, indicating that a user is logged in.
  • echo "The logged-in user is: $logged_in_user": Prints the username of the logged-in user if they are logged in.
  • echo "User is not logged in": Prints "User is not logged in" if no user is logged in.

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.