Bash if else Statement | Bash Scripting - Else If Statement | Linux Shell If-Else Syntax Example
Nov 2, 2023
The if else statement in Bash is used to conditionally execute code based on the evaluation of an expression. The syntax of the if else statement is as follows:
Bash
if [ expression ]; then
# code to execute if the expression is true
else
# code to execute if the expression is false
fi
Use code with caution. Learn more
The expression can be any valid Bash expression, such as a comparison expression, a logical expression, or a test of a file or directory. If the expression evaluates to true, then the code in the then clause is executed. Otherwise, the code in the else clause is executed.
Here is an example of a simple if else statement:
Bash
#!/bin/bash
# Check if the file exists
if [ -f myfile.txt ]; then
# File exists, so print its contents
cat myfile.txt
else
# File does not exist, so print a message
echo "File myfile.txt does not exist."
fi
Use code with caution. Learn more
This if else statement will check if the file myfile.txt exists. If the file exists, then the code in the then clause will be executed, which will print the contents of the file. Otherwise, the code in the else clause will be executed, which will print a message saying that the file does not exist.
If else statements can also be nested to create more complex conditional logic. For example, the following if else statement will check if the file myfile.txt exists and if the file is empty. If the file exists and is not empty, then the code in the then clause will be executed, which will print the contents of the file. Otherwise, the code in the else clause will be executed, which will print a message saying that the file either does not exist or is empty.
Bash
#!/bin/bash
# Check if the file exists and is not empty
if [ -f myfile.txt ] && [ -s myfile.txt ]; then
# File exists and is not empty, so print its contents
cat myfile.txt
else
# File either does not exist or is empty, so print a message
echo "File myfile.txt either does not exist or is empty."
fi
Use code with caution. Learn more
If else statements are a powerful tool for controlling the flow of execution in Bash scripts. By using if else statements, you can write scripts that can handle a variety of different conditions.
Show More Show Less 