Вы находитесь на странице: 1из 30

1. Write a shell script to find the largest among 3 numbers.

#!/bin/sh
echo "Enter 1st number"
read a
echo "Enter 2nd number"
read b
echo "Enter 3rd number"
read c
if [ $a -gt $b -a $a -gt $c ];then
echo "Greatest number is $a";
elif [ $b -gt $c ] ; then
echo "Greatest number is $b";
else
echo "Greatest number is $c";
fi

OUTPUT
[kamal@localhost ~]$ . ./q1.sh
Enter 1st number
2
Enter 2nd number
13
Enter 3rd number
65
Greatest number is 65

Que 2: Write a shell script to accept a number from user and find its factorial.
!/bin/sh
echo "Enter the number "
read n;
f=1;
for (( i=n ; $i>=1 ; i-- ))
do
f=`expr $f \* $i`;
done
echo "Factorial is $f"
OUTPUT:
[kamal@localhost ~]$ . ./file2.sh
Enter the number
4
Factorial is 24

Que 3: Write a script to accept a file name from user and count the number of words in it
#!/bin/sh
echo "Enter the file name"
read file
count=0
i=" "
for i in `cat $file`
do
count=`expr $count + 1`
done
echo "The number of words are $count"
OUTPUT:
[kamal@localhost ~]$ . ./file3.sh
Enter the file name
file1.txt
The number of words are 8

5. Write script, using case statement to perform basic math operation as follows:
i. + Addition
ii. Subtraction
iii. * Multiplication
iv. / Division
#!/bin/sh
i="y"
echo "Enter the value of a"
read a
echo "Enter the value of b"
read b
while [ $i == "y" ]
do
echo "1.Addition"
echo "2.Subtraction"
echo "3.Multiplication"
echo "4.Division"
echo "Enter the choice"
read ch
case $ch in
1) sum=`expr $a + $b`
echo "Sum is :" $sum;;
2) d=`expr $a - $b`
echo "Difference is: " $d;;
3) m=`expr $a \* $b`
echo "Multiplication is: " $m;;
4) i=`expr $a / $b`
echo "Division is: " $i;;
*) Invalid Choice;;
esac
echo "Do you want to continue?"
read i
if [ $i -ne "y" ]
then
exit
fi
done

OUTPUT
[kamal@localhost ~]$. ./q2.sh
Enter the value of a
4
Enter the value of b
4
1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter the choice
3
Multiplication is : 16
Do you want to continue?
y
1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter the choice
1
Sum is : 8
Do you want to continue?
n
[kamal@localhost ~]$

Que 6(a): Print the following pattern


1
12
123
1234
12345
#!/bin/sh
for (( i=1 ;$i<=5 ;i++ ))
do
for (( j=1 ; $j<=i ; j++ ))
do
echo -n $j
done
echo " "
done
OUTPUT:
[kamal@localhost ~]$ . ./file6a.sh
1
12
123
1234
12345

Que 6(b): Print the following pattern


1
12
123
1234
#!/bin/sh
for (( i=0 ; $i<3 ; i++ ))
do
echo -n " "
done
echo "1"
for (( i=0 ;$i<2; i++ ))
do
echo -n " "
done
for (( i=1 ; $i<3 ; i++ ))
do
echo -n $i
done
echo " "
for (( i=0 ; $i<1; i++))
do
echo -n " "
done
for (( i=1 ; $i<4 ; i++ ))
do
echo -n $i
done
echo " "
for (( i=1 ; $i<5 ; i++ ))
do
echo -n $i
done
echo " "
OUTPUT:
[kamal @localhost ~]$ . ./file6b.sh
1
12
123
1234
[kamal @localhost ~]$

Que 6(c): Print the following pattern


5
54
54 3
5432
543 21
#!/bin/sh
for (( i=5 ;$i>=1 ;i-- ))
do
for (( j=5 ; $j>=i ; j-- ))
do
echo -n $j
done
echo " "
done
OUTPUT:
[kamal @localhost ~]$ . ./file6d.sh
5
54
543
5432
54321
[kamal @localhost ~]$

Que 7:Write script to see current date, time, username and current directory.
#!/bin/sh
echo "Hello, $LOGNAME"
echo "Current date is `date`"
echo "User is `who i am`"
echo "Current direcotry `pwd`"
OUTPUT:
[kamal @localhost ~]$ . ./file7.sh
Hello, kamal
Current date is Tuesday Sep 28 16:48:23 IST 2014
User is kamal pts/1
2014-09-28 16:48 (:1.0)
Current direcotry /home/ kamal
[kamal @localhost ~]$

Que 8:Write script to print given number in reverse order.


#!/bin/sh
echo "Enter a number"
read n
echo "Reverse of the number is "
while [ $n -ne 0 ]
do
r=`expr $n \% 10`
n=`expr $n \/ 10`
echo -n $r
done
echo " "
OUTPUT:
[kamal @localhost ~]$ . ./file8.sh
Enter a number
123
Reverse of the number is
321
[kamal @localhost ~]$

Que 9: Write script to print the sum of all digits of a given number.
#!/bin/sh
echo "Enter a number"
read n
sum=0;
while [ $n -ne 0 ]
do
r=`expr $n % 10`
n=`expr $n / 10`
sum=`expr $sum + $r`
done
echo "The sum of digits is $sum"
OUTPUT:
[kamal @localhost ~]$ . ./file9.sh
Enter a number
222
The sum of digits is 6
[kamal @localhost ~]$

Que 10: Write a script to perform real number calculation and store result to third variable
#!/bin/sh
echo "Enter the first number"
read a
echo "Enter the second number"
read b
c=`echo $a + $b | bc`
echo "Sum is $c"
OUTPUT:
[kamal@localhost ~]$ . ./file10.sh
Enter the first number
5.62
Enter the second number
2.26
Sum is 7.88
[kamal@localhost ~]$

Q11 Write script to swap two files if they exist, otherwise display an error message.
#!/bin/sh
# swap two files (if they exist):
if test -f $1
then
if test -f $2
then
mv $1 tempfile.temp
mv $2 $1
mv tempfile.temp $2
else
echo "$2 is not a file. Quitting"
fi
else
echo "$1 isn't a file"
fi
OUTPUT:
[kamal@localhost ~]$ swap xhgj abc.dat
xhgj is not a file. Quitting
[kamal @localhost ~]$ swap abc.dat hkjs
hkjs isn't a file
[kamal @localhost ~]$ swap abc.dat def.dat

Q12 Write a script to accept some numbers at the command prompt and display their sum.
#!/bin/sh
sum=0
for i in $*
do
sum=`expr $sum + $i`
done
echo "Summation of "$#" no. is: "$sum

OUTPUT
[kamal @localhost ~]$ sh sum.sh 10 20
Summation of 2 no. is: 30

Q13 Write a script to input a file name and check whether the file exists. If yes, then check
whether it is a regular file, directory, symbolic link, pipe, socket, character device or any other
type of file.
#!/bin/sh
function fileinfo
{
if [[ ! -a $1 ]]; then
print "file $1 does not exist."
return 1 # nothing to do
fi
if [[ -d $1 ]]; then
print -n "$1 is a directory that you may "
if [[ ! -x $1 ]]; then
print -n "not "
fi
print "search."
elif [[ -f $1 ]]; then
print "$1 is a regular file."
else
print "$1 is a special file."
fi
if [[ -O $1 ]]; then
print 'you own the file.'
else
print 'you do not own the file.'
fi
if [[ -r $1 ]]; then
print 'you have read permission on the file.'
fi
if [[ -w $1 ]]; then
print 'you have write permission on the file.'
fi
if [[ -x $1 && ! -d $1 ]]; then
print 'you have execute permission on the file.'
fi
return 0
}
OUTPUT:
[kamal @localhost ~]$ ./file1.sh myfilekamal
Myfilekamal is a regular file
you have read permission on the file.

Q14 Write a script to input two strings and compare them, whether they are equal. Also print the
string which is greater (which comes later in the dictionary).
#!/bin/sh
Echo Enter the strings
read str1
read str2
if [ $str1 == $str2 ]
then
echo Two strings entered are equal
fi
if [ -n "$str1" -a -n "$str2" ]
then
echo 'Both $str1 and $str2 are not equal'
fi
if [ $str1 gt $str2 ]
then
echo $str1 is greater
else
echo $str2 is greater
fi
OUTPUT:
[kamal @localhost ~]$ ./eg.sh
Enter the strings
Kamal kamalkishore
Both Kamal kamalkishore are not equal
kamalkishore is greater

Q16 Write a script to accept a character from a user and check whether it is an alphabet, a
number or a special symbol.

#!/bin/sh
Echo enter a character
read a
case $a in
[0-9]* )
echo "number" ;;
[a-zA-Z]* )
echo "alphabet"
* ) echo "special symbol" ;;
esac
[kamal @localhost ~]$ ./char.sh
enter a character
5
number

Q17 Write a script to sort the array using bubble sort.


#!/bin/sh

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:
[kamal @localhost ~]$ ./sort.sh

enter maximum number


5
enter Numbers in array:
3
1
65
13
6
Numbers in an array are:
3
1
65
13
6
Sorted Numbers
1
3
6
13
65

Q18 Write a script to enter some elements in the array and print them in reverse order.

#!/bin/sh
clear
echo enter the size of array...
read s
echo enter the elements of array
for ((i=0; $i<$s; i++))
do
read a[$i]
done
j=`expr $s - 1`
for ((i=0; $i<$j; i++))
do
temp=${a[$i]}
a[$i]=${a[$j]}
a[$j]=$temp
j=`expr $j - 1`
done
echo The reverse array is
for ((i=0; $i<$s; i++))
do
echo ${a[$i]}
done
OUTPUT:
[kamal @localhost ~]$ ./rev.sh
enter the size of array.
4
enter the elements of array
5
7
1
2
The reverse array is
2
1
7
5

Q19 Display all the command line arguments supplied by user using shift (also called positional
parameters).

#!/bin/bash
echo "You start with $# positional parameters"
# Loop until all parameters are used up
while [ "$1" != "" ]; do
echo "Parameter 1 equals $1"
echo "You now have $# positional parameters"
# Shift all the parameters down by one
shift
done

Q20 Write a script to concatenate two arrays.


$cat arraymanip.sh
#!/bin/sh
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');

UnixShell=("${Unix[@]}" "${Shell[@]}")
echo ${UnixShell[@]}
echo ${#UnixShell[@]}

OUTPUT:
[kamal @localhost ~]$ ./arraymanip.sh
Debian Red hat Ubuntu Suse Fedora UTS OpenLinux bash csh jsh rsh ksh rc tcsh
14

Q24 Write a script to enter some numbers in the array and print the sum of all the numbers.
#!/bin/sh
echo "Enter numbers"
read numbers
# Initialise min and max with first number in sequence
for i in $numbers; do
min=$i
max=$i

break
done
total=0
count=0
for i in $numbers; do
total=$((total+i))
done
echo "Total: $total"
OUTPUT:
[kamal @localhost ~]$ ./sum.sh
Enter numbers
4618
Total: 19

Q26 Define a function that receives two parameters and returns the larger number.
#!/bin/bash
# max.sh: Maximum of two integers.
E_PARAM_ERR=-198 # If less than 2 params passed to function.
EQUAL=-199
# Return value if both params equal.
max2 ()
# Returns larger of two numbers.
{
# Note: numbers compared must be less than 257.
if [ -z "$2" ]

then
return $E_PARAM_ERR
fi
if [ "$1" -eq "$2" ]
then
return $EQUAL
else
if [ "$1" -gt "$2" ]
then
return $1
else
return $2
fi
fi
}
max2 33 34
return_val=$?
if [ "$return_val" -eq $E_PARAM_ERR ]
then
echo "Need to pass two parameters to the function."
elif [ "$return_val" -eq $EQUAL ]
then
echo "The two numbers are equal."
else
echo "The larger of the two numbers is $return_val."
fi
exit 0
OUTPUT:
[kamal @localhost ~]$ ./largest.sh
34

Q27 Define a function to demonstrate local and global variable visibility.


$ cat localvar.sh
#!/bin/sh
pprint()
{
local lvar="Local content"
echo -e "Local variable value with in the function"
echo $lvar
gvar="Global content changed"
echo -e "Global variable value with in the function"

echo $gvar
}
gvar="Global content"
echo -e "Global variable value before calling function"
echo $gvar
echo -e "Local variable value before calling function"
echo $lvar
pprint
echo -e "Global variable value after calling function"
echo $gvar
echo -e "Local variable value after calling function"
echo $lvar
OUTPUT:
[Sakshi@localhost ~]$ ./t.sh
Global variable value before calling function
Global content
Local variable value before calling function
Local variable value with in the function
Local content
Global variable value with in the function
Global content changed
Global variable value after calling function
Global content changed
Local variable value after calling function

Q31Write a script to search an item in the array.


#!/bin/sh
lsearch()
{
status=-1
for((i=0;i<count;i++))
do

Temp=$1
if [ $Temp -eq ${ARRAY[i]} ]
then
status=0
searches=$((i+1))
return
#
return $((i+1))
# Bash function can return value between 0-255, That's why I assigned
# result to a global variable. This is one of the method to capture
# return value of a function.
fi
done
}
clear
echo "Enter Array Elements : "
read -a ARRAY
count=${#ARRAY[@]}
search=y
while [ "$search" == "y" -o "$search" == "Y" ]
do
echo -n "Enter element to be searched : "
read num
lsearch $num
if [ $status -eq 0 ]
then
echo "$num found after $searches searches"
else
echo "$num not found"
fi
echo -n "Do you want another search (y/n): "
read search
done
OUTPUT:

[kamal @localhost ~]$ linearsearch.sh


Enter Array Elements :
12 34 56 78 90 23 45 56 67 321 66 88 92
Enter element to be searched : 56
56 found after 3 searches
Do you want another search (y/n): y
Enter element to be searched : 321
321 found after 10 searches
Do you want another search (y/n): y
Enter element to be searched : 100
100 not found
Do you want another search (y/n): n

Q32 Write a script to add two numbers using recursion.


#!/bin/sh
#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:
[kamal @localhost ~]$ ./add.sh
enter first number 7
enter first number 8
Number entered by u are: 7 8
sum of 7 and 8 is 15
end of the script

Q 33Write a script that prints good morning, good afternoon and good evening message
according to the time the script is executed.
#!/bin/sh
check=`date +%H`
echo $check
if [ $check -ge 06 -a $check -le 12 ]
then
echo "Good morning"
elif [ $check -ge 12 -a $check -le 17 ]

then
echo "Good afternoon"else
echo "Good evening"
fi
OUTPUT:
[kamal @localhost ~]$ ./pr.sh
Good evening

Q34 Write a script to input some elements in the array and find the largest number.
#!/bin/sh
# This is how to declare / initialize an array:
arrayName=(1 2 3 4 5 6 7)
max=${arrayName[0]}
min=${arrayName[0]}
# Loop through all elements in the array

for i in "${arrayName[@]}"
do
# Update max if applicable
if [[ "$i" -gt "$max" ]]; then
max="$i"
fi
# Update min if applicable
if [[ "$i" -lt "$min" ]]; then
min="$i"
fi
done
# Output results:
echo "Max is: $max"
echo "Min is: $min"
OUTPUT:
[kamal @localhost ~]$ ./max.sh
Max is: 7
Min is: 1

Вам также может понравиться