Introduction to Bash Scripting
Alex Scriven
Data Scientist
A basic IF statement in Bash has the following structure:
if [ CONDITION ]; then# SOME CODEelse # SOME OTHER CODEfi
Two Tips:
];We could do a basic string comparison in an IF statement:
x="Queen"if [ $x == "King" ]; thenecho "$x is a King!"else echo "$x is not a King!" fi
Queen is not a King!
You could also use != for 'not equal to'
Arithmetic IF statements can use the double-parentheses structure:
x=10if (($x > 5)); then echo "$x is more than 5!" fi
10 is more than 5!
Arithmetic IF statements can also use square brackets and an arithmetic flag rather than (>, <, =, != etc.):
-eq for 'equal to'-ne for 'not equal to'-lt for 'less than'-le for 'less than or equal to'-gt for 'greater than'-ge for 'greater than or equal to'Here we re-create the last example using square bracket notation:
x=10
if [ $x -gt 5 ]; then
echo "$x is more than 5!"
fi
10 is more than 5!
Bash also comes with a variety of file-related flags such as:
-e if the file exists-s if the file exists and has size greater than zero-r if the file exists and is readable-w if the file exists and is writableAnd a variety of others:
To combine conditions (AND) or use an OR statement in Bash you use the following symbols:
&& for AND|| for ORIn Bash you can either chain conditionals as follows:
x=10
if [ $x -gt 5 ] && [ $x -lt 11 ]; then
echo "$x is more than 5 and less than 11!"
fi
Or use double-square-bracket notation:
x=10
if [[ $x -gt 5 && $x -lt 11 ]]; then
echo "$x is more than 5 and less than 11!"
fi
You can also use many command-line programs directly in the conditional, removing the square brackets.
For example, if the file words.txt has 'Hello World!' inside:
if grep -q Hello words.txt; then
echo "Hello is inside!"
fi
Hello is inside!
Or you can call a shell-within-a-shell as well for your conditional.
Let's rewrite the last example, which will produce the same result.
if $(grep -q Hello words.txt); then
echo "Hello is inside!"
fi
Hello is inside!
Introduction to Bash Scripting