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.
- Syntax of if statement
- A simple If statement comparing strings
- if statement comparing numbers
- If expression with AND Condition
- If expression with OR Condition
- If expression with Multiple Conditions
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
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
if [ expression ] && [ expression_2 ];
then
statement(s)
fi
The syntax to include multiple conditions with OR operator is
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.
if [[ expression_1 && expression_2 || expression_3 ]];
then
statement(s)
fi
