• Modern UX

    Edit and navigate faster in the terminal with Warp's IDE-like input editor.

  • Warp AI

    AI suggests what commands to run and learns from your documentation.

  • Agent Mode

    Delegate tasks to AI and use natural language on the command line.

  • Warp Drive

    Save and share interactive notebooks, workflows, and environment variables.

  • All Features

Bash If Statement

Thumbnail for Gabriel ManricksGabriel Manricks

Gabriel Manricks

Chief Architect, ClearX

Updated: 7/30/2024

Published: 7/30/2024

About Terminus

The short answer

In Bash, the if  statement is a control structure that allows developers to execute one or more instructions based on the evaluation of a command or an expression called a condition.

If the condition evaluates to true  (i.e. the exit status equals zero), then the subsequent instructions are executed.

The syntax of the if  statement is as follows:

if condition; then
  instructions
fi

Run in Warp

Where:

  • if  starts the conditional statement.
  • condition  is the expression that will be evaluated.
  • then  specifies the set of instructions to execute if the condition is true.
  • fi  ends the conditional statement.

For example, let's consider the following script, where the echo  command will only be executed if the exit status of the grep  command is 0 :

#!/bin/bash

if grep -q error access.log; then
  echo "log contains errors"
fi

Run in Warp

Comparing values

In order to compare two values together within an if  statement, you need to enclose the comparison expression within square brackets [  as follows:

if [ expression ]; then
  instructions
fi

Run in Warp

Where:

  • expression  is a logical expression composed of variables, values, and comparison operators.

Note that this syntax is in fact an alias for the built-in test  command.

Comparing numbers

Numeric comparisons are done using the following operators:

  • -eq : equal to
  • -ne : not equal to
  • -lt : less than
  • -le : less than or equal to
  • -gt : greater than
  • -ge : greater than or equal to

For example, let's consider this script that makes the user guess a number:

 #!/bin/bash

number=5

while true;
do
  read -p "Guess the number: " input

  if [ $input -lt $number ]; then
    echo "Too low..."
    continue
  fi

  if [ $input -gt $number ]; then
    echo "Too high..."
    continue
  fi

  if [ $input -eq $number ]; then
    echo "Good guess!"
    break
  fi
done

Run in Warp

Comparing strings

String comparisons are done using the following operators:

  • = : equal to
  • != : not equal to
  • < : less than
  • > : greater than

And the following flags:

  • -z : string is empty
  • -n : string is not empty

Note that when using flags, you can use the NOT !  operator to negate the expression.

For example, let’s consider this script that makes the user guess a word:

#!/bin/bash

word="hello"

echo "Guess the word (type 'quit' to exit)."

while :
do
  read -p "> " input

  if [ ! -n $input ]; then
    echo "Error: invalid input"
    continue
  fi

  if [ $input == "quit" ]; then
    echo "Goodbye!"
    break
  fi

  if [ $input != $word ]; then
    echo "Try again..."
    continue
  fi

  if [ $input == $word ]; then
    echo "Congratulations!"
    break
  fi
done

Run in Warp

Combining conditions

The logical &&  (AND) and ||  (OR) operators allow you to combine two or more conditions into a single expression.

The logical AND

When using the AND operator, all conditions must evaluate to true for the subsequent instructions to be executed:

if [ condition ] && [ condition ]; then
  # instructions
fi

Run in Warp

The logical OR

When using the OR operator, only one of the conditions must evaluate to true for the subsequent instructions to be executed:

if [ condition ] || [ condition ]; then
  # instructions
fi

Run in Warp

Evaluating complex conditions

Unlike the single square brackets [ , the double square brackets [[  provide a more advanced processing and evaluation of conditional expressions.

It retrieves the specified expression as a single string instead of separate arguments, and performs its own expansions.

if [[ expression ]]; then
  # instructions
fi

Run in Warp

Matching simple and regex patterns

In addition, the double square brackets allow you to match simple and advanced patterns using the =~  operator.

Simple matchers include:

  • [<chars>] : a specific set of characters
  • ? : a single character
  • * : any string/substring

Note that these matchers need to be placed outside of quotes as they will otherwise lose their meaning and be treated as regular characters.

For example, let’s consider this script that checks whether the file passed as argument of the script is a JavaScript or JSON file:

#!/bin/bash

if [[ "$1" =~ \.(js|json)$ ]]; then
    echo "Valid JS or JSON file"
fi

Run in Warp

Evaluating arithmetic expressions

To easily perform basic arithmetic operations within an if  statement using mathematical operators, such as + , - , * , etc, and comparison operators, such as > , <= , == , etc, you can use the double parentheses ((  instead of the square brackets [[  as follows:

if (( expression )); then
  # instructions
fi

Run in Warp

For example, [text]:

#!/bin/bash

number=1
i=2

if (( $number <= 2 )); then
  echo "not prime"
  exit 1
fi

while [ $i -lt $number ];
do
  if (( $number % $i == 0 )); then
    echo "not prime"
    exit 1
  fi
  ((i++))
done

echo "prime"

Run in Warp

Testing files and directories

Testing the existence

To test the existence and type of files or directories you can respectively use the -f  and -d  flags.

For example:

if [ -f ./script.sh ]; then
  # instructions
fi

Run in Warp
if [ -d /home/johndoe ]; then
  # instructions
fi

Run in Warp

Testing permissions

To test whether a file or directory has read, write, or execute permission, you can respectively use the -r , -w , and -x flags.

if [[ ! -x ./my_script.sh ]]; then
    chmod +x my_script.sh
fi

Run in Warp

Written by

Thumbnail for Gabriel ManricksGabriel Manricks

Gabriel Manricks

Chief Architect, ClearX

Filed Under

Related Articles

Bash While Loop

Learn how to use and control the while loop in Bash to repeat instructions, and read from the standard input, files, arrays, and more.

Bash

POST JSON Data With Curl

How to send valid HTTP POST requests with JSON data payloads using the curl command and how to avoid common syntax pitfalls. Also, how to solve the HTTP 405 error code.

BashUnixLinux
Thumbnail for Neeran GulNeeran Gul

Use Cookies With cURL

Learn how to store and send cookies using files, hard-coded values, environment variables with cURL.

Bash

Loop Through Files in Directory in Bash

Learn how to iterate over files in a directory linearly and recursively using Bash and Python.

BashPython
Thumbnail for Razvan LudosanuRazvan Ludosanu

How To Use sudo su

A quick overview of using sudo su

LinuxUnixBash
Thumbnail for Razvan LudosanuRazvan Ludosanu

Generate, Sign, and View a CSR With OpenSSL

Learn how to generate, self-sign, and verify certificate signing requests with `openssl`.

BashLinuxUnix
Thumbnail for Razvan LudosanuRazvan Ludosanu

How to use sudo rm -rf safely

We'll help you understand its components

BashLinuxUnix
Thumbnail for Neeran GulNeeran Gul

How to run chmod recursively

Using -R is probably not what you want

LinuxBashUnix
Thumbnail for Brett TerpstraBrett Terpstra

Run Bash Shell In Docker

Start an interactive shell in Docker container

DockerBash
Thumbnail for Razvan LudosanuRazvan Ludosanu

Curl Post Request

Use cURL to send data to a server

BashUnixLinux
Thumbnail for Zev StravitzZev Stravitz

Reading User Input

Via command line arguments and prompting users for input

BashLinuxUnix
Thumbnail for Amit JotwaniAmit Jotwani

Bash Aliases

Create an alias for common commands

BashLinuxUnix
Thumbnail for Brett TerpstraBrett Terpstra

Trusted by hundreds of thousands of professional developers

Download Warp to get started

Download for Mac
Thumbnail for null