UNIX Tutorials, Tips, Tricks and Shell Scripts

7 Key Concepts to Start with if you want to Learn UNIX Shell Scripting


Learning Shell Scripting

When you need to pick up a new skill or technology, like learning shell scripting, the amount of material that you have to select from can be overwhelming to a newcomer. Where do I start? What concepts will I most likely need to know right away and which ones can be left for later on?

This guide to shell scripting for beginners was written to answer questions like these, and includes shell script examples to help you better understand each concept covered.


(1) Shell Scripting Basics

If you're just starting out it is good to begin with shell scripting basics, like how to write and run a shell script. LiveFire Labs UNIX Shell Scripting Tutorial - The Basics for Beginners covers these concepts in detail.

If you're wondering what exactly is a shell script, how to write a script, what are the fundamental components to a basic script, how to make a script display (or print) something to standard output, and what needs to be done so the script can be executed then it would be good to read through the basics for beginners tutorial above before proceeding.

As stated in the basics tutorial, reading about shell scripting is a good place to start but there is absolutely NO substitute to actually writing and running your own scripts if you want to learn UNIX shell scripting.


(2) How to Access Shell Variables

A variable is a symbol or name representing a value. As indicated by its name, the value of a variable is subject to change. The UNIX shell variables can be displayed by running "env" from the UNIX command line prompt. Here is a snippet (an excerpt) from "env" command output:

$ env
HISTFILE=/home/lfl/.history
PATH=/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin
SHELL=/bin/ksh
HOSTNAME=livefirelabs.com
USER=lfl
MAIL=/var/spool/mail/lfl
HOME=/home/lfl
HISTSIZE=1000

If you wanted to display the value of a single shell variable, HOSTNAME for example, you could do the following at the command line prompt:

$ echo $HOSTNAME
livefirelabs.com
$




Accessing the shell variable HOSTNAME from within a shell script would not be much different as seen in this simple shell script example:

#!/bin/ksh
#This shell script example accesses and displays the variable HOSTNAME
print "The value of the shell variable HOSTNAME is $HOSTNAME"
exit 0

SAMPLE RUN:
$ /bin/ksh ./script2
The value of the shell variable HOSTNAME is livefirelabs.com
$

(3) How to use Shell Script Arguments

Another method for a shell script to access data is through the use of shell script arguments. If you have worked UNIX operating system commands, then it's likely that you have utilized command line arguments that get passed to a particular UNIX command. For example, when copying a file the UNIX copy command (cp) uses source and destination arguments as seen in this example:

$ cp filename1 filename2

Here is a shell script example that illustrates passing arguments that can be used within the script. (Notice that the arguments are saved off to new variable names within the shell script.)

#!/bin/bash
#This shell script example demonstrates the use of shell script arguments
shell_arg1=$1
shell_arg2=$2
echo "the first shell argument was $shell_arg1"
echo "the second shell argument was $shell_arg2"
exit 0

SAMPLE RUN:
$ /bin/bash ./script3 hi there
the first shell argument was hi
the second shell argument was there
$

The first command line argument "hi" is accessed by the shell script via $1, and is saved to a the new variable shell_arg1. Similarly, the script uses $2 to access "there" (the second command line argument) and stores it in the variable shell_arg2 for subsequent use.


(4) The UNIX Test Command

The UNIX test command evaluates an expression and returns a code indicating whether the expression is true or false. If the expression is true, a 0 (zero) is returned. If it is false, a 1 (one) is returned.

The test command can be ran using two different formats:

test expression

or

[ expression ]

In shell scripts, the second format is used more often. The test command can be used to perform many different tests including:

· numeric comparisons
· the existence and type of a file
· the equality of two strings

Our shell script example for this topic incorporates the use of shell script arguments that were covered in the previous section. In this example, the -f option is used to check if the file exists and is a regular file. (HINT: Run "man test" at the UNIX command prompt to see what test command options are available to use within your shell scripts.)

#!/bin/ksh
#This shell script example demonstrates use of the test command to check if file exists
filename=$1
if [ -f $filename ]
then
echo "$filename exists"
fi
exit 0

SAMPLE RUN:
$ ./script4 script2
script2 exists
$

It's obvious that this shell script example is not very robust since it does not handle the scenario when a file does not exist,..

SAMPLE RUN:
$ ./script4 script222
$

...but we'll cover that case in the next topic.



(5) The Shell Script if Statement

The shell script if statement, as seen in the shell script example from the UNIX test command section, is used to execute one or more commands when an expression is evaluated as true. The general format of a simple if statement is:

if expression
then
command(s)
fi

The command(s) will only be executed if the expression is evaluated as true. If the expression is evaluated as false, the program will skip over the command(s) and continue after the fi. You must terminate each if statement with fi (if spelled backwards).

Consider this example:

if expression
then
command1
else
command2
fi

It should be obvious that an else statement has been added to the if statement from above. If the expression is evaluated as false, command1 will be skipped and the else code path will be taken. This means that command2 will be executed, and then the shell script will continue after the fi.

Building on our shell script example from the previous section, the script now handles the scenario of when a file does not exist.

#!/bin/ksh
#This shell script example demonstrates use of the if statement
filename=$1
if [ -f $filename ]
then
echo "$filename exists"
else
echo "$filename does NOT exist"
fi
exit 0

SAMPLE RUN:
$ ./script5 script2
script2 exists
$

$ ./script5 script222
script222 does NOT exist
$

(6) The Shell Script for Loop

A loop structure is a programming mechanism for repeating a series of commands. The three loop structures used in shell script programming is the while loop, the until loop, and the for loop. The often used shell script for loop will be introduced here.

The for loop is executed one iteration for each element contained in a specified list. The syntax of the for loop is:

for variable-name in list
do
command(s)
done

The value for variable-name can be whatever you select, but the letter i is commonly used. The values for list can be filenames, command names, or a list of numbers or letters. Below is an example of a for loop:

for i in script1 script2 script3
do
echo $i
chmod u+x $i
done

Each file in list (script1, script2, script3) will be echoed to the screen, and then will be made executable for the file's user (owner) with the UNIX chmod command.


(7) Shell Script Return Code

Return codes were discussed in the "Exiting a Shell Script" section of UNIX Shell Scripting Tutorial - The Basics for Beginners, but it's also good to see return code usage within a shell script example.

Building again on the shell script used throughout this article, echo statements have been added to display the return code from the test command operation. Although it's not demonstrated here, it would be easy to add conditional statements to perform certain actions based on the value of the return code.

#!/bin/ksh
#This shell script example demonstrates use of the return code
filename=$1
if [ -f $filename ]
then
echo "return code from test command was $?"
echo "$filename exists"
else
echo "return code from test command was $?"
echo "$filename does not exist"
fi
exit 0

SAMPLE RUN:
$ ./script7 script2
return code from test command was 0
script2 exists
$

$ ./script7 script222
return code from test command was 1
script222 does not exist
$

Notice that a 0 (zero) was returned by the test command [ -f $filename ] to indicate success (the file was found), and 1 was returned from the test command to indicate failure (the file was not found).

Hopefully, you have found this article about what to focus on when you want to learn UNIX shell scripting to be useful and informative. When learning shell scripting, there is no substitute to writing and running your own scripts on a real system. A great way to get started is to copy, paste and run the shell script examples used in this article.

There is also a very good introduction to shell scripting module in our UNIX and Linux Operating System Fundamentals online course if you are new to the UNIX and Linux operating system environments, or you may want to consider taking a dedicated UNIX Shell Scripting course if you are already familiar with UNIX/Linux and just need to learn more about shell scripting and the UNIX shell in general.

Both courses include access to LiveFire Labs global lab for working on the course's concept-reinforcing lab exercises, which has always been a very popular feature with our students. Thanks for reading and happy scripting!!!