While Loops (Shell Scripting)

Shell scripting is a very basic method method of programming in Linux/UNIX. Its primary appeal is the speed at which a program can be created and used. It is not an efficient language, and should not be used if execution speed is essential.

Quick Facts

  • Platform(s): Linux, UNIX, MacOS X, Solaris, and others
  • Language Type: Interpreted

List of Concepts

Comments

Comments in shell script are denoted using a # sign at the beginning of the comment. Everything after the # sign is ignored by the interpreter.

#!/bin/bash

echo "Hello World"
# This line will be ignored
echo "Goodbye World"

Echo

Echo is the method of printing to standard output in a shell script. It accepts an unimited number of arguments, printing each one to the screen.

Standard Usage is:

#!/bin/bash

echo Cool Beans

The output from echo can be easily redirected into a file using the > operator:

#!/bin/bash

echo Cool Beans > MyCoolFile.txt

If you wanted to immediately trash the output, you can do so by redirecting the output to /dev/null

#!/bin/bash

echo This will not show up on the screen > /dev/null

Environment Variables

Environment Variables are a type of global variable in shell scripts that are always available to the programmer. They are summarized in the following table:

Environment Variable Variable Description
$HOME The home directory of the current user.
$PATH A semi-colon delimeted list of all paths that the shell will search when looking for an executable file.
$PS1 A variable containing the symbol(s) that will be shown at the primary command prompt
$PS2 A variable containing the symbol(s) that will be shown at the secondary command prompt
$IFS A list of characters that the shell considers as delimeters when reading parameters to a program call. Usually contains a space, a tab, and a newline character.
$0 The name of the current shell script, in the context of how it was invoked.
$# The number of parameters passed to the current shell script
$1-$[#] The parameters passed into the program.
$$ The PID (process ID) of the current script.

The following code demonstrates the use of some of these variables:

#!/bin/bash

echo "You provided $# parameters to this program"
echo "This process's PID is $$"
echo "Your home folder is: $HOME"

The output of the following program is:

$ ./snippetProgram.sh cool beans
You provided 2 parameters
This process's PID is 9002
Your home folder is /home/stargazer

For loop

A for loop in a shell script takes on a different appearance than for loops in many other languages, but ends in the same result.

When declaring the for loop, an index value is provided, and the index successively takes on each value in the list until the end of the list. This is demonstrated by:

#!/bin/bash

for index in 1 2 3 4 5
do
    echo $index
done

This output of the preceding code would simply be:

1
2
3
4
5

By combining a for loop with the 'seq' command, you can avoid the effort of typing every entry in the list:

#!/bin/bash

for i in $(seq 1 100)
do
    echo $i
done

You can also execute commands within the list of a for loop to get some useful results. The following snippet prints the name of each file in the users home directory:

#!/bin/bash

for i in $(ls $HOME)
do
    echo $i
done

or using an alternate syntax:

#!/bin/bash

for i in `ls $HOME`
do
    echo $i
done

If-else

Shell scripts use fairly standard syntax for if statements. The conditional statement is executed using either the test command or the [ command. In its most basic form an if statement is:

#!/bin/bash

if [ "$#" -gt 0 ]
then
    echo "There's Beans"
fi

if [ "$1" = "cool" ]
then
echo "Cool Beans"
fi

(Notice that the fi is simply if spelled backwards). To add an else, we just use standard syntax.

#!/bin/bash

if [ "$1" = "cool" ]
then
    echo "Cool Beans"
else
    echo "Not Cool Beans"
fi

Adding an else-if statement structure is used with the elif command.

#!/bin/bash

if [ "$1" = "cool" ]
then
    echo "Cool Beans"
elif [ "$1" = "neat" ]
then
    echo "Neato cool"
else
    echo "Not Cool Beans"
fi

An if statement does not require two parameters. You can use single flags as well. The following code tests to see if the first parameter is a file or not.

#!/bin/bash

if [ -f "$1" ]
then
    echo "$1 is a file"
else
    echo "$1 is not a file"
fi

There are many different ways that an conditional statement can be used. These are summarized here:

String Comparison Description
Str1 = Str2 Returns true if the strings are equal
Str1 != Str2 Returns true if the strings are not equal
-n Str1 Returns true if the string is not null
-z Str1 Returns true if the string is null
Numeric Comparison Description
expr1 -eq expr2 Returns true if the expressions are equal
expr1 -ne expr2 Returns true if the expressions are not equal
expr1 -gt expr2 Returns true if expr1 is greater than expr2
expr1 -ge expr2 Returns true if expr1 is greater than or equal to expr2
expr1 -lt expr2 Returns true if expr1 is less than expr2
expr1 -le expr2 Returns true if expr1 is less than or equal to expr2
! expr1 Negates the result of the expression
File Conditionals Description
-d file True if the file is a directory
-e file True if the file exists (note that this is not particularly portable, thus -f is generally used)
-f file True if the provided string is a file
-g file True if the group id is set on a file
-r file True if the file is readable
-s file True if the file has a non-zero size
-u True if the user id is set on a file
-w True if the file is writable
-x True if the file is an executable

Read

The read command is the command in shell scripting for reading from standard in. In its most basic form, you can merely prompt the user for input.

#!/bin/bash

echo "Please enter your name"
read name
echo "Hello, $name. How are you?"

For more advanced usage, you can use it in a while statement to read data from standard input line-by-line.

#!/bin/bash

while read line
do
    echo "The next line from standard in is: $line"
done

The output of the above script is shown here:

$ cat TestFile
Cool Beans
This is
a test.

$ cat TestFile | ./TestScript.sh
The next line from standard in is: Cool Beans
The next line from standard in is: This is
The next line from standard in is: a test.

Quotes

The two types of quotes in shell scripts are single quotes ' and double quotes ". Both are used whenever you want to include spaces in a given parameter or expression. The difference is that double quotes have variable replacement while single quotes do not. For example, given the following code…

#!/bin/bash

myvar=7

echo "Myvar is $myvar"
echo 'Myvar is $myvar'
echo Myvar is $myvar

…the result is…

Myvar is 7
Myvar is $myvar
Myvar is 7

Variables

Variables in shell scripts are very basic methods of storing information. They are always stored as strings, however different commands can treat them as numbers. Variables are created using the equal sign, and they are referenced by using a dollar sign.

#!/bin/bash

myvar=value
echo $myvar

A variable has scope within the process in which it is run. When the process is ended, its variables are deleted. In addition, when a sub process is started, the sub process will not have knowledge of any variables within its parent process. This can be changed however, by using the export command as follows:

#!/bin/bash

export myvar=value

While Loops

While loops in shell scripting are fairly standard compared to other programming languages. An example of their use is:

#!/bin/bash

i = 0

while i != 10
do
    i = `expr i + 1`
done

You can also combine a while loop with the read command in order to read from standard input.

#!/bin/bash

while read line
do
    echo "The next line from standard input is: $line"
done
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License