Shell Programming

The shell is an intermediary program, which interprets the commands that are typed at the terminal, and translates them into commands that the kernel understands.

Why shell programming?

Even though there are various graphical interfaces available for Linux the shell still is a very neat tool. The shell is not just a collection of commands but a really good programming language. We can automate a lot of tasks with it, the shell is very good for system administration tasks, we can very quickly try out if our ideas work which makes it very useful for simple prototyping and it is very useful for small utilities that perform some relatively simple tasks where efficiency is less important than ease of configuration, maintenance and portability.

Login process

On switching on a Linux machine, the kernel program is first loaded into memory from the hard disk. This program triggers a chain of initialization processes at the end of which login prompt appears. On entering a valid login and password the process named Bourne shell or the C shell (called login shell) is activated. So let’s see now how it works

Creating a script

There are a lot of different shells available for Linux but usually the bash (bourne again shell) is used for shell programming as it is available for free and is easy to use. So all the scripts we will write in this article use the bash (but will most of the time also run with its older sister, the bourne shell). For writing our shell programs we use any kind of text editor, e.g. nedit, kedit, emacs, vi…as with other programming languages. The program must start with the following line (it must be the first line in the file)

!/bin/sh

The #! Characters tell the system that the first argument that follows on the line is the program to be used to execute this file. In this case /bin/sh is shell we use. When we have written our script and saved it we have to make it executable to be able to use it. To make a script executable type

chmod +x filename

Then we can start our script by typing: ./filename

Comments

Comments in shell programming start with # and go until the end of the line. We really recommend using comments. If we have comments and we don’t use a certain script for some time we will still know immediately what it is doing and how it works.

Variables

As in other programming languages we can’t live without variables. In shell programming all variables have the datatype string and we do not need to declare them. To assign a value to a variable we write:

varname=value

To get the value back we just put a dollar sign in front of the variable:

!/bin/sh

Assign a value:

a="hello world"

Now print the content of “a”:

echo "A is:"
echo a

Type this lines into our text editor and save it e.g. as first. Then make the script executable by typing chmod +x first in the shell and then start it by typing ./first The script will just print:

A is:
hello world

Sometimes it is possible to confuse variable names with the rest of the text:

num=2
echo "this is the $numnd"

This will not print “this is the 2nd” but this is the because the shell searches for a variable called numnd which has no value. To tell the shell that we mean the variable num we have to use curly braces:

num=2
echo "this is the ${num}nd"

This prints what we want: this is the 2nd There are a number of variables that are always automatically set. We will discuss them further down when we use them the first time. If we need to handle mathematical expressions then we need to use programs such as expr. Besides the normal shell variables that are only valid within the shell program there are also environment variables. A variable preceded by the keyword export is an environment variable. We will not talk about them here any further since they are normally only used in login scripts.

Exporting Variables

By default, variables defined within a shell are local to it. Any process/command executed by that shell will not get access to these variables, unless they are exported to the environment.

export VARNAME

This export includes changes to existing variables that are in the path. For example, if we wish to modify the PATH environment variable we would:

PATH=$PATH: additional_directory
export PATH

Positional (Parameter) Variables

When the shell script is run, any command line parameters to the shell are provided by a set of shell variables $0 $1 $2 $3 $4 $5 $6 $7 $8 and $9. $0 (or ${0}) contains the name of the shell script itself, and depending on how the shell was called, may contain the full path to the command. If there are more than 9 parameters/arguments to the script, then they are accessed using the shift command which shifts all the parameters ($1=$2, $2=$3 etc) with $9 getting the next parameter in the line ($0 is unaffected). $# is a variable that contains the number of command line parameters.

$* and $@ can be used to get all the parameters in one go. Very useful for passing the complete command line parameter set to a child process

Example

!/bin/sh

A wrapper for the GNU C compiler that has the debug flag set

gcc -g $*

Write these lines in a file

Example

Echo “First argument is $1”
Echo “Second argument is $2”
Echo “The  Total number of  arguments are $#”
Echo “The  list of arguments are $*”
Echo “The pid of the current process is $$”
Echo “The  name of the file where we written this program is $0”
Echo “The exit status of last command $?”

Result

Execute the above program using some command line arguments like

sh <filename>  1 2 3 4 5

shift: Shifts Parameters

When a large number of parameters (;SPMgt; 9) are passed to the shell, shift can be used to read those parameters. If the number of parameters to be read is known, say three, a program similar to the following could be written:

!/bin/sh
echo The first parameter is $1.
shift
echo The second parameter is $1.
shift
echo The third parameter is $1.
exit 0

read: Reading Input from User

The following short example shows how read can be used to get input from the user:

#!/bin/sh
echo -e "Please enter your name: \c"
read NAME
echo "Your name is $NAME."
exit 0

The \c means that the line feed will be suppressed, so that the prompt sits at the end of the line, not at the beginning of the following line. Two more common controls available to the echo command are to use \n to add a line feed, and \t to add a tab. Multiple values may be read on a single line by using:

!/bin/sh
echo -e "Please enter two numbers: \c"
read NUM1 NUM2
echo The numbers entered are $NUM1 and $NUM2
exit 0

This ensures that if two numbers are entered on a single line, they will be read within two variables. If three numbers were entered, the second variable (NUM2) would contain the last two numbers. Assuming three numbers were the input of the above example, the first two numbers could be assigned to the first variable by entering them as

num1 \num2 num3

The backslash () allows the blank space between num1 and num2 to be part of the variable (ordinarily, spaces are used as field separators

Subscribe For More Content