Programming in Bash can be fun at times.

Find out how get your Bash conditionals right.

For example, one could test if a variable is empty or not.

The main page of the Homepage homelab dashboard with services running on it.

To learn more about Bash variables, you may like to review ourBash Functions and Local Variablesarticle.

Bash is a full-blown Linux shell, and a comprehensive programming language.

It also includes many extensions to the more common conditional statements within it’s scripting/programming language.

Article image

Additionally, one can specify complex conditional statements, and even subshells right inside theifetc.

This makes Bash very suitable for big data wrangling/mangling, text parsing and many other DevOps-like tasks.

This article will focus mainly on getting the conditionals right, using

,else, andelifstatements.

Simple if example in Bash

A future article will look at more complex test conditions, using subshells inside conditional statements etc.

Note that the way to test equality between to items is to use==and not=.

Note also that we terminate each conditionalifstatement with a terminatingfi(the reverse ofif) statement.

In-script if example using variables and an else clause

This allows us to specify multiple lines after thenthenclause before terminating thethen section.

Inside the script we setVAR1andVAR2to the value of 1.

The result is a correcttrueoutput.

A more complex inequality if statement which also tests script variables

We make our script executable again, and execute it with various wrong option combinations.

The-zcode stands forcheck if a parameter is empty or not.

We negate the result (i.e.

elif conditional statement example with two different implementations

in front of the-zcheck.

We then also use anANDclause (i.e.

both sides of theANDclause have to prove true).

In other words, the way that you could read theif [ !

Finally, inside the firstifconditional statement, we have a secondary (computer jargon:nested) conditional statement.

This statement does our inequality check by usingnot equal(!=).

Often, though not always, one can use anelifstatement in such cases.

We see that the two blocks work exactly the same.

Note that you might also combineelseandelifstatements in combination, in a nested fashion etc.

Creating well crafted conditional statements is an integral and commonplace part of this.

In this short tutorial, we looked atif,then,else,elifandfistatements.

Using the various conditional statements you will be able to create great and clean code.Enjoy!