Module – 22 UNIX Shell Scripting – Basics & Examples

Shell Scripting:

This chapter is written to help people understand some of the basics of shell script programming, and hopefully to introduce some of the possibilities of simple but powerful programming available under the bourne shell. As such, it has been written as a basis for one-on-one or group tutorials and exercises, and as a reference for subsequent use.

A Brief History of sh

Steve Bourne, wrote the Bourne shell which appeared in the Seventh Edition Bell Labs Research version of Unix.
Many other shells have been written; this particular chapter concentrates on the Bourne and the Bourne Again shells. (bash)

Other shells include the Korn Shell (ksh), the C Shell (csh), and variations such as tcsh.
This chapter does not cover those shells.

Let us start from Prompt String (PS1)

Command-line entries will be preceded by the Dollar sign ($). If your prompt is different, enter the command:

PS1=”$ ” ; export PS1

Example :1 Display username, host name and current working directory in the prompt

The PS1 in this example displays the following three information in the prompt:

  • \u – Username
  • \h – Hostname
  • \w – Full path of the current working directory
-bash-3.2$ export PS1="\u@\h \w> "
mike@dev-db ~> cd /etc/mail
mike@dev-db /etc/mail>

Example:2 Here is our first script to start with

vi first.sh

#!/bin/sh
# This is a comment!
echo Hello World    # This is a comment, too!

$ chmod 755 first.sh
$ ./first.sh
See the result….it is working good.

Example:3 How effectively to use commands under script

1 . cat /etc/passwd | grep “root”

or

2. grep “root” /etc/passwd   ***effective than above line.

 

Example:4

Below script will explain you the difference between different
special charterers with in script. (" ' * \ )

vi first2.sh

#!/bin/sh
# This is a comment! echo “Hello World” echo “Hello World”
echo “Hello * World” echo Hello * World
echo Hello World echo “Hello” World
echo Hello ” ” World echo “Hello \”*\” World” echo `hello` world
echo ‘hello’ world

chmod 755 first2.sh

./first2.sh


Example:5 Let us learn about Variables now:

Just about every programming language in existence has the concept of variables – a symbolic name for a chunk of memory to which we can assign values, read and manipulate its contents

vi var.sh
#!/bin/sh
MY_MESSAGE=”Hello World”
echo $MY_MESSAGE

chmod 755 var.sh
./var.sh

Try these now:

vi var1.sh

MY_MESSAGE="Hello World"
MY_SHORT_MESSAGE=hi
MY_NUMBER=1
MY_PI=3.142
MY_OTHER_PI="3.142" 
MY_MIXED=123abc
echo $MY_MESSAGE
echo $MY_SHORT_MESSAGE
echo $MY_NUMBER
echo $MY_PI
echo $MY_OTHER_PI
echo $MY_MIXED

 chmod 755 var1.sh
./var1.sh
Try these now:
vi var2.sh

#!/bin/sh
echo What is your name?
read MY_NAME
echo “Hello $MY_NAME – hope you’re well.”

./var2.sh

Example:6  Interactive script:

#!/bin/sh
  echo "What is your name?"
  read USER_NAME
  echo "Hello $USER_NAME"
  echo "I will create you a file called ${USER_NAME}_file"
  touch "${USER_NAME}_file"

Example: 7 Simple Loop script

Try the below simple loop script now.

#!/bin/sh
for i in 1 2 3 4 5 
do
echo "Looping ... number $i" 
done

Now try this see the output.
#!/bin/sh
 for i in hello 1 * 2 goodbye 
do
echo "Looping ... i is set to $i" 
done

Example: 7 Simple While Loops

while loops can be much more fun! (depending on your idea of fun, and how often you get out of the house... )
#!/bin/sh
 INPUT_STRING=hello
 while [ "$INPUT_STRING" != "bye" ] 
 do
 echo "Please type something in (bye to quit)" 
 read INPUT_STRING
 echo "You typed: $INPUT_STRING"
 done

Interesting right? Let us try another while loop  and see the output

#!/bin/sh
 while :
 do
 echo "Please type something in (^C to quit)" 
 read INPUT_STRING
 echo "You typed: $INPUT_STRING"
 done
 
 The colon (:) always evaluates to true; 
whilst using this can be necessary sometimes, 
it is often preferable to use a real exit condition.
 

Example: 8  While loop  with read  “f ” and  “case” function

Another useful trick is the while read f loop.
#!/bin/sh 
while read f 
do
case $f in
hello)         echo English ;;
howdy)         echo American ;;
gday)          echo Australian ;;
bonjour)       echo French ;;
"guten tag")   echo German ;;
*)             echo Unknown Language: $f
;; 
esac
done < myfile

Example: 9 “TEST ” with in if statement

Test is used by virtually every shell script written. It may not seem that way, because test is not often called directly. test is more frequently called as [. [ is a symbolic link to test, just to make shell programs more readable

Comparison strings for integers:

-lt - less than
-gt - greater than
-le - less than or equal
-ge - greater than or equal
=  - equal
!= not equal

Let us try this:

if [$foo == “bar” ]

    Note : if SPACE [ SPACE "$foo" SPACE == SPACE "bar" SPACE ]

Syntax should be like below:

if [ … ] then

# if-code

else

# else-code

fi

Example:
#!/bin/sh 
echo "Enter your number:"
read X
if [ "$X" -lt "10" ]
then 
    echo "X is less than Ten"
fi
if [ "$X" -gt "10" ]; 
then
        echo "X is more than Ten"
fi

Here is an another example in test with while:
#!/bin/sh
 X=0
 while [ -n "$X" ] 
 do
 echo "Enter some text (RETURN to quit)" 
 read X
 echo "You said: $X"
 done
 

Example: 10  “CASE ” statement in a script

        The case statement saves going through a whole set of if .. then .. else statements. Its syntax is really quite simple:

Try this example:

#/bin/sh
echo "Please talk to me ..."
while :
do
    read INPUT_STRING 
    case $INPUT_STRING in
        hello)
             echo "Hello yourself!"
            ;; 
bye)
    echo "See you again!" 
    break
     ;;
*)
    echo "Sorry, I don't understand"
    ;;
  esac 
done
echo
echo "That's all folks!"

 

Quick Reference This is a quick reference guide to the meaning of some of the less easily guessed commands and codes.

 

 

Description

 

Example

 

Run the previous command in the background

 

ls &

 

Logical AND

 

if [ "$foo" -ge "0" ] && [ "$foo" -le "9"]
Command

 

&

 

&&

 

||

Logical OR

if [ "$foo" -lt "0" ] || [ "$foo" -gt "9" ]

^

Start of line

grep “^foo”

$

End of line

grep “foo$”

=

String equality (cf. -eq)

if [ "$foo" = "bar" ]

!

Logical NOT

if [ "$foo" != "bar" ]

$$

PID of current shell

echo "my PID = $$"

$!

PID of last background command

ls & echo "PID of ls = $!"

$?

exit status of last command

ls ; echo "ls returned code $?"

$0

Name of current command (as called)

echo “I am $0″

$1

Name of current command’s first parameter

echo "My first argument is $1"

$9

Name of current command’s ninth parameter

echo "My ninth argument is $9"

Command

Description

Example

$@

All of current command’s parameters (preserving whitespace and quoting)

echo "My arguments are $@"

$*

All of current command’s parameters (not preserving whitespace and quoting)

echo "My arguments are $*"

-eq

Numeric Equality

if [ "$foo" -eq "9" ]

-ne

Numeric Inquality

if [ "$foo" -ne "9" ]

-lt

Less Than

if [ "$foo" -lt "9" ]

-le

Less Than or Equal

if [ "$foo" -le "9" ]

-gt

Greater Than

if [ "$foo" -gt "9" ]

-ge

Greater Than or Equal

if [ "$foo" -ge "9" ]

-z

String is zero length

if [ -z "$foo" ]

-n

String is not zero length

if [ -n "$foo" ]

-nt

Newer Than

if [ "$file1" -nt "$file2" ] (not in Bourne
shell)

-d

Is a Directory

if [ -d /bin ]

-f

Is a File

if [ -f /bin/ls ]

-r

Is a readable file

if [ -r /bin/ls ]

-w

Is a writable file

if [ -w /bin/ls ]
 

Leave a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>