Thursday, July 31, 2014

Unix Shell Programming Basics

Shell Program
A shell program or shell script is a collection of Shell commands to perform a particular task .

  • Unix Shell scripts (ksh, csh, bash, sh)
  • Python
  • perl
  • VBScript
  • Java Script
  • Apple Script etc.

Uses of Shell Programming
  • To combine lengthy and repetitive sequences of commands into a single, simple command.
  • To create new commands using combinations of pre-existing commands.
  • To automate the process of setting up and running applications.
Shell Program structure
  • Any text editor can be used to type shell program.
  • #! /bin/sh
    # this is a comment
    body of program
    exit 0 
  • #! /bin/sh indicates to other users to run the script using /bin/sh 
  • #! /bin/sh is called as shebang or hashbang 
  • Comment line starts with #  
  • exit 0 represents the end of script
Steps involved in Shell Script
    Step-1: Type shell program in a text file 
    Step-2: Save file with .sh extension
    Step-3: Make Executable for all users using 'chmod 755
    Step-4: Run script using ./

Shell Script Examples

#! /bin/sh
#Script Name:
#Purpose: to run hello.c file
gcc -o hello hello.c
exit 0

#! /bin/sh
#Script Name:
#Purpose: To update & upgrade debian #based system
apt-get update
apt-get upgrade
exit 0

Note: You need super user privileges to run script

  • Write a shell script to display your name on screen (Time: 1 Min) 
  • Write a shell script to remove CDAC directory, whose absolute path is /home/reniguntla/CDAC (Time: 2 Min) 
  • Write a shell script to display all lines contains “sh” in file (Time: 2 Min)

Shell Script Variables
  • By deafault all variables in shell script are strings.

  • #! /bin/sh
    #Script Name:
    #Purpose: To demonstrate variables
    echo "$x"
    echo "$y"
    z="How are you?"
    echo "$z"
    exit 0
  • Output: Hello
                      How are you?

Quoting of variables

#! /bin/sh
#Script Name:
#Script purpose: To demonstrate variable with #quotations
echo $x
echo $x
x=”Hello Mr.L”
echo $x
echo '$x'
exit 0

OutPut: Hello
             Hello Mr.L

  • Write a shell script to print your name and student id on screen using variables? (1 Mins) 
  • Write a shell script to swap 2 numbers using temporary variable? (2 Mins)

Shell Script Binary Operators 

Shell Script Binary Operators Example

#Script Name:
#Purpose: Demonstration of binary operators
val=`expr $a + $b`
echo "a + b : $val"
val=`expr $a - $b`
echo "a - b : $val"
val=`expr $a \* $b`
echo "a * b : $val"
val=`expr $b / $a`
echo "b / a : $val"
val=`expr $b % $a`
echo "b % a : $val"
exit 0

OutPut: a+b:30

Shell Script Relational Operators

Shell Script Boolean Operators

Note: Explore string operators yourself

Shell Script File Test Operators

Reading Input From User

To read input we use read command 
#! /bin/sh
#Script Name:
#Purpose: To demonstrate read command
echo “Enter your name?”
read MyName
echo “Your name is $MyName”
exit 0

OutPut: Enter your name ?
               Your name is Reniguntla


Write a shell script to read your name, roll number, marks in 4 subjects. Display your name, roll number, average of 4 subjects & percentage on screen. (3 Min)

Shell Script Parameters

All command line parameters / arguments of a shell script can be accessed via $1, $2, $3,..., $9, ${10}, ${11}...

$# holds the number of parameters passed

$@ Holds A list of all parameters in a single variable

$* also holds all parameters

$0 holds the name of the script

Shell Script Parameters Example

#Script Name:
#Purpose: Script parameters demo
echo "There are $# parameters"
echo "The parameters are $@"
echo "The script name is $0"
echo "The first parameter is $1"
echo "The second parameter is $2"
exit 0

OutPut: / reni sam
             There are 2 parameters
             The parameters are reni sam
             The script name is ./
             The first parameter is reni
            The second parameter is sam


Write a shell script to delete file1.txt & to give RWX permissions to all users on file2.txt. Take file1.txt and file2.txt as shell script parameters. (3 Min)


Syntax: if [ condition ]


#! /bin/sh
#purpose: To demonstrate if-then-fi
echo "Is it morning? Please answer yes(1) or no(0)"
read response
if [ $response -eq 1 ]
         echo “good morning”
exit 0


Syntax: if [ condition ]

#! /bin/sh
#purpose: To demonstrate if-then-else-fi
if [ -d /home/faculty ]
    echo “/home/faculty is a directory”
    echo “/home/faculty is not a directory”
exit 0


Write a shell script to check whether read number is even or odd? (Time: 2 Min)
Write a shell script to check given file(take this a script parameter) is plain file or directory. (Time: 2 Min)

Case Statement
case variable in
Pattern ) statements ;;
Pattern ) statements ;;

#! /bin/sh
#purpose: To demonstrate case statement
echo “is it morning? Please anser yes or no”
read timeofday
case “$timeofday” in
yes | Y | y | YES ) echo “Hi”
echo “good morning” ;;
yo | N | n | NO ) echo “Hi”
echo “Good After Noon” ;;
* ) echo “sorry answer not recognized” ;;
exit 0

For Loop

Syntax: for variable in values
#! /bin/sh
#Purpose: To demonstrate for loop
for file in $(ls *.sh)
     echo “$file”
exit 0

Note: You can use loop controls break, continue in for loop with a value.

While loop
Syntax: while [ condition ]

#! /bin/sh
#Purpose: To demonstrate While loop
echo "enter password:"
read password
while [ "$password" != "secret" ]
    echo "try again"
    read password
exit 0

Note: You can use loop controls break, continue in while loop with a value.
Note: Explore do-while loop for yourself

Arrays in Shell Script

An array variable can hold multiple values at the same time and each value can access using index value.


#Purpose: To demonstrate Array in shell script
#Displaying array item based on index number
echo "First Method: ${name[0]}"
echo "First Method: ${name[2]}"
# Different method to display all items in array
echo "First Method: ${name[*]}"
echo "Second Method: ${name[@]}"
exit 0
Function with No parameters & No return 
#Purpose: To demonstrate function with no #parameters & no return 
# Function Hi definition 
Hipgdst () { 
   echo "Hi PGDST" 
# Invoking function Hi 
exit 0

Function with  Parameters & Return Value
#Purpose: To demonstrate function with parameters & return val
# Function add definition
add () {
   return `expr $1 + $2`
# Reading 2 nums for adding through func
echo "enter first number"
read a
echo "enter second number"
read b

# Invoking function add with a & b as #parameters
add $a $b
# Capture value returned by last command
echo "Return value is $sumval"
exit 0

Shell Script Assignments
  1. Write a shell script to check read number is prime or not? (use for / while loop) 
  2. Write a shell script to determine whether the given word begins with lower case 
    or upper-case letter or whether it is starting with a special character using case statement. (use case) 
  3. Write a shell script to read contents of a file (which has been provided 
    as a script parameter) line by line and display on screen. (use while loop) 
  4. Write a shell script to read 10 values into an array and print them on screen using array index. 
  5. Write a shell script to read 5 values into array1 and 5 values into array2 and concatenate 
    both arrays store in array3. 
  6.  Write shell script functions to calculate +, -, *, / , % of two numbers which 
    are provided as parameters to the functions and and each function must return result. 
    Call all those functions and print return values. 
  7. Write a single shell script to do the following
    a. Create a file profile.txt 
    b. Change permissions of profile.txt to _rwxr_xr_x 
    c. Read your name, e-mail id, roll number and write them to profile.txt 
    d. Read the contents of profile.txt using a loop and display on screen. 
  8. Write a single shell script to do the following
    a. read a number 
    b. Define a function checkprime() which takes read number as parameter 
    & checks that number is prime or not & return the result. 
    c. Call checkprime() with parameters 12, 97, 111
    d. Display the return values of above function calls on screen 
  9. Write a single shell script to 
    a. read a number N 
    b. read N numbers in to an array called array_all using loop 
    c. Navigate through array_all and check for even & odd numbers. Store 
    all even numbers in array even_array & odd numbers in array odd_array 
    d. display all even numbers then odd numbers on screen. 

No comments:

Post a Comment