Introducing Oz: the orchestration platform for cloud agents.

Learn More.

Bash If Statement

Gabriel 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:

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 :

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:

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:

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:

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:

The logical OR

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

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.

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:

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:

For example, [text]:

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:

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.

Written by

Gabriel 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
Neeran 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
Razvan Ludosanu

How To Use sudo su

A quick overview of using sudo su

LinuxUnixBash
Razvan Ludosanu

Generate, Sign, and View a CSR With OpenSSL

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

BashLinuxUnix
Razvan Ludosanu

How to use sudo rm -rf safely

We'll help you understand its components

BashLinuxUnix
Neeran Gul

How to run chmod recursively

Using -R is probably not what you want

LinuxBashUnix
Brett Terpstra

Run Bash Shell In Docker

Start an interactive shell in Docker container

DockerBash
Razvan Ludosanu

Curl Post Request

Use cURL to send data to a server

BashUnixLinux
Zev Stravitz

Reading User Input

Via command line arguments and prompting users for input

BashLinuxUnix
Amit Jotwani

Bash Aliases

Create an alias for common commands

BashLinuxUnix
Brett Terpstra

Trusted by hundreds of thousands of professional developers

Download Warp to get started

Download for Mac
.deb

Debian, Ubuntu

.rpm

Red Hat, Fedora, SUSE

Download for Windows

For Windows 11/10 x64

Download for Windows

For Windows 11/10 ARM64

On a mobile device? Send Warp to your work station.