0% found this document useful (0 votes)
58 views

P - Many Shell Programs - 82

The document contains examples of shell script programs that perform various tasks like converting case of text in a file, counting vowels/consonants in a string, copying content between files, generating Fibonacci series, checking if a number is prime, Armstrong number etc. It also provides examples of scripts for mathematical operations like finding factorial, power, reverse of a number and checking leap years. The scripts demonstrate use of basic shell scripting constructs like variables, conditional statements, loops, string manipulation and arithmetic operations.

Uploaded by

Amitava Sarder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

P - Many Shell Programs - 82

The document contains examples of shell script programs that perform various tasks like converting case of text in a file, counting vowels/consonants in a string, copying content between files, generating Fibonacci series, checking if a number is prime, Armstrong number etc. It also provides examples of scripts for mathematical operations like finding factorial, power, reverse of a number and checking leap years. The scripts demonstrate use of basic shell scripting constructs like variables, conditional statements, loops, string manipulation and arithmetic operations.

Uploaded by

Amitava Sarder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

What is Shell Script??

Shell Script is nothing but sequence of commands that are stored in a single file (same like a text file) . The commands
written in file are interpreted by Shell . A shell script is created for those commands which user need again and again ,
this save time as instead of writing same commands again and again you only need to enter the shell script name.

Advantages of using Shell Script:-


1. Save time
2. It is not compiled into a separate executable file as a C program is.

Disadvantages:-
1. Not fast in comparison to high level languages.
2. Complex code are very difficult to write using shell script.
Shell script files uses .sh extension . Shell Scripts are executed in a separate child shell process , and this sub-shell need
not to be of same type as your login shell.

Write a Shell Script to accept file name and convert its


contents from lower case to upper case.
echo "Type any file name"
read fname

if test -e $fname
then
if test -f $fname
then
cat $fname | tr [a-z] [A-Z] > change
rm $fname
mv change $fname
cat $fname
else
echo "Given file name exists,but it is not a regular file"
fi
else
echo "File does not exist"
fi

Write a Shell Script to count the number of Vowels, Number


of Consonants and Number of digits present in a given
String.
clear
echo "Type any String"
read string
length=`echo $string | wc -c`
nvowels=0
nconsonants=0
ndigits=0

while [ $length -gt 1 ]


do
length=`expr $len - 1`
h=`echo $string | cut -c $length`

case $h in
[AaEeIiOoUu]) nvowels=`expr $nvowels + 1`
;;

[BbCcDdFfGgHhJjKkLlMmNnPpQqRrSsTtVvWwXxYyZz])
nconsonants=`expr $consonants + 1`
;;

[0-9]) ndigits=`expr $ndigits + 1`


;;
esac
done

echo "Number of Vowels : $nvowels"


echo "Number of Consonants : $nconsonants"
echo "Number of Digits : $ndigits"

Write a Shell Script to copy the content of a file to another


file.
clear

echo "Enter Source file name"

read source

echo "Enter Destination file name"

read destination

if test -e $source

then
if test -f $source

then

if test -e $destination

then

echo "Failed to copy,Destination file already exist"

else

cp $source $destination

echo "File copied successfully"

fi

else

echo "Failed to copy, $source not a regular file"

fi

else

echo "Failed to copy, Source file does not exist"

fi

Write a Shell Script to Wish "Good Morning" and "Good Evening" depending
on the time
clear
hours=`date|cut -c12-13`
if [ $hours -le 12 ]
then
echo "Good Morning"
else
if [ $hours -le 16 ]
then
echo "Good Afternoon"
elif [ $hours -le 20 ]
then
echo "Good Evening"
else
echo "Good Night"
fi
fi

Write a Shell Script to display Mathematical Table for a given number


clear
echo "Type any number to generate Mathematical Table"
read number
i=1
while [ $i -le 10 ]
do
echo " $number * $i =`expr $number \* $i ` "
i=`expr $i + 1`
done

Write a Shell Script to generate Fibonacci Series.(Example : 0 1 1 2 3 5 8 13 ...)


clear
echo "How many number of terms to be generated ?"
read n
x=0
y=1
i=2
echo "Fibonacci Series up to $n terms :"
echo "$x"
echo "$y"
while [ $i -lt $n ]
do
i=`expr $i + 1 `
z=`expr $x + $y `
echo "$z"
x=$y
y=$z
done

Write a Shell Script to find the reverse of a given number Using WC


clear
echo " Type any number "
read number

length=`echo $number | wc -c `
reverse=0

while [ $length -gt 1 ]


do
length=`expr $length - 1 `
d=`echo $number|cut -c $length `
reverse=`expr $reverse \* 10 + $d `
done

echo "Reverse of the entered number is : $reverse"


Who:- Displays all the users information who are currently logged into
the system.
Write a shell script to check whether a given number is an Armstrong number or not.

echo "Enter a number: "


read c

x=$c
sum=0
r=0
n=0
while [ $x -gt 0 ]
do
r=`expr $x % 10`
n=`expr $r \* $r \* $r`
sum=`expr $sum + $n`
x=`expr $x / 10`
done

if [ $sum -eq $c ]
then
echo "It is an Armstrong Number."
else
echo "It is not an Armstrong Number."
fi

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number:
153
It is an Armstrong Number.

Write a shell script that takes two number s through keyboard and finds the value od one number raised
to the power of another.

echo "Enter a number: "


read a
echo "Enter Power: "
read p

i=1
ans=1
while [ $i -le $p ]
do
ans=`expr $ans \* $a`
i=`expr $i + 1`
done
echo "Answer of $a^$p is $ans"

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number: 10
Enter Power: 3
Answer of 10^3 is 1000

How do I write Bash Script to find Armstrong number

Ans:

#!/bin/bash
#Script to find armstrong number till 500, you can change it
i=1
while((i<=500))
do
c=$i
d=$i
b=0
a=0
#checking each number
while((c>0))
do
#separating each digit
a=$((c%10))
#finding cube of each digit and adding them
b=$((b + a*a*a))
c=$((c/10))
done
if((b==d)); then
echo "$i"
fi
i=$((i+1))
done
Output

Write a shell script to display and evaluate following series up to n. 1-4+27-16+125-36+-------

echo "Enter a number: "


read n
i=1
val=0
cal=0
while [ $i -le $n ]
do
if [ `expr $i % 2` -ne 0 ]
then
val=`expr $i \* $i \* $i`
cal=`expr $cal + $val`
echo -e "+$val \c"
else
val=`expr $i \* $i`
cal=`expr $cal - $val`
echo -e "-$val \c"
fi
i=`expr $i + 1`
done
echo -e "\nSum is $cal"

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number:10
+1 -4 +27 -16 +125 -36 +343 -64 +729 -100
Sum is 1005

Write a sccript to find a factorial of a given no.

fact=1
ie=1

echo -e "Enter a number:\c"


read a
while [ $ie -le $a ]
do
fact=`expr $fact \* $ie`
ie=`expr $ie + 1`
done
echo -e "Multilpication of $a number is $fact."

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number:10
Multilpication of 10 number is 3628800.

Write a shell script to find whether a given year(4 digits)is leap year or not.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter the year in 4 digits: "
read num
if [ $num -ge 1000 -a $num -le 9999 ]
then
if [ `expr $num % 4` -eq 0 ]
then
echo "The year $num is a Leap year"
else
echo "The year $num is not a Leap year"
fi
else
echo "Invalid year format"
fi

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter the year in 4 digits:
2000
The year 2000 is a Leap year

===========================================================
Script-6

Write a shell script to find the sum of the first n numbers.

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter a number: "
read num

i=1
sum=0

while [ $i -le $num ]


do
sum=`expr $sum + $i`
i=`expr $i + 1`
done
echo "The sum of first $num numbers is: $sum"
--------------------------------------------------------------------------------------------------------------
Enter a number:
5
The sum of first 5 numbers is: 15
===========================================================
Script-7

Write a shell script to check whether a given number is prime or not.

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter a number: "
read num
i=2
f=0
while [ $i -le `expr $num / 2` ]
do
if [ `expr $num % $i` -eq 0 ]
then
f=1
fi
i=`expr $i + 1`
done
if [ $f -eq 1 ]
then
echo "The number is composite"
else
echo "The number is Prime"
fi

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number:
5
The number is Prime
===========================================================
Script-8

Write a shell script to check whether a given number is an Armstrong


number or not.

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter a number: "
read c

x=$c
sum=0
r=0
n=0
while [ $x -gt 0 ]
do
r=`expr $x % 10`
n=`expr $r \* $r \* $r`
sum=`expr $sum + $n`
x=`expr $x / 10`
done

if [ $sum -eq $c ]
then
echo "It is an Armstrong Number."
else
echo "It is not an Armstrong Number."
fi

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number:
153
It is an Armstrong Number.

===========================================================
Script-9

Write a pro. to make a table for a given no.

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
i=0
sum=0
echo -e "Please enter the number that you want Table:\c"
read a

for i in 1 2 3 4 5 6 7 8 9 10
do
echo -e "$a * $i =`expr $a \* $i`"
done

--------------------------------------------------------------------------------------------------------------
OUTPUT
Please enter the number that you want Table:10
10 * 1 =10
10 * 2 =20
10 * 3 =30
10 * 4 =40
10 * 5 =50
10 * 6 =60
10 * 7 =70
10 * 8 =80
10 * 9 =90
10 * 10 =100

===========================================================
Script-10:
Write a sccript to find a factorial of a given no.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
fact=1
ie=1

echo -e "Enter a number:\c"


read a

while [ $ie -le $a ]


do
fact=`expr $fact \* $ie`
ie=`expr $ie + 1`
done
echo -e "Multilpication of $a number is $fact."

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number:10
Multilpication of 10 number is 3628800.

===========================================================
Script-11

Write a shell script to find a sum of given no and to check out to see if it is even
or odd.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter a number: "
read n

sum=0
x=$n
r=0

while [ $x -gt 0 ]
do
r=`expr $x % 10`
sum=`expr $sum + $r`
x=`expr $x / 10`
done

if [ `expr $sum % 2` -eq 0 ]


then
echo "The sum of $n is $sum and it is even"
else
echo "The sum of $n is $sum and it is odd"
fi

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number:11
The sum of 11 is 2 and it is odd

===========================================================
Script-12

Write a shell script to stimulate a calculator that does the addition, subtraction,
multiplication and division between two numbers. The user should be prompted for
two operands and operator.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ans='Y'
while [ $ans = 'Y' -o $ans = 'y' ]
do
echo "Enter operand1: "
read op1
echo "Enter operand2: "
read op2
echo "Enter operation: "
echo "+ for addition"
echo "- for subtraction"
echo "* for multiplication"
echo "/ for division"
echo "Enter your choice: "
read op

case $op in
"*")sum=`expr $op1 \* op2`
echo "Product is $sum";;
"+")sum=`expr $op1 + op2`
echo "Sum is $sum";;
"-")sum=`expr $op1 - $op2`
echo "Difference is $sum";;
"/")sum=`expr $op1 / $op2`
echo "Quotient is $sum";;
*)echo "Invalid Entry"
esac
echo "Do you wish to continue:(Y/N):"
read ans
done
--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter operand1:
8
Enter operand2:
4
Enter operation:
+ for addition
- for subtraction
* for multiplication
/ for division
Enter your choice:
/
Quotient is 2
Do you wish to continue:(Y/N):
n
===========================================================
Script-13.

Write a shell script to display and evaluate following series up to n.


1-4+27-16+125-36+-------

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter a number: "
read n
i=1
val=0
cal=0
while [ $i -le $n ]
do
if [ `expr $i % 2` -ne 0 ]
then
val=`expr $i \* $i \* $i`
cal=`expr $cal + $val`
echo -e "+$val \c"
else
val=`expr $i \* $i`
cal=`expr $cal - $val`
echo -e "-$val \c"
fi
i=`expr $i + 1`
done
echo -e "\nSum is $cal"

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number:10
+1 -4 +27 -16 +125 -36 +343 -64 +729 -100
Sum is 1005

===========================================================
Script-14.

Display series: 0,1,1,2,3,5,8.......

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter a number: "
read num
sum=0
a=0
b=1
echo "Series is:"
while [ $sum -le $num ]
do
a=$b
b=$sum
sum=`expr $a + $b`
echo -e "$b \c"
done
echo -e "\n"

--------------------------------------------------------------------------------------------------------------
Enter a number:10
Series is:
0112358

===========================================================
Script:15.

Display series:1+4+27+256...

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter a number: "
read num
val=1
i=1
j=1
echo "The Series is: "
while [ $i -le $num ]
do
while [ $j -le $i ]
do
val=`expr $val \* $i`
j=`expr $j + 1`
done
if [ $i -eq 1 ]
then
echo -e "$val \c"
else
echo -e "+$val \c"
fi
j=1
val=1
i=`expr $i + 1`
done
echo -e "\n"

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number: 5
The Series is: 1 +4 +27 +256 +3125

===========================================================
Script:16.

Find out the sum of the following series up to a given no.


1+4+9+....N.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter a number: "
read num
i=1
val=0
sum=0
echo -e "The Sum of \c"
while [ $i -le $num ]
do
val=`expr $i \* $i`
if [ $i -eq 1 ]
then
echo -e "$val \c"
else
echo -e "+$val \c"
fi
sum=`expr $sum + $val`
i=`expr $i + 1`
done
echo -e "= $sum\n"

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number: 5
The Sum of 1 +4 +9 +16 +25 = 55

===========================================================
Script:17.

Write a shell script to find the sum of a given numbers.

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
if [ $# -lt 1 ]
then
echo "Invalid Argument"
else
j=0
sum=0
echo -e "The sum of \c"
for i in $*
do
if [ $j -ne -1 ]
then
echo -e "$i, \c"
sum=`expr $sum + $i`
fi
j=`expr $j + 1`
done
echo -e "= $sum \n"
fi

--------------------------------------------------------------------------------------------------------------
OUTPUT
The sum of 1, 2, 3, = 6

===========================================================
Script:18.

Display series:1-2+6-24+....

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter a number: "
read num

i=1
x=0
while [ $i -le $num ]
do
j=1
x=1
while [ $j -le $i ]
do
x=`expr $x \* $j`
j=`expr $j + 1`
done

if [ $i -eq 1 ]
then
echo -e "$x \c"
elif [ `expr $i % 2` -eq 0 ]
then
echo -e "-$x \c"
elif [ `expr $i % 2` -ne 0 ]
then
echo -e "+$x \c"
fi
i=`expr $i + 1`
done
echo -e "\n"

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number:5
1 -2 +6 -24 +120

===========================================================
Script:19.

Find Basic Salary,Hra,DA, And Calculate the Net Salary.

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter Basic Salary: "
read b

hra=0
da=0
if [ $b -gt 1500 ]
then
hra=500
da=`expr $b \* 98 / 100`
else
hra=`expr $b \* 10 / 100`
da=`expr $b \* 90 / 100`
fi
gs=`expr $b + $hra + $da`

echo "Gross Salary is: Rs.$gs"


echo "Details:"
echo "Basic: Rs.$b"
echo "HRA: Rs.$hra"
echo "DA: Rs.$da"

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter Basic Salary:
15000
Gross Salary is: Rs.30200
Details:
Basic: Rs.15000
HRA: Rs.500
DA: Rs.14700
===========================================================
Script:20.

Write a shell script that takes two number s through keyboard and finds the value od one number raised to the power of another.

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter a number: "
read a

echo "Enter Power: "


read p

i=1
ans=1
while [ $i -le $p ]
do
ans=`expr $ans \* $a`
i=`expr $i + 1`
done
echo "Answer of $a^$p is $ans"

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number: 10
Enter Power: 3
Answer of 10^3 is 1000

===========================================================
Script - 21
Write a shell to generate the following patterns.
*
**
***
****
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter the number of Rows:"
read r
i=1
j=1
while [ $i -le $r ]
do
j=1
while [ $j -le $i ]
do
echo -e "* \c"
j=`expr $j + 1`
done
echo -e "\n"
i=`expr $i + 1`
done

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter the number of Rows:
5
*

**

***

****

*****

===========================================================
Script 22

Display Following:
1
2 2
3 3 3
4 4 4

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter number of rows: "
read r
echo "Enter number of columns: "
read c
i=1
j=1
while [ $i -le $r ]
do
j=$c
while [ $j -ge $i ]
do
echo -e " \c"
j=`expr $j - 1`
done

j=1

while [ $j -le $i ]
do
echo -e " $i\c"
j=`expr $j + 1`
done
echo -e "\n"
i=`expr $i + 1`
done

--------------------------------------------------------------------------------------------------------------
OUTPUT

Enter number of rows:


4
Enter number of columns:
5
1

22

333

4444
===========================================================
Script-23:
Display Following:
|_
||_
|||_
||||_

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter Number of Rows: "
read row

i=1

while [ $i -le $row ]


do
j=1
while [ $j -le $i ]
do
echo -e "| \c"
j=`expr $j + 1`
done
echo -e "_ \n"
i=`expr $i + 1`
done

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter Number of Rows:
4
|_

||_

|||_

||||_

===========================================================
Script-24
Display Following:
*
**
***
**
*
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter Number of rows: "
read row

i=1
while [ $i -le $row ]
do
j=1
while [ $j -le $i ]
do
echo -e "* \c"
j=`expr $j + 1`
done
echo -e "\n"
i=`expr $i + 1`
done
i=`expr $row - 1`
while [ $i -ge 1 ]
do
j=1
while [ $j -le $i ]
do
echo -e "* \c"
j=`expr $j + 1`
done
echo -e "\n"
i=`expr $i - 1`
done

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter Number of rows:3
*

**

***

**

===========================================================
Script25

Display Following:
1
12
123
1234

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter number of Rows: "
read row

i=1
while [ $i -le $row ]
do
j=1
while [ $j -le $i ]
do
echo -e "$j \c"
j=`expr $j + 1`
done
echo -e "\n"
i=`expr $i + 1`
done

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter number of Rows:
5
1

12

123

1234

12345

===========================================================
SCRIPT-26

Display Following:
*
* *
* * *
* * * *
* * *
* *
*

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
echo "Enter Number of Rows: "
read row

i=1
while [ $i -le $row ]
do
j=$row
while [ $j -gt $i ]
do
echo -e " \c"
j=`expr $j - 1`
done
j=1
while [ $j -le $i ]
do
echo -e " *\c"
j=`expr $j + 1`
done
echo -e "\n"
i=`expr $i + 1`
done
i=`expr $row - 1`
while [ $i -ge 1 ]
do
j=$row
while [ $j -gt $i ]
do
echo -e " \c"
j=`expr $j - 1`
done
j=$i
while [ $j -ge 1 ]
do
echo -e " *\c"
j=`expr $j - 1`
done
echo -e "\n"
i=`expr $i - 1`
done

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter Number of Rows:5
*

**

***

****

*****

****

***

**

===========================================================

Practical List-03

Script-1:
Write a shell script to read a string through keyboard and check whether it is
palindrome or not.
*************************************************************************************************
echo "Enter a string: "
read s

len=`echo $s | wc -c`
while [ $len -gt 0 ]
do
st=`echo $s | cut -c $len`
str=$str$st
len=`expr $len - 1`
done
if [ $str = $s ]
then
echo "String Palindrome"
else
echo "string is not palindrome"
fi
*************************************************************************************************
OUTPUT:
Enter a string:
madam
String Palindrome
*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************
Script-2:
Write a shell script that combine two files in the third file horizontally and vertically.
*************************************************************************************************
echo "Enter Filename1: "
read f1
echo "Enter Filename2: "
read f2

cat $f1 > vfile


cat $f2 >> vfile

paste -d " " $f1 $f2 >> vfile

*************************************************************************************************
OUTPUT:

Enter Filename1:
f1
Enter Filename2:
f2

[s92@popeye TW3]$ cat vfile


HI HELLP
HARDIK
Welcome
HI HELLP Welcome
HARDIK
*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-3: Write a shell script that displays all the processes in the systemby every 30 seconds, but five times.

*************************************************************************************************
i=1
while [ $i -le 5 ]
do
ps
sleep 30
i=`expr $i + 1`
done
*************************************************************************************************

OUTPUT:

PID TTY TIME CMD


4289 pts/0 00:00:00 bash
4758 pts/0 00:00:00 sh
4759 pts/0 00:00:00 ps
PID TTY TIME CMD
4289 pts/0 00:00:00 bash
4758 pts/0 00:00:00 sh
4763 pts/0 00:00:00 ps
PID TTY TIME CMD
4289 pts/0 00:00:00 bash
4758 pts/0 00:00:00 sh
4802 pts/0 00:00:00 ps
PID TTY TIME CMD
4289 pts/0 00:00:00 bash
4758 pts/0 00:00:00 sh
4806 pts/0 00:00:00 ps
PID TTY TIME CMD
4289 pts/0 00:00:00 bash
4758 pts/0 00:00:00 sh
4809 pts/0 00:00:00 ps

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-4 : Write a shell script to remove the zero sized file from the current directory

*************************************************************************************************
for i in `ls`
do
if [ -s $i ]
then
echo "$i - Non-empty file"
else
echo "$i - Empty file Deleted"
rm $i
fi
done
*************************************************************************************************
OUTPUT:

05 - Non-empty file
20 - Non-empty file
h - Empty file Deleted
a - Empty file Deleted
r - Empty file Deleted

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-5: Write a shell script to change the suffix of all your *.txt files to .dat

*************************************************************************************************

for i in `ls *.txt`


do
f=`echo $i | cut -d "." -f 1`
mv $i $f.dat
done

*************************************************************************************************

OUTPUT:

Before->
01 05 09 13 17 21 25 29 33 37 db36 f2 status.dat
02 06 10 14 18 22 26 30 34 38 db37 ff test
03 07 11 15 19 23 27 31 35 39 db38 file vfile
04 08 12 16 20 24 28 32 36 a.txt f1 project.dat wordfile
-------
After->
01 05 09 13 17 21 25 29 33 37 db36 f2 status.dat
02 06 10 14 18 22 26 30 34 38 db37 ff test
03 07 11 15 19 23 27 31 35 39 db38 file vfile
04 08 12 16 20 24 28 32 36 a.dat f1 project.dat wordfile
-------

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-6: Write a shell script that appends the PID of current shell to the filenames of all files having extension txt.

*************************************************************************************************

ps | cut -d " " -f 2 > pfile


l=`cat pfile | wc -l`
l=`expr $l - 1`
x=`cat pfile | tail -$l | head -1 | cut -d " " -f 2`
for i in `ls *.txt`
do
a=`echo $i | cut -d "." -f 1`
fn=$x$a
mv $i $fn.txt
done
rm pfile

*************************************************************************************************

OUTPUT:

Before->
01 05 09 13 17 21 25 29 33 37 db36 f2 status.dat
02 06 10 14 18 22 26 30 34 38 db37 ff test
03 07 11 15 19 23 27 31 35 39 db38 file vfile
04 08 12 16 20 24 28 32 36 a.txt f1 project.dat wordfile
-------
After->
01 05 09 13 17 21 25 29 33 37 db36 f2 status.dat
02 06 10 14 18 22 26 30 34 38 db37 ff test
03 07 11 15 19 23 27 31 35 39 db38 file vfile
04 08 12 16 20 24 28 32 36 4289a.txt f1 project.dat wordfile
----------
*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-7: Write a shell script to delete all spaces from a given file

*************************************************************************************************
echo "Enter the Filename: "
read fname

cat $fname | tr -d " " > $fname

*************************************************************************************************

OUTPUT:

Enter the Filename:


f1
[s92@popeye TW3]$ cat f1
HARDIK
HARDIK

*************************************************************************************************
*************************************************************************************************
*************************************************************************************************

Script-8: Write a shell Script that displays the user information from /etc/passwd for a given user as follows:
User Login Name:
User Id:
User Gourp Id:
If no argument is passed, display or the current user

*************************************************************************************************

if [ $# -ne 1 ]
then
user=`who am i | tr -s " " | cut -d " " -f 1`
else
user=$1
fi
cat /etc/passwd | grep $user > file
lname=`cat file | cut -d ":" -f 1`
uid=`cat file | cut -d ":" -f 3`
gid=`cat file | cut -d ":" -f 4`
echo "User Login name: $lname"
echo "User Id: $uid"
echo "User Group id: $gid"

*************************************************************************************************

OUTPUT:

User Login name: s92


User Id: 2535
User Group id: 1050

**********************************************************************************************************
**********************************************************************************************************
*******************************************************************************
*************************************************************************************************

Script-9: Write a shell script that will change the current working directory to given directory.
For example if argument passed is /d1/d2/d3/d4/d5 then at the end of the script, the user should be in the d5 directory.
*************************************************************************************************

x=`echo $1 | tr "/" " "`


for i in `echo $x`
do
mkdir $i
cd $i
done

*************************************************************************************************

OUTPUT:

sh 09 /d1/d3
01 06 11 16 21 26 31 36 d1 f2 test
02 07 12 17 22 27 32 37 db36 ff vfile
03 08 13 18 23 28 33 38 db37 file wordfile
04 09 14 19 24 29 34 39 db38 project.dat
05 10 15 20 25 30 35 4289a.txt f1 status.dat

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-10: Write a shell script to find a given date fall on a weekday or a weekend.

*************************************************************************************************

if [ $# -eq 2 ]
then
x=`cal $2 07 | wc -l`
x=`expr $x - 1`
cal $2 07 | tail -$x > file
cat file | grep -w "$1" > f
j=0
for i in `cat f`
do
j=`expr $j + 1`
if [ $i = $1 ]
then
break
fi
done
if [ $j -gt 1 -a $j -lt 7 ]
then
echo "Day is Weekday"
else
echo "Day is Weekend"
fi
else
echo "Invalid arguments"
echo "Usage: 10 day month"
fi

*************************************************************************************************

OUTPUT:

[s92@popeye TW3]$ sh 10 11 07
Day is Weekday

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-11: Write a shell script to search for a given word in all files given as the arguments on the command line.
On the first occurence of the the word, display the filename and terminate the script.
*************************************************************************************************
if [ $# -lt 1 ]
then
echo "Invalid Argument"
else
echo "Enter a word: "
read word
x=0
for i in `echo $*`
do
if [ -f $i ]
then
x=`cat $i | grep -c "$word"`
if [ $x -ne 0 ]
then
echo "Word found in File : $i"
break
fi
fi
done
fi

*************************************************************************************************

OUTPUT:

[s92@popeye TW3]$ sh 11 f1 f2 file


Enter a word:
Su
Word found in File : file

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-12: Write a shell script that displays the name of the smallest file in the current working directory.
It should display all the information about that file in the following format:
Filename:
Owner:
Size:
No. of Links:

*************************************************************************************************

x=`ls -Sl | tail -1 | tr -s " "`


fname=`echo $x | cut -d " " -f 9`
owner=`echo $x | cut -d " " -f 3`
size=`echo $x | cut -d " " -f 5`
link=`echo $x | cut -d " " -f 2`
echo "Filename : $fname"
echo "Owner : $owner"
echo "Size : $size"
echo "Link : $link"

*************************************************************************************************

OUTPUT:

Filename : 4289a.txt
Owner : s112
Size : 0
Link : 1

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-13: Write a shell script that displays only specified lines of the given files as follows
showlines n file -> displays first n lines of file
showlines n1 n2 file -> displays line numbers then display error
if no. of arguments are not in the correct number thendisplay error message

*************************************************************************************************

if [ $# -eq 2 ]
then
cat $2 | head -$1
elif [ $# -eq 3 ]
then
cat $3 | head -$2 | tail -$1
else
echo "Invalid Arguments"
fi

*************************************************************************************************

OUTPUT:

[s92@popeye TW3]$ sh 13 2 file


Su Mo Tu We Th Fr Sa
1 2
[s92@popeye TW3]$ sh 13 2 3 file
1 2
3 4 5 6 7 8 9

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-14: A file Wordfile contains list of words. Write a shell script to search for those words which are in Wordfile,
in all the files that are passed as an argument to the program. The name of Wordfile should also be passed as an argument.
*************************************************************************************************
if [ $# -ge 2 ]
then
c=0
for i in `echo $*`
do
if [ $c -eq 1 ]
then
for j in `cat $1`
do
x=`cat $i | grep -wc "$j"`
if [ $x -eq 1 ]
then
echo "$j word found in $i"
fi
done
fi
c=1
done
else
echo "Usage: 14 wordfile file1 file2 ... file9"
fi

*************************************************************************************************

OUTPUT:

[s92@popeye TW3]$ sh 14 wordfile f1 f2 ff file


unix word found in ff
is word found in ff
unix word found in file
is word found in file

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-15: Write a shell script to display the following menu:


i.Length of the string
ii.reverse of the string
iii.copy one string to another
*************************************************************************************************

echo "Enter a string: "


read str
echo "i. Length of string"
echo "ii.Reverse of the string"
echo "iii. copy one string into another."
echo "Enter your choice: "
read c
case "$c" in
i)x=`echo $str | wc -c`
x=`expr $x - 1`
echo "Length is : $x";;
ii)x=`echo $str | wc -c`
x=`expr $x - 1`
while [ $x -gt 0 ]
do
c=`echo $str | cut -c $x`
s=$s$c
x=`expr $x - 1`
done
echo "The Reverse of string is : $s";;
iii)s=$str
echo "The copied string is : $s";;
esac

*************************************************************************************************

OUTPUT:

Enter a string:
life
i. Length of string
ii.Reverse of the string
iii. copy one string into another.
Enter your choice:
ii
The Reverse of string is : efil

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-16: Write a shell script to display the following menu for a particular file:

i.Display all the words of a file in ascending order.


ii.Display a file in descending order.
iii.Display a file in reverse order.
iv.Toggle all the characters in the file
v.Display type of the file.
*************************************************************************************************

echo "Enter the Filename: "


read fn
echo "i. Display all the words of a file in ascending order."
echo "ii. Display a file in descending order."
echo "iii. Display a file in reverse order."
echo "iv. Toggle all the characters in the file."
echo "v. Display type of the file."
echo "Enter your choice : "
read c

case $c in
i)for i in `cat $fn`
do
echo $i >> ff
done
echo "File in ascending order: "
cat ff | sort
rm -f ff;;
ii)for i in `cat $fn`
do
echo $i >> ff
done
echo "File in decending order: "
cat ff | sort -r
rm -f ff;;
iii)for i in `cat $fn`
do
echo $i >> ff
done
x=`cat ff | wc -l`
echo "Reverse order: "
while [ $x -gt 0 ]
do
s=`cat ff | head -$x | tail -1`
echo $s
x=`expr $x - 1`
done
rm -f ff;;
iv)x=`cat $fn | wc -l`
i=1
while [ $i -le $x ]
do
s=`cat $fn | head -$i | tail -1`
xx=`echo $s | wc -c`
j=1
str=""
while [ $j -le $xx ]
do
c=`echo $s | cut -c $j`
case $c in
[A-Z])c=`echo $c | tr [A-Z] [a-z]`;;
[a-z])c=`echo $c | tr [a-z] [A-Z]`;;
esac
str=$str$c
j=`expr $j + 1`
done
echo $str >> ff

i=`expr $i + 1`
done;;
v)if [ -f $fn ]
then
echo "$fn is ordinary file"
elif [ -d $fn ]
then
echo "$fn is Directory file"
elif [ -x $fn ]
then
echo "$fn is Executable file"
elif [ -r $fn ]
then
echo "$fn is Readable file"
elif [ -w $fn ]
then echo "$fn is Writable file"
fi;;
esac

**********************************************************************************************************
***************************************************

OUTPUT:

Enter the Filename:


file
i. Display all the words of a file in ascending order.
ii. Display a file in descending order.
iii. Display a file in reverse order.
iv. Toggle all the characters in the file.
v. Display type of the file.
Enter your choice :
i
File in ascending order:
asdjlasjdsd;jas
askdjaskljdas
is
thdjasdjlasd
unix

**********************************************************************************************************
***************************************************

Script-17: Write a shell script to display the following menu for a particular file:
i.Count the no. of characters,words,lines.
ii.Count no. of words that has exactly five characters and also display them

*************************************************************************************************

echo "Enter the filename: "


read fname
echo "Select from: "
echo "i. Count no. of characters , words , lines."
echo "ii. Count the no. of word that has exactly five characters and also display them."
echo "Enter your choice: "
read c
case $c in
i)ch=`cat $fname | wc -c`
word=`cat $fname | wc -w`
lines=`cat $fname | wc -l`
echo "Number of characters are: $ch"
echo "Number of words are: $word"
echo "Number of lines are: $lines";;
ii)for i in `cat $fname`
do
echo $i >> file
done
x=`cat file | grep -w ..... | wc -w`
echo "Words are: $x they are as follows: "
cat file | grep -w .....
rm -f file
;;
*)echo "Invalid choice.";;
esac

*************************************************************************************************
OUTPUT:

Enter the filename:


file
Select from:
i. Count no. of characters , words , lines.
ii. Count the no. of word that has exactly five characters and also display them.
Enter your choice:
i
Number of characters are: 51
Number of words are: 5
Number of lines are: 4

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-18: Write a shell script to accept file and directory as command line arguments and remove that file from the specified
directory.

*************************************************************************************************

if [ $# -eq 2 ]
then
cd
if [ -d $2 ]
then
x=`ls $2 | grep -wic "$1"`
if [ $x -eq 1 ]
then
rm -f `pwd`/$2/$1
echo "File $1 removed"
else
echo "File not found"
fi
else
echo "Argument passed is not a directory"
fi
else
echo "Invalid option. Usage: 18 file directory"
fi

*************************************************************************************************

OUTPUT:

[s92@popeye TW3]$ sh 18 m 04
Argument passed is not a directory
[s92@popeye TW3]$ sh 18 04 m
File 04 removed

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-19: Write a shell script to get a group name and display all the users who are group member of it.
Also display how many of them are currently active.

*************************************************************************************************

echo "Enter the group name: "


read g
no=`cat /etc/group | grep -w $g | cut -d ":" -f 3`
echo "The users of $g group are : "
cat /etc/passwd | grep -w $no | cut -d ":" -f 1 > file

for i in `cat file`


do
x=0
x=`who | grep -c $i`
if [ $x -eq 0 ]
then
echo "$i - not Logged on."
else
echo "$i - Logged on."
fi
done
*************************************************************************************************

OUTPUT:

Enter the group name:


faculty
The users of faculty group are :
hardik - not Logged on.
himali - not Logged on.
nimisha - not Logged on.
jinali - not Logged on.
chintan - not Logged on.
dishant - not Logged on.
dhaval - not Logged on.
parth - not Logged on.
jill - not Logged on.
minti - not Logged on.
nitesh - not Logged on.
kush - not Logged on.
aashil - not Logged on.
nauka - not Logged on.
archit - not Logged on.
kushal - not Logged on.
nidhi - not Logged on.
parth - not Logged on.

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-20: Write a shell script to get all files of home directory and rename them if their names start with c
Newname=oldname111

*************************************************************************************************

cd
y="111"
c="c"
for i in `ls`
do
if [ -d $i ]
then
x=`echo $i | cut -c 1`
if [ $x = $c ]
then
mv -f $i $i$y
fi
fi
done
*************************************************************************************************

OUTPUT:

Previously->
05 add_K dataentry finduser menudriven t1 usercount
06 b dirname g mul test vowel
09 c display list newfile tw1 while_construct
1 calen e2 log pfile TW1
11 check empinfo log2 print tw-2
*234.txt cin loggedin print123 TW2
a d f2.dat loggein2 printseries tw3
a+b d4 file m s TW3
add data filemenu Maildir sub *.txt

After->
05 add_K dataentry finduser menudriven t1 usercount
06 b dirname g mul test vowel
09 c display list newfile tw1 while_construct
1 calen e2 log pfile TW1
11 check empinfo log2 print tw-2
*234.txt cin111 f loggedin print123 TW2
a d f2.dat loggein2 printseries tw3
a+b d4 file m s TW3
add data filemenu Maildir sub *.txt

*************************************************************************************************
*************************************************************************************************
*************************************************************************************************
*************************************************************************************************

Script-21: Write a shell script to read a string through keyboard and replace that string in the file with new word.

*************************************************************************************************

echo "Enter a string: "


read str
echo "Enter the word to replace with: "
read r
l=`cat file | wc -l`
i=1
sp=" "

while [ $i -le $l ]
do
s=`cat file | head -$i | tail -1`
ss=""
for j in `echo $s`
do
if [ $j = $str ]
then
j=`echo $r`
fi
ss=$ss$sp$j
done
echo $ss >> f
i=`expr $i + 1`
done
cat f > file
rm -f f

*************************************************************************************************

OUTPUT:

Enter a string:
hardik
Enter the word to replace with:
HARDIK

[s92@popeye TW3]$ cat file


10 11 12 13 14 15 16
HARDIK
himali
nimisha
jinali
chintan
dishant
dhaval
parth
jill
minti
nitesh
kush
aashil
nauka
archit
kushal
nidhi
parth

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-22: Write a shell script that displays the directory information in the following format-
Filename Size Date Protection Owner

*************************************************************************************************

x=`ls -l | wc -l`
i=2
echo -e "Filename\t\tSize\tDate\tProtection\tOwner\n"
while [ $i -le $x ]
do
s=`ls -l | head -$i | tail -1 | tr -s " "`
fn=`echo $s | cut -d " " -f 9`
si=`echo $s | cut -d " " -f 5`
d1=`echo $s | cut -d " " -f 6`
d2=`echo $s | cut -d " " -f 7`
p=`echo $s | cut -d " " -f 1`
o=`echo $s | cut -d " " -f 3`
echo -e "$fn\t\t\t$si\t$d1 $d2\t$p\t$o"
i=`expr $i + 1`
done

*************************************************************************************************

OUTPUT:

Filename Size Date Protection Owner

01 2 Feb 7 -rw-r--r-- s112


02 131 Feb 6 -rw-r--r-- s112
03 0 Feb 7 -rw-r--r-- s112
04 128 Jan 4 -rw-r--r-- s112
05 73 Jan 11 -rw-r--r-- s112
06 213 Jan 11 -rw-r--r-- s112
07 72 Feb 6 -rw-r--r-- s112
08 299 Jan 18 -rw-r--r-- s112
09 70 Jan 11 -rw-r--r-- s112
10 363 Feb 5 -rw-r--r-- s112
11 238 Feb 6 -rw-r--r-- s112
12 254 Jan 18 -rw-r--r-- s112
13 129 Feb 6 -rw-r--r-- s112
14 278 Feb 5 -rw-r--r-- s112
15 488 Jan 25 -rw-r--r-- s112
16 1429 Feb 6 -rw-r--r-- s112
17 665 Jan 27 -rw-r--r-- s112
18 475 Feb 6 -rw-r--r-- s112
19 323 Jan 29 -rw-r--r-- s112
20 133 Feb 5 -rw-r--r-- s112

*************************************************************************************************
Script-23: Write a shell script to display the following menu:
i. Change the system prompt to username + current date
ii. No. of ordinary file in the current directory
iii. No. of files which are not accessible by others or group
iv. Display five largest file in the current directory
v. Display all the hidden files in the current directory

*************************************************************************************************
echo "Enter : "
echo "i. Change the system prompt to username + current date"
echo "ii. No. of ordinary file in the current directory"
echo "iii. No. of file which are not accessible by others or group"
echo "iv. Display five largest file in the current directory"
echo "v. Display all hidden files in current directory"
echo "Please enter your choice: "
read c
case "$c" in
i)x=`date`
PS1="$LOGNAME $x";;
ii)k=0
for i in `ls`
do
if [ -f $i ]
then
k=`expr $k + 1`
fi
done
echo "Number of ordinary files are: $k";;
iii)x=`ls -l | grep -wc "....\-\-\-\-\-\-"`
echo "No. of files which are not accessible by others or group are: $x";;
iv) echo "The Five largest files in the current directory."
ls -Sl | tr -s " " | head -6 | cut -d " " -f 9;;
v) echo "All hidden files in the current directory are: "
ls -a | tr -s " " | grep -w ^[.] | cut -d " " -f 9;;
*)echo "Invalid option"
esac

*************************************************************************************************

OUTPUT:

Enter :
i. Change the system prompt to username + current date
ii. No. of ordinary file in the current directory
iii. No. of file which are not accessible by others or group
iv. Display five largest file in the current directory
v. Display all hidden files in current directory
Please enter your choice:
ii
Number of ordinary files are: 51

*************************************************************************************************
*************************************************************************************************
*************************************************************************************************
*************************************************************************************************

Script-24: Write a shell script that takes filenames and comment on their size.
Display appropriate message as follows:

"File is empty" - if file is empty


"File is small" - if it contains less than 100 words
"File is large" - if it contains 100 to 1000 words
"File is huge" - if it contains more than 1000 lines
*************************************************************************************************

if [ $# -gt 0 ]
then
for i in `echo $*`
do
w=`cat $i | wc -w`
s=`ls -l $i | tr -s "" | cut -d " " -f 5`
l=`cat $i | wc -l`
if [ $s -eq 0 ]
then
echo "$i - File is empty"
elif [ $w -gt 0 -a $w -lt 100 ]
then
echo "$i - File is small"
elif [ $w -ge 100 -a $w -le 1000 ]
then
echo "$i - File is Large"
else
echo "$i - File is Huge"
fi
done
else
echo "Invalid argument"
echo "Usage: 24 File1 file2....."
fi

*************************************************************************************************

OUTPUT:

[s92@popeye TW3]$ sh 24
Invalid argument
Usage: 24 File1 file2.....
[s92@popeye TW3]$ sh 24 file
file - File is small

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-25: Write a shell script to display the following at login time:


i. Calendar of the current month and year.
ii. Display "Good Morning/Good Afternoon/Good Evening" according to the current login time
iii. User,Users home directory
iv. Terminal name, Terminal type.
v. Machine name
vi. No. of users who are currently logged in; List of users who are currently logged in.

*************************************************************************************************
cal
x=`who am i | tr -s " " | cut -d " " -f 5`
x=`echo $x | cut -d ":" -f 1`
if [ $x -lt 12 ]
then
echo "Good Morning"
elif [ $x -ge 12 -a $x -lt 17 ]
then
echo "Good Afternoon"
else
echo "Good Evening"
fi
echo "Username: $LOGNAME"
echo "HOME directory: $HOME"
tn=`who am i | tr -s " " | cut -d " " -f 6`
echo "Terminal name: $tn"
tn=`who am i | tr -s " " | cut -d " " -f 2`
echo "Machine name: $tn"
n=`who | wc -l`
echo "No. of user logged in : $n they are as follows: "
who | tr -s " " | cut -d " " -f 1

*************************************************************************************************

OUTPUT:

February 2007
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28

Good Morning
Username: s92
HOME directory: /home/sybcas112
Terminal name: (aesics84)
Machine name: pts/7
No. of user logged in : 7 they are as follows:
s81
s92
s72
s66
s106
s62
s84

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-26: write a shell script to display the following menu for a particular file:
i. Count the no. of words that are starting with '0' and ending with '*' and also display them.
ii. Count the no. of occurences of a particular word.

*************************************************************************************************

echo "Enter the file name: "


read fn
echo "Enter: "
echo "i. Count the no. of words thar are starting with '0' and ending with '*'
and also display them"
echo "ii. Count the no. of occurences of a particular word."
echo "Enter your choice: "
read c
for i in `cat $fn`
do
echo $i >> f
done
case $c in
i)x=`cat f | grep -wc "0*$"`
echo "Number of words starting 0 and end with * are: $x"
cat f | grep -w "0*$";;
ii)echo "Enter the word to count occurences : "
read s
x=`cat f | grep -wc $s`
echo "Number of times the word $s is repeated: $x";;
*) echo "Invalid option"
esac
rm -f f

*************************************************************************************************

OUTPUT:

Enter the file name:


file
Enter:
i. Count the no. of words thar are starting with '0' and ending with '*' and also display them
ii. Count the no. of occurences of a particular word.
Enter your choice:
ii
Enter the word to count occurences :
HARDIK
Number of times the word HARDIK is repeated: 2

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************
Script-27: Write a shell script to display the following:
i. Concatenation of two strings.
ii. Rename a file
iii. Delete a file
iv. Edits a file

*************************************************************************************************

echo "Enter: "


echo "i. Concatenation of two strings"
echo "ii. Rename a file"
echo "iii. Delete a file"
echo "iv. Edits a file"
echo "Please enter your choice: "
read c
case $c in
i)echo -e "Enter string1: \c"
read s1
echo -e "Enter string2: \c"
read s2
str=$s1$s2
echo "Concated string is $str";;
ii)echo "Enter a file: "
read f
echo "Enter new name of file: "
read nf
mv -f $f $nf;;
iii)echo "Enter a file: "
read f
rm -f $f;;
iv)echo "Enter a file: "
read f
vi $f;;
*)echo "Invalid Option"
esac

*************************************************************************************************

OUTPUT:

Enter:
i. Concatenation of two strings
ii. Rename a file
iii. Delete a file
iv. Edits a file
Please enter your choice:
i
Enter string1: jack
Enter string2: back
Concated string is jackback

*************************************************************************************************
**********************************************************************************************************
****************************************************************************************
*************************************************************************************************

Script-28: Write a shell script to accept 2 filenames and check i both exist then append the contents of the second file into the first
file.

*************************************************************************************************

echo -e "Enter filename1: \c"


read f1
echo -e "Enter filename2: \c"
read f2
if [ -s $f1 -a -s $f2 ]
then
cat $f2 >> $f1
else
echo "Cannot append"
fi

*************************************************************************************************

OUTPUT:

Enter filename1: f1
Enter filename2: f2
[s92@popeye TW3]$ cat f1
HIHELLP
ASDSAD
Welcome

**********************************************************************************************************
*****************************************************************************************************
Script-29: write a shell script to get user name through keyboard. If that user exists then display all information of that user.
Also check whether that user is active or not.
**********************************************************************************************************
*****************************************************************************************************

echo -e "Enter the username: "


read user
x=`cat /etc/passwd | grep -iw $user`
s=`cat /etc/passwd | grep -wic $user`
if [ $s -eq 1 ]
then
u=`echo $x | cut -d ":" -f 1`
gn=`echo $x | cut -d ":" -f 4`
h=`echo $x | cut -d ":" -f 6`
g=`cat /etc/group | grep -w $gn | cut -d ":" -f 1`
echo "USER INFO: "
echo "Username: $u"
echo "Group no: $gn"
echo "Group Name: $g"
echo "Home directory: $h"
a=`who | grep -wc $u`
if [ $a -eq 1 ]
then
echo "Currently Logged On"
else
echo "Not logged on"
fi
else
echo "User doesn't exist"
fi

**********************************************************************************************************
***************************************************
OUTPUT:

Enter the username:


hardik
USER INFO:
Username: hardik
Group no: 502
Group Name: student
Home directory: /home/hardik
Not logged on

**********************************************************************************************************
*************************************************************
Script-30: Write a shell script to test whether a user is available or not if yes then display its home directory and group name.

**********************************************************************************************************
***************************************************

echo "Enter the username: "


read user
x=`who | grep -wic "$user"`
if [ $x -eq 1 ]
then
s=`cat /etc/passwd | grep -wi $user`
u=`echo $s | cut -d ":" -f 1`
gn=`echo $s | cut -d ":" -f 4`
g=`cat /etc/group | grep -w $gn | cut -d ":" -f 1`
h=`echo $s | cut -d ":" -f 6`
echo "User is available Info as follows: "
echo Username: $u
echo "Group No.: $gn"
echo "Group Name: $g"
echo "Home directory: $h"
else
echo "$user is Unavailable"
fi

**********************************************************************************************************
*************************************************************

OUTPUT:

Enter the username:


s42
User is available Info as follows:
Username: s92
Group No.: 1050
Group Name: sybca
Home directory: /home/sybcas92

**********************************************************************************************************
*************************************************************

Script-32: Write a shell script to display the following menu:


i. change the system prompt to the current directory
ii. No. of executable files in the current directory
iii. Display the last modified file in the current directory
iv. Display all subdirectories in current directory
v. Display the attributes of the current directory

**********************************************************************************************************
***************************************************

echo "Enter : "


echo "i. Change the system prompt to the current directory"
echo "ii. No. of executable files in the directory"
echo "iii. Display last modified file in the current directory"
echo "iv. Display all subdirectories in current directory"
echo "v. Display all attributes of the current directory"
echo "Please enter your choice: "
read c
case "$c" in
i)PS1=`pwd`;;
ii)c=0
for i in `ls`
do
if [ -x $i ]
then
c=`expr $c + 1`
fi
done
echo "No. of executable files are: $c";;
iii)x=`ls -lt | tr -s " " | head -2 | cut -d " " -f 9`
echo -e "The last modified file in the current directory is : $x\c";;
iv)echo -e "All subdirectories in current directory are: \n"
for i in `ls`
do
if [ -d $i ]
then
echo "$i"
fi
done;;
v)x=`ls -al | grep -w ".$" | head -1 |tr -s " " | cut -d " " -f 1`
echo "Attributes of current directory are: $x";;
*)echo "Invalid Option"
esac
********************
**********************************************************************************************************
*************************************************************

OUTPUT:

Enter :
i. Change the system prompt to the current directory
ii. No. of executable files in the directory
iii. Display last modified file in the current directory
iv. Display all subdirectories in current directory
v. Display all attributes of the current directory
Please enter your choice:
v
Attributes of current directory are: drwxr-xr-x

**********************************************************************************************************
***************************************************
Script-33: Write a shell script that
i. changes text to uppercase
ii. Find the reverse of the given number.

**********************************************************************************************************
*************************************************************

echo "Enter : "


echo "i. Change text to uppercase"
echo "ii. Find reverse of given number"
echo "Enter your choice : "
read c
case $c in
i)echo -e "Enter a string: "
read s
s=`echo $s | tr [a-z] [A-Z]`
echo "Converted to uppercase: $s";;
ii)echo -e "Enter number: \c"
read n
m=$n
while [ $n -ne 0 ]
do
r=`expr $n % 10`
f=`expr $f \* 10`
f=`expr $f + $r`
n=`expr $n / 10`
done
echo "Reverse of $m is $f";;
*)echo "Invalid option"
esac

**********************************************************************************************************
*************************************************************

OUTPUT:

Enter :
i. Change text to uppercase
ii. Find reverse of given number
Enter your choice :
i
Enter a string:
hardIk
Converted to uppercase: HARDIK

**********************************************************************************************************
***************************************************
Script-34: Write a shell script to display the calender in the following manner:

i. Display the calendar of months m1 and m2 by `cal m1,m2` command file


ii. Display the calendar of the months from m1 to m2 by `Cal m1-m2` command file.

**********************************************************************************************************
*********************************************************************************

if [ $# -eq 1 ]
then
y="-"
z=","
l=`echo $1 | wc -c`
i=1
c=0
while [ $i -le $l ]
do
x=`echo $1 | cut -c $i`
if [ $x = $y ]
then
c=1
break
elif [ $x = $z ]
then
c=2
break
fi
i=`expr $i + 1`
done
if [ $c -eq 1 ]
then
first=`echo $1 | cut -d "-" -f 1`
second=`echo $1 | cut -d "-" -f 2`
while [ $first -le $second ]
do
cal $first 07
first=`expr $first + 1`
done
elif [ $c -eq 2 ]
then
first=`echo $1 | cut -d "," -f 1`
second=`echo $1 | cut -d "," -f 2`
cal $first 07
cal $second 07
else
echo "Argument not entered correctly"
fi

else
echo "Invalid argument Usage: 34 m1,m2 or 34 m1-m2"
fi

**********************************************************************************************************
**********************************************************************************************************
*****

OUTPUT:

[s92@popeye TW3]$ sh 34 5,7


May 7
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

July 7
Su Mo Tu We Th Fr Sa
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
[s92@popeye TW3]$ sh 34 6-7
June 7
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30

July 7
Su Mo Tu We Th Fr Sa
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

**********************************************************************************************************
**********************************************************************************************************
***************

Script-35: Write a shell script to display the following menu:


i. Display names of all the user currently logged in
ii. Display the names of members of a particular user group
iii. Display names of all users who are in the system
iv. Exit

**********************************************************************************************************
*************************************************************

echo "Enter : "


echo "i. Display names of all the users currently logged in"
echo "ii. Display the names of the members of a particular group"
echo "iii. Display the names of all the who are in the system"
echo "iv. Exit"
echo "Please enter your choice: "
read c
case $c in
i)echo "Users currently logged in are: "
who | tr -s " " | cut -d " " -f 1;;
ii)echo "Enter the name of the group: "
read g
x=`cat /etc/group | grep -wic "$g"`
if [ $x -eq 1 ]
then
gn=`cat /etc/group | grep -wi "$g" | cut -d ":" -f 3`
echo "Members of the group $g are: "
cat /etc/passwd | grep -w $gn | cut -d ":" -f 1
else
echo "Group doesn't exist"
fi;;
iii)echo "All Users who are in the system are: "
cat /etc/passwd | cut -d ":" -f 1;;
iv)exit;;
*)echo "Invalid Option"
esac

**********************************************************************************************************
**********************************************************************************************************
***************
OUTPUT:

Enter :
i. Display names of all the users currently logged in
ii. Display the names of the members of a particular group
iii. Display the names of all the who are in the system
iv. Exit
Please enter your choice:
ii
Enter the name of the group:
student
Members of the group faculty are:
HARDIK
himali
nimisha
jinali
chintan
dishant
dhaval
parth
jill
minti
nitesh
kush
aashil
nauka
archit
kushal
nidhi
parth
**********************************************************************************************************
***************************************************

Script-36: Create file which contains information about items in following manner.
Itemname | item code | item price
Write a shell script which allows you to purchse any item from item list and generates
a printout of a bill.

**********************************************************************************************************
*************************************************************

echo -e "Enter the item to purchase: \c"


read item
x=`cat db36 | grep -wi "$item"`
i=`echo $x | cut -d "|" -f 1`
p=`echo $x | cut -d "|" -f 3`
code=`echo $x | cut -d "|" -f 2`
echo "BILL:"
echo "Item Name: $i"
echo "Item Code: $code"
echo "Price: $p"
**********************************************************************************************************
***************************************************

OUTPUT:

Enter the item to purchase: Pen


BILL:
Item Name: 001
Item Code: Pen
Price: 5

**********************************************************************************************************
***************************************************
Script-37: Create a file which contains information about employees.
The sample record is
Iyer|chandra|2007|35 cement road, nagpur|5000
Write a shell script with three functionality
i. To add new employee in the file
ii. To get information of any employee
iii. to display all employees whose basic pay is between 1000 to 3999

**********************************************************************************************************
**********************************************************************************************************
*****

echo "Enter : "


echo "i. To add new employee in file"
echo "ii. To get information of any employee by entering name"
echo "iii. To display all employees whose basic pay is between 1000 to 3999"
echo "Enter your choice: "
read c
case $c in
i)echo -e "Enter Surname: \c"
read sn
echo -e "Enter Name: \c"
read n
echo -e "Enter Year of joining: \c"
read y
echo -e "Enter Address: \c"
read a
echo -e "Enter Basic: \c"
read b
echo "$sn|$n|$y|$a|$b" >> db37;;
ii)echo -e "Enter the name of employee: \c"
read n
u=`cat db37 | grep -wi "$n"`
sn=`echo $u | cut -d "|" -f 1`
n=`echo $u | cut -d "|" -f 2`
y=`echo $u | cut -d "|" -f 3`
a=`echo $u | cut -d "|" -f 4`
b=`echo $u | cut -d "|" -f 5`
echo "Name: $n"
echo "Surname: $sn"
echo "Year: $y"
echo "Address: $a"
echo "Basic: $b";;
iii)x=`cat db37|wc -l`
i=1
echo "Employee with 1000 to 3999 basic are: "
while [ $i -le $x ]
do
u=`cat db37 | head -$i | tail -1`
b=`echo $u | cut -d "|" -f 5`
if [ $b -ge 1000 -a $b -lt 3999 ]
then
c=`echo $u | cut -d "|" -f 2`
sr=`echo $u | cut -d "|" -f 1`
echo $sr $c
fi
i=`expr $i + 1`
done;;
*)echo "Invalid option";;
esac

**********************************************************************************************************
***************************************************

OUTPUT:

Enter :
i. To add new employee in file
ii. To get information of any employee by entering name
iii. To display all employees whose basic pay is between 1000 to 3999
Enter your choice:
ii
Enter the name of employee: hardik
Name: hardik
Surname: shah
Year: 2007
Address: 28,Hardi Park Sco,Naranpura
Basic: 5000

**********************************************************************************************************
****************************************************************************************
Script-38: Write a shell script for simple database management system operation .Database file contains following fields:
Empno,emp_name,address_emp,emp_age ,emp_designation,emp_salary.
Provide a menu driven facility for

i. View Data
ii. View Record
iii. Add Record
iv. Delete Record
v. Exit
**********************************************************************************************************
*************************************************************

echo "Enter : "


echo "i. View Data: "
echo "ii. View Record"
echo "iii. Add Record"
echo "iv. Delete Record"
echo "v. Exit"
echo "Enter your choice: "
read c
case $c in
i)x=`cat db38 | wc -l`
i=1
while [ $i -le $x ]
do
s=`cat db38 | head -$i | tail -1`
n=`echo $s | cut -d "|" -f 1`
nm=`echo $s | cut -d "|" -f 2`
a=`echo $s | cut -d "|" -f 3`
age=`echo $s | cut -d "|" -f 4`
d=`echo $s | cut -d "|" -f 5`
sal=`echo $s | cut -d "|" -f 6`
echo "Emp Code: $n"
echo "Name: $nm"
echo "Address: $a"
echo "Age: $age"
echo "Designation: $d"
echo -e "Salary: $sal\n\n"
i=`expr $i + 1`
done;;
ii)echo -e "Enter employee name to view: \c"
read x
s=`cat db38 | grep -wi "$x"`
n=`echo $s | cut -d "|" -f 1`
nm=`echo $s | cut -d "|" -f 2`
a=`echo $s | cut -d "|" -f 3`
age=`echo $s | cut -d "|" -f 4`
d=`echo $s | cut -d "|" -f 5`
sal=`echo $s | cut -d "|" -f 6`
echo "Emp Code: $n"
echo "Name: $nm"
echo "Address: $a"
echo "Age: $age"
echo "Designation: $d"
echo "Salary: $sal";;
iii)echo -e "Enter Emp no: \c"
read eno
echo -e "Enter name: \c"
read n
echo -e "Enter Address: \c"
read a
echo -e "Enter Age: \c"
read age
echo -e "Enter designation: \c"
read d
echo -e "Enter salary: \c"
read sal
echo "$eno|$n|$a|$age|$d|$sal" >> db38;;
iv)echo -e "Enter the name of the employee to delete: \c"
read em
x=`cat db38 | wc -l`
i=1
while [ $i -le $x ]
do
s=`cat db38 | head -$i | tail -1`
t=`echo $s | grep -wic "$em"`
if [ $t -eq 0 ]
then
echo "$s" >> file
fi
i=`expr $i + 1`
done
mv -f file db38;;
v)exit;;
*)echo "Invalid Option";;
esac

**********************************************************************************************************
***************************************************

OUTPUT:

Enter :
i. View Data:
ii. View Record
iii. Add Record
iv. Delete Record
v. Exit
Enter your choice:
i
Emp Code: 001
Name: ABC
Address: Ahmedabad
Age: 23
Designation: Manager
Salary: 10000

Emp Code: 002


Name: XYZ
Address: Jamnagar
Age: 45
Designation: Asst.Manager
Salary: 8000

Emp Code: 003


Name: GHJ
Address: Bhuj
Age: 28
Designation: Clear
Salary: 5000

**********************************************************************************************************
****************************************************************************************

Script-39: Write a shell script to accept employee name from the user and display an appropriate message. Assume that an
employee is working on a sinle project. Employee project details are stored in a file project.dat. The details of the work done on
the assigned
Project by the employee are in a file status.dat
The structure:

Project.cat Status.dat
----------- ------------
Emp code Empcode
Empname Project code
Project code Daysworked
Duration

If the duration of the project is the same as the number of days worked on the project, then display the message
<Empname>. Today is the last day to finish the
project and if the number of days are <= 30, then display the message<Empname>,Hurry!
Only <days> are remaining to finish your project. If the number of days is >30 then display the message <Empname>,
schedule yourself. You still have <days> to finis your work.

**********************************************************************************************************
***************************************************************

echo -e "Enter the Employee's Name: \c"


read name
x=`cat project.dat | grep -c -i "$name"`
if [ $x -eq 1 ]
then
d=`cat project.dat | grep -wi "$name" | cut -d "|" -f 4`
code=`cat project.dat | grep -wi "$name" | cut -d "|" -f 1`
w=`cat status.dat | grep -wi "$code" | cut -d "|" -f 3`
c=`expr $d - $w`
if [ $c -eq 0 ]
then
echo "$name,Today is the last day to finish the project"
elif [ $c -le 30 ]
then
echo "$name, Hurry! Only $c days are remaining to finish your project"
else
echo "$name,Schedule yourself, You still have $c days to finish your work"
fi
else
echo "Employee not found"
fi

**********************************************************************************************************
***************************************************
OUTPUT:

Enter the Employee's Name: hardik


hardik,Today is the last day to finish the project

Write a shell script to check whether a given number is prime or not.


echo "Enter a number: "
read num
i=2
f=0
while [ $i -le `expr $num / 2` ]
do
if [ `expr $num % $i` -eq 0 ]
then
f=1
fi
i=`expr $i + 1`
done
if [ $f -eq 1 ]
then
echo "The number is composite"
else
echo "The number is Prime"
fi

--------------------------------------------------------------------------------------------------------------
OUTPUT
Enter a number:
5
The number is Prime

Write a shell script to find the sum of the first n numbers.

echo "Enter a number: "


read num

i=1
sum=0

while [ $i -le $num ]


do
sum=`expr $sum + $i`
i=`expr $i + 1`
done
echo "The sum of first $num numbers is: $sum"
--------------------------------------------------------------------------------------------------------------
Enter a number:
5
The sum of first 5 numbers is: 15

How do I write Bash Script to find Armstrong number

Ans:

#!/bin/bash
#Script to find armstrong number till 500, you can change it
i=1
while((i<=500))
do
c=$i
d=$i
b=0
a=0
#checking each number
while((c>0))
do
#separating each digit
a=$((c%10))
#finding cube of each digit and adding them
b=$((b + a*a*a))
c=$((c/10))
done
if((b==d)); then
echo "$i"
fi
i=$((i+1))
done

Q. How to use array in Bash for taking input and displaying it

Ans:

#!/bin/bash
for((i=0;i<5;i++))
do
echo "enter `expr $i + 1` number"
read arr[$i]
done
echo "the numbers you hav entered are"
for((i=0;i<5;i++))
do
echo ${arr[$i]}
done

Output
Q. How do I print pyramid of stars using function in Bash

Ans.

Before writing bash script lets understand how we going to print this pattern. We do it in two part, first we are going to print part 1
and then we print the part 2.

#!/bin/bash
makePyramid()
{
#Here $1 is the parameter you passed with the function i,e 5
n=$1;

#outer loop is for printing number of rows in the pyramid


for((i=1;i<=n;i++))
do

#This loop print spaces required


for((k=i;k<=n;k++))
do
echo -ne " ";
done
#This loop print part1 of the the pyramid
for((j=1;j<=i;j++))
do
echo -ne "*";
done

#This loop print part 2 of the pryamid.


for((z=1;z<i;z++))
do
echo -ne "*";
done

#This echo used for printing new line


echo;
done
}

#calling function

#change number according to your need


makePyramid 5

Output

Note: You can combine loop of Part1 and Part2 to make it more simple

#!/bin/bash
makePyramid()
{
#Here $1 is the parameter you passed with the function i,e 5
n=$1;

#outer loop is for printing number of rows in the pyramid


for((i=1;i<=n;i++))
do

#This loop print spaces required


for((k=i;k<=n;k++))
do
echo -ne " ";
done

#This loop print part1 and part2 of the the pyramid


for((j=1;j<=2*i-1;j++))
do
echo -ne "*"
done

#This echo used for printing new line


echo;
done
}

#calling function

#change number according to your need


makePyramid 5

Output

Q: How do I check whether a Input String is Palindrome or not in Linux and Unix

Ans:

#!/bin/bash
read -p "Enter the String:" n
len=${#n}
flag=1
for((i=0;i<=len/2;i++))
do
c1="${n:$i:1}"
c2="${n:$len-$i-1:1}"
#comparing single single charcters from begining and end
if [ $c1 != $c2 ];then
flag=0
echo "String is not palindrome"
break
fi
done
if(( $flag==1)); then
echo "Input String is Palindrom"
fi

Output

Q. How do I swap two numbers without using addition and subtraction in Bash

Ans:

#!/bin/bash
read -p "Enter first number :" first
read -p "Enter second number:" sec
echo ""
echo -e "Number before swapping is $first and $sec \n"
#swapping logic
first=$((first*sec))
sec=$((first/sec))
first=$((first/sec))
echo -e "Number after swapping is $first and $sec \n"
Output

Q. How do I add command line arguments in Bash

Ans:

#!/bin/bash
if [ $# -ne 2 ] ; then
echo -e " please provide correct number of arguments"
else
# $1 is first argument and $2 is second .
echo " sum of $1 + $2 is `expr $1 + $2` "
fi

Output

Q. How do I write Shell Script to find Greatest of Three Numbers by If-else statement

Ans:

#!/bin/bash
echo "enter first number"
read first
echo "enter second number"
read sec
echo "enter third number"
read third
if [ $first -gt $sec ] ; then
if [ $first -gt $third ] ; then
echo -e " $first is greatest number "
else
echo -e " $third is greatest number "
fi
else
if [ $sec -gt $third ] ; then
echo -e " $sec is greatest number "
else
echo -e " $third is greatest number "
fi
fi

Output

Q. How do I print pyramid of numbers in Bash

Ans.

Before writing bash script lets understand how we going to print this pattern. We do it in two part, first we are going to print part 1
and then we print the part 2. As you can notice from above figure that, in 2nd part we are printing number in reverse order till 1.

#!/bin/bash

#Taking input
read -p "Enter Number:" number

#Outer loop for printing number of rows in pyramid


for((row=1;row<=number;row++))
do

#Loop for printing required spaces


for((spaces=row;spaces<=number;spaces++))
do
echo -ne " "
done

#Loop for printing 1st part


for((j=1;j<=row;j++))
do
echo -ne "$j"
done

#Loop for printing 2nd part


for((l=(row-1);l>=1;l--))
do
echo -ne "$l"
done

#echo for printing new line


echo
done

Output

Q. How do I write Shell Script to find Greatest of Three Numbers by If-else statement

Ans:

#!/bin/bash
echo "enter first number"
read first
echo "enter second number"
read sec
echo "enter third number"
read third
if [ $first -gt $sec ] ; then
if [ $first -gt $third ] ; then
echo -e " $first is greatest number "
else
echo -e " $third is greatest number "
fi
else
if [ $sec -gt $third ] ; then
echo -e " $sec is greatest number "
else
echo -e " $third is greatest number "
fi
fi

Output
Q. How to use array in Bash for taking input and displaying it

Ans:

#!/bin/bash
for((i=0;i<5;i++))
do
echo "enter `expr $i + 1` number"
read arr[$i]
done
echo "the numbers you hav entered are"
for((i=0;i<5;i++))
do
echo ${arr[$i]}
done

Output

Q. How do I write Shell Script function to find "a" to the power "b"

Ans.

#!/bin/bash
#function to find "a" to the power "b"
power()
{
num=$1
pow=$2
counter=1
result=1
if((pow==0)); then
result=1
fi
if ((num==0)); then
result=0
fi
if((num>=1&&pow>=1)); then
while((counter<=pow))
do
result=$((result*num))
counter=$((counter + 1))
done
fi
#Printing the result
echo "$1 to the power $2 is $result"
}

#main script
read -p "Enter number:" num
read -p "Enter power:" pow

#calling above function


power $num $pow

Output

Q. How do I write shell script to find Smallest and Greatest number in an array

Ans:

#!/bin/bash
echo "enter size of an array"
read n
#taking input from user
for((i=0;i<n;i++))
do
echo " enter $((i+1)) number"
read nos[$i]
done
#printing the entered number
echo "number entered are"
for((i=0;i<n;i++))
do
echo ${nos[$i]}
done
#main loop
small=${nos[0]}
greatest=${nos[0]}
for((i=0;i<n;i++))
do
#logic for smallest number
if [ ${nos[$i]} -lt $small ]; then
small=${nos[$i]}
#logic for greatest number
elif [ ${nos[$i]} -gt $greatest ]; then
greatest=${nos[$i]}
fi
done
#printing smallest and greatest number
echo "smallest number in an array is $small"
echo "greatest number in an array is $greatest"
Q. How do I write Bash Script to add two numbers using function

Ans:

#!/bin/bash
#function to add two numbers
add()
{
x=$1
y=$2
echo -e "Number entered by u are: $x and $y"
echo "sum of $1 and $2 is `expr $x + $y` "
}
# main script
echo "enter first number"
read first
echo "enter second number"
read sec
#calling function
add $first $sec
echo "end of the script"

Output

Q. How do I find factorial of a number using recursion function in Bash

Ans:

#!/bin/bash
#Recursive factorial function
factorial()
{
local=$1
if((local<=2)); then
echo $local
else
f=$((local -1))
#Recursive call
f=$(factorial $f)
f=$((f*local))
echo $f
fi
}
#main script
read -p "Enter the number:" n
if((n==0)); then
echo 1
else
#calling factorial function
factorial $n
fi

Output

Q: How do I find the length of the String in Bash

Ans: There are number of ways to find the length of the String in Bash.

Method 1:
Q. How do I write Shell Script to print number in descending order

Ans:

#!/bin/bash
echo "enter maximum number"
read n
# taking input from user
echo "enter Numbers in array:"
for (( i = 0; i < $n; i++ ))
do
read nos[$i]
done
#printing the number before sorting
echo " Numbers in an array are:"
for (( i = 0; i < $n; i++ ))
do
echo ${nos[$i]}
done
# Now do the Sorting of numbers
for (( i = 0; i < $n ; i++ ))
do
for (( j = $i; j < $n; j++ ))
do
if [ ${nos[$i]} -lt ${nos[$j]} ]; then
t=${nos[$i]}
nos[$i]=${nos[$j]}
nos[$j]=$t
fi
done
done
# Printing the sorted number in descending order
echo -e "\nSorted Numbers "
for (( i=0; i < $n; i++ ))
do
echo ${nos[$i]}
done

Output

Q. How do I write Bubble sort in Bash

Ans:

#!/bin/bash
echo "enter maximum number"
read n
# taking input from user
echo "enter Numbers in array:"
for (( i = 0; i < $n; i++ ))
do
read nos[$i]
done
#printing the number before sorting
echo "Numbers in an array are:"
for (( i = 0; i < $n; i++ ))
do
echo ${nos[$i]}
done
# Now do the Sorting of numbers
for (( i = 0; i < $n ; i++ ))
do
for (( j = $i; j < $n; j++ ))
do
if [ ${nos[$i]} -gt ${nos[$j]} ]; then
t=${nos[$i]}
nos[$i]=${nos[$j]}
nos[$j]=$t
fi
done
done
# Printing the sorted number
echo -e "\nSorted Numbers "
for (( i=0; i < $n; i++ ))
do
echo ${nos[$i]}
done

Output

Here are Logical operators that are used during Shell Script.

OPERATOR DESCRIPTION
cond1 -a cond2 True if cond1 and cond2 are True(Performs AND operation)

cond1 -o cond2 True if con1 or cond2 is True (Perform OR operation)

!cond1 True if cond1 is false

Output

String Comparison Operators in Shell Script


Here are Some String Comparison operators used in Shell Script to compare two Strings.
OPERATOR DESCRIPTION
str1 = str2 True if str1 and str2 are identical
str1 != str2 True if str1 and str2 are not identical
-n str1 True if str1 is not null (size is greater than zero)
-z str1 True if str1 is null
Example

Output

Arithmetic Operators in Shell Script


By Sandeep Kumar 9:33 PM Arithmetic operator, shell script 1 comment

Here are Some Arithmetic Operators Used in Shell Script.

OPERATOR DESCRIPTION
+ Add two Numbers
- Subtract two Numbers
* Multiply two Numbers
/ Division
% Modulus
= Assignment
Note: There should be no space when using Assignment operator.
Note: * is a wild card , therefore we have to suppress it using \ , other wise it will display error message.

Output
Arithmetic Comparison Operators used in Shell Script
Different Arithmetic Comparison operators used in shell script are

1. -lt: It has same meaning as <.

$ cat > arth.sh


#!/bin/bash
num1=1;
num2=2;

if [ $num1 -lt $num2 ] ; then


echo "num1 is less then num2"
else
echo "num2 is less than num1"
fi

Output

$ ./arth.sh
num1 is less then num2

2. -gt : It has same meaning as >.

$ cat > arth.sh


#!/bin/bash
num1=1;
num2=2;

if [ $num2 -gt $num1 ] ; then


echo "num2 is greater then num1"
else
echo "num1 is greater then num2"
fi

Output

$ ./arth.sh
num2 is greater then num1

3. -eq : It has same meaning as == .

$ cat > arth.sh


#!/bin/bash
num1=2;
num2=2;

if [ $num1 -eq $num2 ] ; then


echo "num1 is equal to num2"
else
echo "num2 is not equal to num1"
fi

Output

$ ./arth.sh
num1 is equal to num2

4. -ne : It has same meaning as !=.

$ cat > arth.sh


#!/bin/bash
num1=1;
num2=2;

if [ $num1 -ne $num2 ] ; then


echo "num1 is not equal to num2"
else
echo "num2 is equal to num1"
fi

Output

$ ./arth.sh
num1 is not equal to num2

Other Arithmetic comparison operators are:

1. -ge: It has same meaning as >=.

2. -le: It has same meaning as <=.


Q. How do I write Shell Script to find Sum of digits of a Number

Ans:

#!/bin/bash
echo -e "enter the number"
read n
sum=0
a=$n
while(($n >0))
do
x=`expr $n % 10`
sum=`expr $sum + $x`
n=`expr $n / 10`
done
echo "the sum of $a is $sum"

Output

Q. How do I write Shell Script to print triangle of Numbers

Ans:

#!/bin/bash
for((i=1;i<=5;i++))
do
for((k=1;k<=(5-i);k++))
do
echo -e " \c "
done
for((j=1;j<=i;j++))
do
echo -e " $j \c"
done
echo -e "\n"
done

Output

You might also like