How to Use Flags in Bash If Condition? [With Example]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Flags refer to the options, or switches in Bash that specify and customize various settings and change the behavior of commands, scripts, or functions accordingly. Generally, flags are prefixed with a hyphen (-) or double hyphen (- -). For example, ls -l; where the -l flag/option instructs the ls command to list files in long format.

In Bash, you can use flags or options to control the behavior of your script. These flags are typically passed as arguments when executing the script. You can then check for the presence of these flags using conditional statements like ‘if’. Explore the following article to learn about Bash flags and their versatile usage.

What are the Types of Flags in Bash?

There are two main types of flags in Bash. They are:

  1. Short Flags: Short flags consist of single characters, hence they are also known as single-letter flags. Short flags are usually prefixed with a single hyphen (-). For example, -l, -f, -v, etc.
  2. Long Flags: Long flags are represented by a double hyphen (- -) followed by a descriptive name (a whole word or phrase). These flags are more descriptive and readable. For example, – -list, – -force, – -version, etc.

What are If Flags?

If flags are the structures in Bash where the if statement uses different flags within the test expression and performs conditional executions based on the conditions. The basic syntax of Bash if flags is:

if [ condition_based_on_different_flags ]; then
    #Code to execute if the condition is true
fi

Benefits of Using Flags for Complex If Conditions

The benefits of using flags are:

  • Clarifies the conditions within complex if statements.
  • Breaks down complex conditions into small and manageable portions.
  • Provides flexibility to modify conditions per needs.
  • Aids in debugging by identifying issues within conditions.
  • Enhances efficiency by enabling reusability of conditions across different parts of the code.

Uses of Flags in If Condition

The use cases of flags are so versatile that they allow users to customize the execution of a script or command by specifying certain parameters or settings. Here are some basic use cases of different Bash flags including simple conditional testing, nested conditional execution and command-line arguments.

1. Flags in Single If Block

Bash flags combined with conditional statements allow users to execute different parts of the script conditionally or to modify its behavior based on user inputs or system conditions. Here’s an example of a simple condition execution of Bash flags:

#!/bin/bash

filename="/home/nadiba/distro.txt"

if [ -f $filename ]; then
    echo "The file exists and is a regular file."
    cat $filename
fi
EXPLANATION

Here, the -f flag within the if [ -f $filename ] syntax checks whether the file defined in the $filename variable exists and is a regular file. If the condition is true, the script echoes a successful message displaying the contents of the file.

Simple conditional execution using flags

2. Flags in Nested If Block for Handling Multiple Conditions

Nested-if flags involve using multiple if statements within each other to check various conditions based on the presence or absence of certain flags.

Review the following script to handle multiple conditions using nested if flags:

#!/bin/bash

existence() {
if [ -e $1 ]; then
    echo "'$1' exists."
    if [ -d $1 ]; then
       echo "This is a directory."
    elif [ -f $1 ]; then
       echo  "This is a regular file."
    fi
else
    echo  "'$1' doesn't exist."
fi
}

var=my_dir
existence $var
EXPLANATION

First, the outer if statement if [ -e $1 ] checks if the file or directory specified by $1 exists using the -e flag/option. If the condition is true, it prints a message showing its existence. Then, the inner if statement if [ -d $1 ] checks if the existing one is a directory using the -d flag. If the condition evaluates to true, it prints a message. Otherwise, elif [ -f $1 ] using the -f flag checks if the existing one is a regular file. If it is a regular file, the script prints a message.

If the outer if condition evaluates to false, the script executes the else block and prints a corresponding message.

Bash flags with nested if statement

In the image, you can see that ‘my_dir’ exists in my system and is a directory.

3. Flags as Command-line Arguments

You can pass flags as command line arguments in a Bash script. For example, to display usage information with “-h” or “–help” flag, go through the following script:

#!/bin/bash

#Checking if the "-h" or "--help" flag is set
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    echo "Usage: $0 [-h] [-f] [-v]"
    echo "Options:"
    echo " -h,  Display help message"
    echo " -f,   Force execution"
    echo " -v,  Display Bash version"
    exit 0
fi
EXPLANATION

Here, if [ "$1" = "-h" ] || [ "$1" = "--help" ] checks if the first argument ($1) passed to the script is equal to either -h or –help. If the condition is true, echo "Usage: $0 [-h] [-f] [-v]" prints the usage message where $0 returns the name of the script. Then, echo "Options:" prints the header for the list of options. Next, the echo command prints the usage instructions along with the available options. Finally, exit 0 exits the script with a status code of 0, indicating successful completion.

Bash flags as command line arguments

From the image, you can see that when I run the script with the “-h” or “–help” flag as the first argument, it displays the usage information.

What are the Flags for Error Handling?

To avoid unexpected errors, using the effective Bash flags is necessary. This section interprets some must-know Bash flags that aid in debugging and error handling.

1. “-e” Flag

The ‘-e’ flag when enabled using ‘set’, i.e. set -e, instructs the script to terminate immediately whenever a command returns non-zero output, indicating failure. This option is also known as errexit and is used at the beginning of the script to catch errors earlier.

Check out the following script to handle errors using the set -e option:

#!/bin/bash

set -e
rm /home/nadiba/distro.txt
echo "This will not be displayed"

Using "-e" flag for error handling

From the image, it is clear that the script terminates as soon as the rm command fails to remove the file ‘distro.txt’ from the given path. Even it doesn’t print the message within the echo command.

2. “-u” Flag

The set -u option is referred to as the nounset option. The “-u” flag here helps catch unset variables, treat them as errors, and make the script terminate immediately. This is useful to avoid accidentally misusing uninitialized variables.

#!/bin/bash

set -u
echo "Hello, $distro!"

Using "-u" flag for error handling

In the image, when the -u flag is enabled, the script treats the unset variable as an unbound variable error and exits immediately.

3. “-o” Flag

To enable the -o flag, use the set -o pipefail option. This option makes the script fail if any of the commands within the pipeline fail. In this effort, the script by default considers the exit status of the last command in the pipeline. Here’s an example:

#!/bin/bash

set -o pipefail
cat /home/nadiba/os.txt | grep "linux"

Using "-o" flag for error handling

In the image, when the set -o pipefail option is enabled, the script terminates because of the failure of the cat command. Even, the script doesn’t continue to the grep command.

4. “-x” Flag

Using the set -x option (also known as xtrace) enables the -x flag in a script. It displays every command before its execution which helps in debugging. Following is such a script:

#!/bin/bash

set -x
echo "A debugging message"

var="Linux"
echo "$var"

Using "-x" flag for error handling

The image shows the commands (the highlighted parts) along with their respective outputs.

How to Set Flag Values in Bash?

The getopts is a shell built-in command that allows users to parse command-line options and arguments. So, to set and handle flag values, use the ‘getopts’ command with a case block. The following script shows how:

#!/bin/bash

while getopts ":i:o:" choice; do
  case $choice in
    i)
      input_dir="$OPTARG"
      ;;
    o)
      output_file="$OPTARG"
      ;;
    *)
      echo "Usage: $0 [-i input_dir] [-o output_file]"
      exit 1
      ;;
  esac
done

echo "Input directory is: $input_dir"
echo "Output file is: $output_file"
EXPLANATION

First, while getopts ":i:o:" choice; do initiates a while loop that uses the getopts command to parse command line options. Here, :i:o: specifies two flags (-i for input directory and -o for output file) that the script expects and choice is the variable that stores the processed option flags.

Inside the case statement, when the flags -i and -o are provided, the variables input_dir and output_file store the values of the respective arguments accordingly. Finally, the script echoes the values of the parsed options.

Setting flag values using 'getopts' command

From the image, you can see that when the -i flag is provided, the script outputs its value ‘bash’. When the -o flag is provided, the script prints its value ‘distro.txt’. And when both flags are provided, the script echoes both values.

How to Set the Prompt Input into a Flag?

To set an input from a prompt into a flag, use the read command with a case statement. Let’s see how:

#!/bin/bash

read -p "Do you want to enable the feature? (Y/N):" answer

case $answer in
       [Yy]*) flag=true ;;
       *) flag=false ;;
esac
EXPLANATION

First, the script prompts users with an input message. Then, the construct case $answer in ... esac performs conditional branching based on the value of the variable $answer. Next, [Yy]*) flag=true ;; checks if the input starts with either ‘Y’ or ‘y’. If it does, it sets the variable flag to true. Again, *) flag=false ;; checks if the input doesn’t match ‘Y’ or ‘y’, it sets the variable flag to false.

Setting prompt input into a Bash flag

Conclusion

In conclusion, mastering the usage of Bash if flags opens up a plethora of opportunities for shell scripting enthusiasts and system administrators, I hope this article has provided you the strength and adaptability of conditional statements in regulating a script’s flow according to different circumstances.

People Also Ask

What are bash flags?

Bash flags are switches or options preceded by a hyphen (-) or double hyphen (–) that change the behavior of the commands or scripts. For example, -v or --verbose enables verbose mode (prints additional information), and -f or --force enables force mode (operates without confirmation).

How do I use bash flags?

To use Bash flags, you can either use the built-in getopts command or directly check the value of the positional parameters ($1, $2, etc.).

Can I nest if statements with bash if flags?

Yes, you can nest if statements with Bash If Flags. It allows one to perform complex conditional checking based on specific flag conditions. Here’s the basic structure of a nested if statement using Bash flags:

if [ condition1_based_on_different_flags ]; then
    #Code to execute if the condition1 is true
   if [ condition2_based_on_different_flags ]; then
    #Code to execute if the condition2 is true
   fi
fi

How to check the presence of a specific flag in Bash?

To check if a specific flag is present in Bash, compare command line arguments with the flag within an if statement. For example, the below script checks if the ‘-v’ flag is present in the first argument.

#!/bin/bash

if [[ "$1" == "-v" ]]; then
    echo "Verbose mode enabled"
fi

How can I handle flags in Bash scripts?

You can handle flags in Bash scripts using the built-in getopts command. Generally, getopts parses command-line options and processes them based on the specified flags. In addition, you can process flags manually by checking the values of positional parameters ($1, $2, etc.) or using conditional statements.

Related Articles


<< Go Back to If Statement in Bash | Bash Conditional Statements | Bash Scripting Tutorial

Rate this post
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment