If-Then-Else Loop and Variables in Bash

Problem

Create an If-Then loop in Bash.

tl;dr

#!/bin/bash
var=VALUE
if test $var = VALUE
then
    DO SOMETHING
else
    DO SOME OTHER THING
fi

Solution

For a simple scripting language, bash is surprisingly powerful. It's also a lot easier to use than Microsoft's Batch scripting language.

Creation and execution of a Bash file is covered other tutorials linked at the bottom of the page.

Bash is used mainly for automation of tasks. For example, you may have to backup a folder on a regular basis and save it as "/usr/backup/today's_date". However, you only need to perform the backup if anything inside it has been modified.

If-Then Loop Format

An If-Then Loop has the following format in UNIX Bash:

#!/bin/bash
var=VALUE
if test $var = value
then
    DO SOMETHING
else
    DO SOME OTHER THING
fi

Variable

A variable is defined as such when it is given a value, such as var=VALUE. It is called by placing a $ sign before it's name, such as $var.

Initial condition

if test $var = VALUE is the initial condition. It checks if var = VALUE and proceeds to steps in Then if the condition is true or steps in Else if the condition is false.

For a DOES NOT EQUAL check (var ≠ VALUE), use an exclamation mode before the variable in the initial condition:

if test ! $var = VALUE_2

This does something if var does not equal to VALUE

End of loop

Put fi after the last command of your loop.


Was this article helpful?

mood_bad Dislike 0
mood Like 0
visibility Views: 4200