15 Shell Scripts Examples for Exam Preparation

on 10 November 2011

This is a list of shell script or shell script programs examples for UNIX-like systems(e.g. Linux). Shell script is a script written for the shell, or command line interpreter, of an operating system. This shell scripts works in all the major UNIX shells like Bourne shell, C shell and Bash shell.

This programs or scripts are very likely to come in practical examinations. This collection of basic shell scripts examples(with output) covers most of the syllabus like loops, command line arguments(positional parameters), file operations, if..else..fi, case in statement etc.

If you want to install Linux/UNIX in Windows then you can check install Linux/UNIX in windows. You might also like to check list of C programs for exam preparation.

List of Shell Scripts for Unix and Linux

1) Shell script to calculates the gross salary. (HRA = 20% of basic salary, DA = 50% of basic salary)

Code:

clear
echo -e "Enter basic salary:\c"
read bs
hra=`expr $bs \* 20 / 100`
da=`expr $bs \* 50 / 100`
gross=`expr $bs + $hra + $da`
echo "Gross salary is $gross"

Output:

Enter basic salary:9000
Gross salary is 15300

2) Shell Script to Generate Fibonacci Series

Code:

if [ $# -eq 1 ]
then
    num=$1
else
    echo -n "Enter a Number :"
    read num
fi

a=0
b=1

echo "The Fibonacci sequence for the number $num is : "

for (( i=0;i<=num;i++ ))
do
     echo -n "$a "
     f=$((a+b))
     a=$b
     b=$f
done

Output:

Enter a Number :8
The Fibonacci sequence for the number 8 is :
0 1 1 2 3 5 8 13 21

3) Shell script to check whether the given number is prime or not.

Code:

clear
echo -e "Enter a number: \c"
read num

i=2
rem=1

if [ $num -lt $i ]; 
then
 echo -e "$num is not a prime number.\n"
 exit 0
fi

while [ $i -le `expr $num / 2` -a $rem -ne 0 ]; 
do
 rem=`expr $num % $i`
 i=`expr $i + 1`
done

if [ $rem -ne 0 ]; 
then
 echo -e "$num is a prime number.\n"
else
 echo -e "$num is not a prime number.\n"
fi

Output:

Enter a number: 17
17 is a prime number.

Enter a number: 10
10 is not a prime number.

4) Shell Script to Find Armstrong Numbers between a Range

Code:

echo -n "Enter the Lower Limit : "
read Start
echo -n "Enter the Upper Limit : "
read Ending

echo "Armstrong Numbers between $Start and $Ending are: "

while [ $Start -le $Ending ]
do
     Number=$Start
     Length=${#Number}
     Sum=0
     OldNumber=$Number

     while [ $Number -ne  0 ]
     do
          Rem=$((Number%10))
          Number=$((Number/10))
          Power=$(echo "$Rem ^ $Length" | bc )
          Sum=$((Sum+Power))
     done

     if [ $Sum -eq $OldNumber ]
     then
         echo -n "$OldNumber  "
     fi

     let Start++
done

Output:

Enter the Lower Limit : 100
Enter the Upper Limit : 400
Armstrong Numbers between 100 and 400 are:
153  370  371 407

5) Shell script to find the sum of digits of a number.

Code:

clear
echo -e "Enter number:\c"
read n
n1=$n
sum=0
r=0
while [ $n -gt 0 ]
do
    r=`expr $n % 10`
    sum=`expr $sum + $r`
    n=`expr $n / 10`
done
    echo -e "Sum of digits of number $n1 is $sum\n"

Output:

Enter number:7890
Sum of digits of number 7890 is 24

6) Shell Script to find profit or loss given the Cost price and Selling price

Code:

clear
echo -e "Enter Cost Price:\c"
read cp
echo -e "Enter Selling Price:\c"
read sp
if [ $sp -eq $cp ];
then
  echo -e "\nNo profit or loss has incurred.\n"
elif [ $sp -lt $cp ];
then
  echo -e "\nLoss of Rs.`expr $cp - $sp` has incurred.\n"
else
  echo -e "\nProfit of Rs.`expr $sp - $cp` has incurred.\n"
fi

Output:

Enter Cost Price:1000
Enter Selling Price:1250

Profit of Rs.250 has incurred.

Enter Cost Price:300
Enter Selling Price:275

Loss of Rs.25 has incurred.

Enter Cost Price:280
Enter Selling Price:280

No profit or loss has incurred.

7) Shell script, which receives two filenames as arguments. It checks whether the two files contents are same or not. If they are same then second file is deleted.

Code:

if [ 2 –ne $# ];
then
echo “Usage: sh $0 filename1 filename2”
echo “For eg. sh $0 abc.txt xyz.txt”
if [ ! -e $1 ];
then
 echo -e " $1 does not exist!\n"
 exit 1
fi
if [ ! -e $2 ];
then
 echo -e " $2 does not exist!\n"
 exit 1
fi

if cmp $1 $2
then
  echo "Both file’s content are same."
  rm -f $2
  if [ $? -eq 0 ];
  then
    echo -e "File $2 deleted successfully.\n"
  else
    echo -e "Error deleting file $2. Please check whether it is a 
             regular file or not.\n"
  fi
else
  echo -e "Files $1 and $2 are different.\n"
fi

Output:

$ sh filecmpdel.sh k.txt c.txt
 k.txt does not exist!

$ sh filecmpdel.sh a.txt c.txt
a.txt c.txt differ: char 4, line 1
Files a.txt and c.txt are different.

$ sh filecmpdel.sh a.txt b.txt
Both file’s content are same.
File b.txt deleted successfully.

8) Write a program to find the factorial value of any number.

Code:

clear
echo -e "Enter a number:\c"
read num
fact=1
n=$num
while [ $num -ge 1 ]
do

  fact=`expr $fact \* $num`
  num=`expr $num - 1`

done
echo -e "Factorial of $n is $fact\n"

Output:

Enter a number:7
Factorial of 7 is 5040

9) Menu driven Shell script that Lists current directory, Prints Working Directory, displays Date and displays Users logged in

Code:

clear
chk=y
while [ "$chk" = "y" ]
do
        echo -e "\nMENU:\n1. List Current Directory\n2. Date\n3. 
                 Print Working Directory\n4. Users logged in
                 \nEnter your choice:\c"
        read choice
        case "$choice" in
                1) ls ;;
                2) date ;;
                3) pwd ;;
                4) who -Hu ;;
                *) echo "Invalid Choice"
        esac
        echo -e "\nDo you want to continue? Enter y to continue
                 or any other key to quit:"
        read chk
done

Output:

MENU:
1. List Current Directory
2. Date
3. Print Working Directory
4. Users logged in
Enter your choice:1
ap2.txt     cost.sh       f.txt         res
ap5.sh.txt  c.txt       google-chrome-stable_current_i386.deb  result
ap.sh.txt   Desktop       gross.sh         sdf
asd.sh     Documents       hui              Templates
a.sh     Downloads       makeshared        test2.sh
ass.txt      dsa.sh       menu.sh         test.sh
a.txt     examples.deb    Music         Videos
calc.sh     filecmp.sh       Pictures
chk.sh     file.sh       prime.sh
cobi.sh     fsct.sh       Public

Do you want to continue? Enter y to continue or any other key to quit:
y

MENU:
1. List Current Directory
2. Date
3. Print Working Directory
4. Users logged in
Enter your choice:2
Sun Oct  2 12:45:21 IST 2011

Do you want to continue? Enter y to continue or any other key to quit:
y

MENU:
1. List Current Directory
2. Date
3. Print Working Directory
4. Users logged in
Enter your choice:3
/home/akash

Do you want to continue? Enter y to continue or any other key to quit:
y

MENU:
1. List Current Directory
2. Date
3. Print Working Directory
4. Users logged in
Enter your choice:4
NAME     LINE         TIME             IDLE          PID COMMENT
akash    tty7         2011-10-02 09:12  old         1074 (:0)
akash    pts/1        2011-10-02 09:18   .          1491 (:0.0)

Do you want to continue? Enter y to continue or any other key to quit:
n

10) Shell script to check executable rights for all files in the current directory, if a file does not have the execute permission then make it executable.

Code:

clear
s=0
x=0
for file in *.*;
do
s=`expr $s + 1`
 if [ ! -x $file ];
 then
        if chmod u+x $file
        then
                echo "Added executable permission to $file"
                x=`expr $x + 1`
        else
                echo "Error adding executable permission to $file"     
        fi
 fi
done
echo -e "\nTotal number of files scanned: $s"
echo -e "Executable permission added to $x files.\n"

Output:

Added executable permission to examples.desktop
Added executable permission to google-chrome-stable_current_i386.deb
Added executable permission to menu.sh
Added executable permission to test2.sh
Added executable permission to test.sh

Total number of files scanned: 22
Executable permission added to 5 files.

11) Shell script for a simple calculator.

Code:

clear
echo "Enter number1:\c"
read n1
echo "Enter operator(+, -, /, *):\c"
read op
echo "Enter number2:\c"
read n2
if [ "$op" = "+" ];
then
 calc=`echo $n1 + $n2|bc`
 echo "\n$n1 + $n2 = $calc\n"
elif [ "$op" = "-" ];
then
 calc=`echo $n1 - $n2|bc`
 echo "\n$n1 - $n2 = $calc\n"
elif [ "$op" = "*" ];
then
 calc=`echo $n1 \* $n2|bc`
 echo "\n$n1 * $n2 = $calc\n"
elif [ "$op" = "/" ];
then
 calc=`echo $n1 / $n2|bc`
 echo "\n$n1 / $n2 = $calc\n"
else
  echo "Invalid operator!\n"
fi

Output:

Enter number1:100 
Enter operator(+, -, /, *):+
Enter number2:50

100 + 50 = 150

Enter number1:90  
Enter operator(+, -, /, *):*
Enter number2:5

90 * 5 = 450

12) Shell program to generate all combinations of 1, 2, and 3

Code:

clear
for i in 1 2 3
do
  for j in 1 2 3
  do
    for k in 1 2 3
    do
      echo $i $j $k
    done
  done
done

Output:

1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
1 3 1
1 3 2
1 3 3
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
2 3 1
2 3 2
2 3 3
3 1 1
3 1 2
3 1 3
3 2 1
3 2 2
3 2 3
3 3 1
3 3 2
3 3 3

13) Shell program for number sequence.

Code:

clear
if [ $# -ne 1 ];
then
n=4
else
n=$1
fi
a=1
i=1
while [ $i -le $n ]
do
 b=1
 while [ $b -le $i ]
 do
  echo "$a    \c"
  a=`expr $a + 1`
  b=`expr $b + 1`
 done
 echo "\n"
 i=`expr $i + 1`
done

Output:

1    

2    3

4    5    6

7    8    9    10

14) Decimal to Binary Conversion Shell Script

Code:

if [ $# -eq 0 ]
then
    echo "Argument(s) not supplied "
    echo "Usage: dec2binary.sh Decimal_number(s)"
else
echo -e "\033[1mDECIMAL             \t\t BINARY\033[0m"

    while [ $# -ne 0 ]
    do
         DecNum=$1
         Binary=
         Number=$DecNum

         while [ $DecNum -ne 0 ]
         do
              Bit=$(expr $DecNum % 2)
              Binary=$Bit$Binary
              DecNum=$(expr $DecNum / 2)
         done

         echo -e "$Number              \t\t $Binary"
         shift
# Shifts command line arguments one step.Now $1 holds second argument
        unset Binary
   done

fi

Output:

sh dec2binary.sh 7 16 255 256 1023 1024
DECIMAL                          BINARY
7                                111
16                               10000
255                              11111111
256                              100000000
1023                             1111111111
1024                             10000000000

15) Shell Script to Check Whether a String is Palindrome or not

Code:

if [ $# -eq 0 ]
then
     echo -n "Enter a String: "
     read pstr
else
     pstr=$*
fi

# Remove all punctuations from input string and convert upper case to
# lower or lower case to upper.

String="$(echo $pstr | sed 's/[^[:alnum:]]//g' | \
tr '[:upper:]' '[:lower:]')"

Flag=0

# Find length of the string.
len=${#String}

#You can also calculate string length using bellow commands.
#len=`echo $str | wc -c`
#len=$((len-1))

#get the mid value up to which the comparison would be done.
mid=$((len/2))

for ((i=1;i<=mid;i++))
do
   c1=`echo $String|cut -c$i`           # extracts from beginning
   c2=`echo $String|cut -c$len`         # extracts from last

   if [ $c1 != $c2 ]
   then
        Flag=1


        break 2             # break N breaks out of N levels of loop.
   fi

   let len--
done

if [ $Flag -eq 0 ]
then
     echo "\"$pstr\" is a Palindrome"
else
     echo "\"$pstr\" is not a Palindrome"
fi

Output:

sh palindrome1.sh Akash Shastri
"Akash Shastri" is not a Palindrome
sh palindrome.sh Dammit, I\'m mad!
"Dammit, I'm mad!" is a Palindrome
sh palindrome1.sh
Enter a String: 11/02/2011
"11/02/2011" is a Palindrome

If you have any queries related to the shell script, you can comment below.

4 comments:

Anonymous said...

Nice scripts... very useful !!!

Unknown said...

sir can u send more shell scripts

Anonymous said...

sir can u give me code to print all the pemutations of given number contains n digits and those permutations should be less than or equal to given number

Anonymous said...

nice very nice thank you....

Post a Comment