IF statements

Introduction to Bash Scripting

Alex Scriven

Data Scientist

A basic IF statement

A basic IF statement in Bash has the following structure:

if [ CONDITION ]; then

# SOME CODE
else # SOME OTHER CODE
fi

Two Tips:

  • Spaces between square brackets and conditional elements inside (first line)
  • Semi-colon after close-bracket ];
Introduction to Bash Scripting

IF statement and strings

We could do a basic string comparison in an IF statement:

x="Queen"

if [ $x == "King" ]; then
echo "$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'

Introduction to Bash Scripting

Arithmetic IF statements (option 1)

Arithmetic IF statements can use the double-parentheses structure:

x=10

if (($x > 5)); then echo "$x is more than 5!" fi
10 is more than 5!
Introduction to Bash Scripting

Arithmetic IF statements (option 2)

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'
Introduction to Bash Scripting

Arithmetic IF statement example

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!
Introduction to Bash Scripting

Other Bash conditional flags

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 writable

And a variety of others:

Introduction to Bash Scripting

Using AND and OR in Bash

 

To combine conditions (AND) or use an OR statement in Bash you use the following symbols:

  • && for AND
  • || for OR
Introduction to Bash Scripting

Multiple conditions

In 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
Introduction to Bash Scripting

IF and command-line programs

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!
Introduction to Bash Scripting

IF with shell-within-a-shell

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

Let's practice!

Introduction to Bash Scripting

Preparing Video For Download...