Shell Scripts

Introduction

If a group of commands or command list are used frequently, such list of commands can be stored in a file so that they are analyzed and executed by a shell as a single entity.

A file containing such command names is called a shell script.

Shell scripts are text files and can be created with an editors like vi, emacs, pico etc.

Creating & Executing

A Shell can be executed in two forms:

  1. sh scriptname
  2. scriptname (only when the execute permission of the shellscript is enabled)

$ ls -l
-rwxr-xr-x   1   shelluser  shellgroup   Dec 10 01:22   shellscript

Example:
Creating and executing a shell script named script1 that executes pwd and ls commands
$ pico script1
pwd
ls                        Quit the editor with Ctrl-X

Now run the script as:
$ sh script1
/home/kundan                   — Result of pwd execution
TEST   Maildir   mbox     — Result of ls execution
If the execute permission of the script is enabled then the script can also be run merely by specifying its pathname.
You can enable the execute permission by issuing the chmod command:
$ chmod +x script1
After enabling the execute bit of the file, the script can be run as:
$ ./script1

Note: Shell scripts may contain comment lines. To code a comment line, place a # symbol before the comment line.

#Shell Script to display the pwd and ls command
pwd     #Displays the current directory
ls         #Displays the list of directories and files in the current directory

Parameters

Shell scripts can contain parameters that are equivalent to variables in a program.
Types of Parameters:

  • Positional Parameters
  • Shell Variable
  • Special Parameter

By using these types of parameters, the user can create and run program-equivalent files without the use of programming language.

Positional Parameters

The user can specify arguments in a shell script at run time as in ordinary commands. The shell script uses positional parameters as parameters for receiving those arguments.

$ sh scriptname [arg1 arg2 ………….. argn]

$0           $1     $2  ………..            $n

A positional parameter is represented by a $ symbol followed by a number (0-9) that identifies the ordinal position of the parameter.

Example:

Running shell script script2 that examines the contents of the parameters specifying two arguments

Contents of script2

echo $0

echo $1

echo $2

Execute the shellscript script2

$ sh script2 param1 param2

script2

param1

param2                                                  Execution Result

Shell Variables

Shell variables are similar to variables in a program. They are used to define and change values in shell scripts.

a)      Shell variable naming conventions

  • A shell variable must begin with a letter or underscore
  • A shell variable must be a combination of letters, digits and underscores

b)      Assigning a value to a shell variable

shellvariable = value

c)      The value of a shell variable is referenced by prepending a $ symbol to the variable name.

$shellvariable

Example:

Defining and displaying the value of variable admin in a shell script to string administrator

Contents of script3

admin=administrator

echo This training is for system $admin

Run the Script

$ sh script3

This training is for system administrator

Special Parameters

Special Parameters are automatically passed by the system for the user to use them to establish his or her execution environment.

Major Special Parameters:

a)      HOME

Holds the path name of the home directory of currently logged user

b)      PATH

Holds a list of path names of directories that shell programs frequently searches for commands. Since commands are stored in various directories, their path names are separated by colons. Eg: /bin:/usr/bin:/usr/local/bin

c)      PS1

Holds the primary prompt symbol. The default value of PS1 is a $ symbol and a space.

Escape Symbols

If the user wants to handle characters that have special meaning to a shell as ordinary characters in a string to be given as a command argument, it is necessary to escape them.

‘(single quotation): String enclosed in single quotation marks are escaped except the quotation mark.

“(double quotation): String enclosed in double quotation marks are escaped except parameter values and the quotation mark.

\single-character: All single-characters following a backslash (\) are escaped.

The above symbols escape the characters that are handled by a shell as special characters. The characters that a shell handles as special characters include the following:

; & | ( ) ^ < > ? * [ ] space newline

Example:

* echo ‘?message?’                             handling a ? which the shell regards as a special character as an ordinary character

Execution Result: ?message?

* echo ‘e  n  d’                                    To include  two or more spaces in a message, enclose them with single quotatios

Execution Result: e  n  d

* echo “*$HOME*”                           When displaying * as an ordinary character and replacing the variable with its value

Execution Result: */home/kundan*

* echo \\111                                         To handle a backslash as an ordinary character, specify two backslashes consecutively.

Execution Result: \111

Commands

  1. echo command

<<General Format>>

echo [arg1 arg2…… argn]

The echo command echoes the string specified in arguments on the standard output as is. It is used to display messages during the execution of shell scripts.

Example:

Displaying messages at the beginning and end of a shell script

Contents of script4

echo –start of a program-

pwd

ls

echo –end of a program-

Run

$ sh script4

-start of a program-

/home/kundan

TEST   Maildir   mbox

-end of a program-

  1. 2. read command

<<General Format>>

read shellvariable

The read command enables a value to be assigned to a shell variable not within a shell script but from the standard input at run time.

Example:

Shell script script5 assigns a value read from the standard input to shell variable X after displaying a message and extracts the lines that contain the value of shell variable X as the search string from the file specified in $1.

Contents of script5

echo input value of pattern

read x

grep “$x” $1

Run

$ sh script5 /etc/passwd

input value of pattern

^muk                                       waits for a value from the keyboard

mukesh:x:501:502:/home/mukesh:/bin/bash

mukunda:x:503:502:/home/mukunda:/bin/bash

Note: The user can suppress a newline by using the escape symbol “\c” after displaying a message with an echo command. This escape symbol must be enclosed in single quotes. The similar can be done using “-n” option.

Eg:

echo “Input value of pattern ‘\c’

read X

OR

echo –n “Input value of pattern”

read X

  1. 3. Control Commands

Some shell command control the execution of shell scripts. Such commands include decision making commands and iteration control commands.

  1. Decision Making Commands
    1. I.      if command
    2. II.      case command
  2. Iteration Control Commands
    1. I.      for command
    2. II.      while command

a) Decision Making Commands

  1. I.

    When if commands are nested

    if list of conditions

    then

    list1

    elif list of conditions

    then

    list1

    else

    list2

    fi

    if command

<<General Format>>

if list of conditions

then

list1

else

list2

fi

The operators that can be specified in the conditional expression differ for arithmetic comparison and string comparison as summarized below:

  • Arithmetic Comparison
Operators Used Meaning
number1 –gt number2

number1 –ge number2

number1 –lt number2

number1 –le number2

number1 –eq number2

number1 –ne number2

number1 > number2

number1 >= number2

number1 < number2

number1 <= number2

number1 = number2

number1 = number2

  • String Comparison
Operators Used Meaning
String1 = string2

String1 != string2

String

String1 = string2

String1 = string2

Whether string has assigned a value

Example:

Shell Script script6 determines whether the value of argument1 specified at run time is greater that that of argument2

Contents of script6

$ sh script6 4 –2

para1 > para2

if test $1 –gt $2

then

echo ‘para1 > para2’                           Run

else

echo ‘para1 <= para2’

fi

  1. II.      case command

<<General Format>>

case word in

pattern1) list1;;

pattern2) list2;;

.

.

.

patternN) listN;;

esac

The word part of the case command is primarily a parameter. The command compares the parameter value with the patterns sequentially from the top and, if a match occurs, the command executes the list following the matching pattern. Each list must be terminated by two consecutive semicolons (;).

Example:

Shell script script7 displays Linux if the run-time argument1 has the value L, Unix if the value is U, Windows if the value is W, and an error message if the value is none of the above.

Contents of script7

The pattern * is treated as wildcard.

If a list spans over two or more lines, only the last command must be terminated by two consecutive semicolons (;;).

Case $1 in

L) echo Linux;;

U) echo Unix;;

W) echo Windows;;

*) echo Error !!

echo Try again;;

esac

Run

$ sh script7 L

Linux

$ sh script7 A

Error !!

Try again

Note: When executing the same pattern for two or more patterns, the user can separate the patterns by vertical bars.

When patterns L and l are specified in the above example: L | l) echo Linux;;

b)      Iteration Control Commands

  1. I.      for command

<<General Format>>

for shellvariable [in word1 word2 ….. wordn]

do

list

done

A list of commands to be executed repeatedly are specified in list. The words after the keyword in are ordinary strings. If the in part is specified, the list of commands are executed the number of times equal to the number of words specified in the in part. Firstly, word1 is assigned to the shell variable and the list is executed. Secondly, word2 is assigned to the shell variable and the list is executed, and so on, until the end of word list is reached.

Example:

1. shell script script8 extracts from file /etc/passwd the lines of data of users containing bash or pppd as shell.

Contents of script8

$ sh script8

shell = bash

kundan:x:502:502:KK:/home/kundan:/bin/bash

shell = pppd

ram:x:503:502:R.K.:/home/ram:/usr/sbin/pppd

for x in bash pppd

do

echo “shell = $x”                      Run

grep “$x” /etc/passwd

done

  1. Omitting the in part to assign a string to the shell variable not from the shell script but at runtime.

Contents of script9

$ sh script9 bash

shell = bash

kundan:x:502:502:KK:/home/kundan:/bin/bash

for x

do

echo “shell = $x”                      Run

grep “$x” /etc/passwd

done

  1. II. while command

<<General Command>>

while list for evaluating iteration condition

do

list

done

The while command repeatedly executes a list of commands while the given conditions are met.

Example:

Shell script10 first displays a message and while the character entered from the standard input is not Q, check to determine whether the number entered from the standard input is positive, negative or 0 and repeatedly displays messages accordingly.

Contents of script10

echo –n “please input: “

read val

while [ “$val” != “q” ]

$ sh script10

please input: 12     entered value

input value is plus

please input: -5     entered value

input value is minus

please input: Q   entered value

$

do

if [ $val –gt 0 ]

then

echo input value is plus               Run

elif  [ $val –lt 0 ]

then

echo input value is minus

else

echo input value is zero

fi

echo –n “please input: “

read val

done

File Manipulation

Example Script script11 to display the username and shell of users from /etc/passwd file

Contents of script11

PASSFILE=/etc/passwd

STAT=0

COUNT=1

While [ $STAT = 0 ]

Do

LINE=`cat $PASSFILE | awk –v n=$COUNT ‘NR==n {print}’`

If  [ “$LINE” = “” ]

Then

STAT=1

else

$USER=`echo $LINE | awk –F: ‘{print $1}’`

$SHELL=`echo $LINE | awk –F: ‘{print $7}’`

echo “$USER::$SHELL”

let COUNT=COUNT+1

fi

done

Functions

<<General Format>>

Defining a Function                            Calling a Function

function function-name

{

.

.

function-body

.

.

}

Functions in shell scripts are treated as a command. It can be called from anywhere just by the name of the function.

function-name

Example:

Shell script script11 to display the mathematical result of two numbers using a function. Two numbers and the operator are passed as positional parameters.

Contents of script11

#Function to add, subtract and divide

function perform

{

case $3 in

add)

let RESULT=A+B;;

sub)

let RESULT=A-B;;

div)

let RESULT=A/B;;

*)

RESULT=”Error: Unknown Operator, Use add, sub, div”;;

esac

}

#start of main program

A=$1

B=$2

operator=$3

perform

echo $RESULT

Leave a Reply

Your email address will not be published. Required fields are marked *


*