Copyright

Practical Application for Introduction to Linux: Programming Statements in Bash

Instructor: Alexis Kypridemos

Alexis is a technical writer for an IT company and has worked in publishing as a writer, editor and web designer. He has a BA in Communication.

This lesson explains how to use conditional statements and loops in the Linux Bash shell language. Examples are provided for if, else, and elif conditional statements, and for and while loops.

Lesson Overview & Knowledge Required

Conditional Statements, or conditionals in computer programming, allow for creating programs that execute commands depending on whether or not a condition is true. The most common conditionals are the if, else, and else if statements. This lesson will cover how to use these tools in Linux Bash.

Required knowledge: able to use a Linux Bash terminal / command line interface application. Tip: if it is not possible to use a physical or virtual machine with a Bash terminal, there are free online emulators that allow you to enter and execute commands.

If, Else and Else If

If Conditional

The if conditional checks whether or not a particular condition is true and executes the command(s) only if the condition is true. The following example program executes a command only if the current day is Friday. To see this work, type the following into a Linux terminal, pressing Enter after each line:


DOW=$(date +%A)
if [ $DOW = 'Friday' ]; then
echo $DOW
fi


Line by line explanation:

DOW=$(date +%A) - DOW, an arbitrary name for a variable to hold the current day of week. $ specifies what follows in parentheses is the variable's value. (date +%A) is Bash's built-in way of getting the current day of the week. Important: spaces in a bash command are significant. If you write this statement as DOW=$(date + %A), with a space after the plus sign, it will not work.

if [ $DOW = 'Friday' ]; then - The if conditional. Checks if the $DOW variable (variables in Bash are distinguished by the $ sign before their name) value is ''Friday''. Important: the spaces inside the brackets ([ ]) and on either side of the = sign are required. If written like this: [$DOW='Friday'], the statement will not work. The last part of the statement, ; then, sets up the command on the following line, telling the program what to do if the current day is Friday.

echo $DOW - The echo command displays the $DOW variable's value (current day of week) on screen.

fi - Closes the ''if'' statement. Pressing Enter after this runs the program. If the current day is Friday, the program displays ''Friday'' in the terminal. Otherwise, the program does not execute any commands.

Generalizing, the Bash 'if' structure is:

if [ the condition to check ]; then
the command(s) to execute
fi

Else Conditional

Else conditionals tell programs to do something when an ''if'' condition is not met. The next example expands on the previous one, displaying 'Today is not Friday' on all other days of the week.


DOW=$(date +%A)
if [ $DOW = 'Friday' ]; then
echo $DOW
else
echo 'Today is not Friday'
fi


The structure is almost identical to the above, but includes two new lines:

else - The else conditional; sets up the program for the command to execute on all other days of the week.

echo 'Today is not Friday' - Similar to the first example, the echo command, followed by the text to display in single quotes. Note: in the Bash terminal language, it does not matter whether you use single or double quotes. The one exception is when you have a single quote inside the double quotes. For example, to echo ''Today isn't Friday'' you would need to use double quotes around the text to display.

Else conditionals only work when combined with if statements. The general else structure is:

if [ condition to check ]; then
do something
else
do something else
fi

Else If Conditional

Else if (elif in Bash) conditionals tell programs to check for an additional condition to the 'if' as in this example:


DOW=$(date +%A)
if [ $DOW = 'Friday' ]; then
echo $DOW
elif [ $DOW = 'Thursday' ]
then
echo 'Today is almost Friday!'
else
echo 'Today is not Friday'
fi


Explanation:

elif [ $DOW = 'Thursday' ] - elif, the else if statement in Bash. Notice there is no semi-colon (;) after the brackets.

then - 'then' must be on a new line

echo 'Today is almost Friday!' - the new command.

General Bash elif (else if) structure:

if [ condition to check ]; then
do something
elif [ other condition to check ]
then
do something else
else
do this in all other situations
fi

Please note: There is no limit to the number of 'elif' statements that can be added after an 'if', nor is the 'else' necessary, though it's recommended.

Introduction to Loops

Loops are programming structures that allow programs to perform repetitive tasks. Like conditionals, virtually all programming languages include ways of using loops. The most common types of loops are for, for each, and while.

For and For Each Loops

In other programming languages, 'for' and 'for each' loops are expressed in two different ways. In Bash, they are considered two different types of 'for' loop.

A standard Bash for loop repeats a command for each value in a list of values. In other languages, this would be called a 'for each' loop.

Example:


list='one two three four five'
for listItem in $list
do
echo $listItem
done


Explanation:

list='one two three four five' - As in the ''if'' example, 'list' is a variable that contains multiple values ('one two three four five'), each value separated by a space.

for listItem in $list - New variable listItem is defined as a single value from the previously defined list variable

do - sets up the program for the command on the next line

echo $listItem - displays each of the list values, one after the other.

done - Ends the loop.

General 'for' structure:

for variable in another variable that holds multiple values
do
command
done

What in other programming languages would be a standard 'for' loop, in Bash is a 'for' loop for a range of values. This is particularly useful if you want to loop through the statements a certain number of times, or are looping based on a numeric value, as below:

Example:


for decade in {1948..2018..10}
do
echo $decade
done


Explanation:

for decade in {1948..2018..10} - Defines a variable named decade holding values between 1948 and 2018. Also tells the loop to move through the values 10 at a time. Important: The syntax here is strict: the two ends of the range (1948 and 2018) are separated by two dots (..) and are inside curly brackets ({}). The 'step' by which to count through these numbers is separated by another two dots after the second value (second value..step). There are no spaces in this expression!

do - Same as previous example.

echo $decade - displays one value for every ten (e.g. 1948, 1958, etc.).

done - Closes loop.

General structure:

for variable in {beginning of range..end of range..step}
do
command
done

While Loops

A while loop repeats a command while a condition is true.

Example:


variable='0'
while [ $variable -lt 10 ]
do
((variable++))
echo $variable
done


Explanation:

variable='0' - Defines the variable with name 'variable', giving it an initial value of 0.

while [ $variable -lt 10 ] - The 'while' condition. This statement means 'while the variable is less than 10'. Again, note the spaces inside the brackets ([]). In many programming languages, 'less than' is expressed as '<'. In Bash it is '-lt'.

do - The set-up for the commands. In contrast to previous examples, this structure contains two commands.

To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account
Support