Bash IF

Bash IF statement is used for conditional branching in the sequential flow of execution of statements.

We shall learn about the syntax of if statement and get a thorough understanding of it with the help of examples.

Options for IF statement in Bash Scripting

If statement can accept options to perform a specific task. These options are used for file operations, string operations, etc. In this topic, we shall provide examples for some mostly used options.

  • Example – if -z (to check if string has zero length)
  • Example – if -s (to check if file size is greater than zero)
  • Example – if -n (to check if string length is not zero)
  • Example – if -f (to check if file exists and is a regular file)

Syntax of Bash If

Bash If statement syntax is

</>
Copy
if [ expression ];
# ^ ^          ^      please note these spaces
then
    statement(s)
fi

Note : Observe the mandatory spaces required, in the first line, marked using arrows. Also the semicolon at the end of first line. And if conditional statement ends with fi

The syntax to include multiple conditions with AND operator is

</>
Copy
if [ expression ] && [ expression_2 ];
then
    statement(s)
fi

The syntax to include multiple conditions with OR operator is

</>
Copy
if [ expression ] || [ expression_2 ];
then
statement(s)
fi

For compound expressions, following if syntax is allowed. Please observe that the condition has double square brackets.

</>
Copy
if [[ expression_1 && expression_2 || expression_3 ]];
then
    statement(s)
fi