In this tutorial, we will walk you through the basics of the Bash if
statement and show you how to use it in your shell scripts.
Decision making is one of the most fundamental concepts of computer programming. Like in any other programming language, if
, if..else
, if..elif..else
and nested if
statements in Bash can be used to execute code based on a certain condition.
if
StatementBash if
conditionals can have different forms. The most basic if
statement takes the following form:
if TEST-COMMAND
then
STATEMENTS
fi
Copy
The if
statement starts with the if
keyword followed by the conditional expression and the then
keyword. The statement ends with the fi
keyword.
If the TEST-COMMAND
evaluates to True
, the STATEMENTS
gets executed. If TEST-COMMAND
returns False
, nothing happens, the STATEMENTS
gets ignored.
In general, it is a good practice to always indent your code and separate code blocks with blank lines. Most people choose to use either 4-space or 2-space indentation. Indentations and blank lines make your code more readable and organized.
Let’s look at the following example script that checks whether a given number is greater than 10:
#!/bin/bash
echo -n "Enter a number: "
read VAR
if [[ $VAR -gt 10 ]]
then
echo "The variable is greater than 10."
fi
Copy
Save the code in a file and run it from the command line:
bash test.sh
#bash #statement