Sie sind auf Seite 1von 40

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

Ans.
str="/tmp/abc"

if [ -f $str ]

then

echo $str is a file

elif [ -d $str ]

then

echo $str is a directory

else

echo $str is neither a file nor directory

fi

Shivam 40417724416
2. Write a shell script to accept a number from user and find its factorial.

Ans.
str="/tmp/abc"

if [ -f $str ]

then

echo $str is a file

elif [ -d $str ]

then

echo $str is a directory

else

echo $str is neither a file nor directory

fi

Shivam 40417724416
3. Write a script to accept a file name from user and count the number of words in it.

Ans.
str="/tmp/abc"
if [ -f $str ]
then
echo $str is a file
elif [ -d $str ]
then
echo $str is a directory
else
echo $str is neither a file nor directory
fi

Shivam 40417724416
4. Accept a string on command line. If it represents a file then show the contents, if it is a
directory show directory listing else display error message

Ans.

str="/tmp/abc"
if [ -f $str ]
then
echo $str is a file
elif [ -d $str ]
then
echo $str is a directory
else
echo $str is neither a file nor directory
fi

Shivam 40417724416
5. Write script, using case statement to perform basic math operation of addition, subtraction,
multiplication and division.

Ans.
echo "Enter Two numbers : "
read a
read b

echo "Enter Choice :"


echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo "4. Division"
read ch

case $ch in
1)res=`expr $a + $b`
;;
2)res=`expr $a - $b`
;;
3)res=`expr $a \* $b`
;;
4)res=`expr $a / $b`
;;
esac
echo "Result : $res"

Shivam 40417724416
6. Write a script to print the following patterns as indicated below:
#
##
###
####
#####
####
###
##
#

Ans.
for r in {1..4}

do

for i in $(seq 1 $r)

do

printf "*"

done

printf "\n"

done

for r in {4..1}

do

for i in $(seq 1 $r)

do

printf "*"

done

printf "\n"

done

Shivam 40417724416
7. Write script to see current date, time, username and current directory

Ans.
echo "Current date is `date`"

echo "User is `who i am`"

echo "Current direcotry `pwd`"

Shivam 40417724416
8. Write script to print given number in reverse order.

Ans.

echo “Enter a number: “


read num
echo $num | rev

Shivam 40417724416
9. Write script to print the sum of all digits of a given number.

Ans.

echo "Enter a Number:"


read n

temp=$n
sd=0
sum=0

while [ $n -gt 0 ]
do
sd=$(( $n % 10 ))
n=$(( $n / 10 ))
sum=$(( $sum + $sd ))
done
echo "Sum is $sum"

Shivam 40417724416
10. Write a script to perform real number calculation and store result to third variable, let’s say
a=5.66, b=4.5, c=a+b

Ans.
echo “Enter 2 real numbers”
read a
read b
c=`echo $a + $b | bc`
echo "$a + $b = $c"

Shivam 40417724416
11. Write a shell script which takes a file name and prints its size

Ans.

echo “Enter Filename”


read FILENAME
FILESIZE=$(stat -c%s "$FILENAME")
echo "Size of $FILENAME = $FILESIZE bytes."

Shivam 40417724416
12. Write a script to accept some numbers at the command prompt and display their sum.

Ans.

if [ $# -ne 2 ] ; then
echo -e " please provide correct number of arguments"
else
echo " sum of $1 + $2 is `expr $1 + $2` "
fi

Shivam 40417724416
13. 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.

Ans.

echo -n "Enter file name : "


read file

[ -a $file ] && A="Exists = yes" || A="Exists = No"

[ -f $file ] && F="Regular File = yes" || F="Regular File = No"

[ -d $file ] && D="Directory = yes" || D="Directory = No"

[ -h $file ] && H="Symbolic Link = yes" || H="Symbolic Link = No"

[ -p $file ] && P="Pipe = yes" || P="Pipe = No"

[ -S $file ] && S="Socket = yes" || S="Socket = No"

[ -c $file ] && C="Character Device = yes" || C="Character Device = No"

echo "$File Check"


echo "$A"
echo "$F"
echo "$D"
echo "$H"
echo "$P"
echo "$S"
echo "$C"

Shivam 40417724416
14. 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).

Ans.

echo "Enter first String"


read s1
echo "Enter second string "
read s2
if [ $s1 = $s2 ]
then
echo "Two strings are equal "
else
echo "Two strings are not equal"
fi
if [[ $s1 < $s2 ]]; then
echo $s1 is greater
else
echo $s2 is greater
fi

Shivam 40417724416
16. Write a shell script to print all prime numbers from 1 to 100.

Ans.
echo "1"
i=3
j=100
flag=0
tem=2

while [ $i -ne $j ]
do
temp=`echo $i`

while [ $temp -ne $tem ]


do
temp=`expr $temp - 1`
n=`expr $i % $temp`

if [ $n -eq 0 -a $flag -eq 0 ]


then
flag=1
fi
done

if [ $flag -eq 0 ]
then
echo $i
else
flag=0
fi
i=`expr $i + 1`
done

Shivam 40417724416
17. Write a script to sort the array using bubble sort

Ans.
echo "enter maximum number"

read n

echo "enter Numbers in array:"

for (( i = 0; i < $n; i++ ))

do

read nos[$i]

done

echo "Numbers in an array are:"

for (( i = 0; i < $n; i++ ))

do

echo ${nos[$i]}

done

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

echo -e "\nSorted Numbers "

for (( i=0; i < $n; i++ ))

do

echo ${nos[$i]}

done

Shivam 40417724416
Shivam 40417724416
18. Write a script to enter some elements in the array and print them in reverse order.
Ans.
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

Shivam 40417724416
19. Display all the command line arguments supplied by user using shift (also called
positional parameters).
Ans.

echo "The script name : $0"


echo "The value of the first argument to the script : $1"
echo "The value of the second argument to the script : $2"
echo "The value of the third argument to the script : $3"
echo "The number of arguments passed to the script : $#"
echo "The value of all command-line arguments (\$* version) : $*"
echo "The value of all command-line arguments (\$@ version) : $@"

Shivam 40417724416
20. Write a script to concatenate two arrays

Ans.

a=(0 1)
b=(1 2)
for((i=0;i<${#a[@]};i++));
do
for ((j=0;j<${#b[@]};j++))
do
c+=(${a[i]}:${b[j]});
done
done

for i in ${c[@]}
do
echo $i
done

Shivam 40417724416
22. Write a shell script to check, if the string entered by user starts from vowel or consonant
Ans.
read -p "Enter something: " char

if [[ "$char" == *[AEIOUaeiou]* ]]; then

echo "vowel"

else

echo "consonant"

fi

Shivam 40417724416
23. Write a shell script which renames all .txt files as .text files
Ans.

for f in *.txt; do

mv -- "$f" "${f%.txt}.text"

done

echo “Extentions changed from .txt to .text”

Shivam 40417724416
24. Write a script to enter some numbers in the array and print the sum of all the numbers

Ans.
read -a array

tot=0

for i in ${array[@]}; do

let tot+=$i

done

echo "Total: $tot"

Shivam 40417724416
25. Write a shell Script to accept 10 numbers from user and sort them in ascending order
Ans.
echo "enter Numbers in array:"

for (( i = 0; i < 10; i++ ))

do

read nos[$i]

done

echo "Numbers in an array are:"

for (( i = 0; i < 10; i++ ))

do

echo ${nos[$i]}

done

for (( i = 0; i < 10 ; i++ ))

do

for (( j = $i; j < 10; j++ ))

do

if [ ${nos[$i]} -gt ${nos[$j]} ]; then

t=${nos[$i]}

nos[$i]=${nos[$j]}

nos[$j]=$t

fi

done

done

echo -e "\nSorted Numbers "

for (( i=0; i < 10; i++ ))

do

echo ${nos[$i]}

done

Shivam 40417724416
Shivam 40417724416
26. Define a function that receives two parameters and returns the larger number.

Ans.
max2 ()
{
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

Shivam 40417724416
27. Define a function to demonstrate local and global variable visibility
Ans.

function innerFunc() {
var='new value'
echo "innerFunc: [var:${var}]"
}

function outerFunc() {
local var='initial value'

echo "outerFunc: before innerFunc: [var:${var}]"


innerFunc
echo "outerFunc: after innerFunc: [var:${var}]"
}

echo "global: before outerFunc: [var:${var}]"


outerFunc
echo "global: after outerFunc: [var:${var}]"

Shivam 40417724416
28. Write a script to accept some strings from command line, assign them in the array and print
the string with the smallest length
Ans.

array=( "$@" )
arraylength=${#array[@]}
for (( i=1; i<${arraylength}+1; i++ ));
do
echo "${array[$i-1]}"
awk 'NR==1{x=$0}length($0)<length(x){x=$0}END{print “Shortest:” x}'
done

Shivam 40417724416
29. Write a script to load an array with some contents, display them, unset the entire array and
load the new contents.

Ans.
array=( apple bat dog elephant frog )
echo Array is : ${array[@]}
unset array[@]
echo After unset Array is : ${array[@]}
declare -a array='([0]="a" [1]="b" [4]="e" [5]="f" [6]="g" [7]="h")'
echo Array is now ${array[@]}

Shivam 40417724416
30. Define a recursive function to display a text message n no. of times.

Ans.
factorial()
{
if [[ $1 -le 1 ]]
then
echo 1
else
last=$(factorial $[$1-1])
echo $(($1 * last))
fi
}
factorial 5

Shivam 40417724416
31. Write a script to search an item in the array
Ans.
arr=()
arr+=('a')
arr+=('b')
arr+=('c')

SEARCH_STRING='b'

if [[ " ${arr[*]} " == *"$SEARCH_STRING"* ]];


then
echo "YES, your arr contains $SEARCH_STRING"
else
echo "NO, your arr does not contain $SEARCH_STRING"
fi

Shivam 40417724416
32. Write a shell script to count the number of ordinary files in root directory.

Ans.

f=0
d=0
for i in `ls -l|tr -s " "|cut -c 1`
do
if [ $i = "-" ]
then
f=`expr $f + 1`
elif [ $i = "d" ]
then
d=`expr $d + 1`
fi
done
echo no of ordinary files are $f
echo no of directories are $d

Shivam 40417724416
33. Write a shell script to determine whether the given string is a palindrome or not

Ans.
echo "Enter a string to be entered:"
read str
echo
len=`echo $str | wc -c`
len=`expr $len - 1`
i=1
j=`expr $len / 2`
while test $i -le $j
do
k=`echo $str | cut -c $i`
l=`echo $str | cut -c $len`
if test $k != $l
then
echo "String is not palindrome"
exit
fi
i=`expr $i + 1`
len=`expr $len - 1`
done
echo "String is palindrome"

Shivam 40417724416
34. Write a shell script which takes a name as parameter and returns the PID(s) of processes
with that name
Ans.

echo "enter process name"


read $proc

ps $proc

Shivam 40417724416
35. Write a script to input names of two files and print the name of the file which is older than
another and also print the permissions assigned to owner, group and others for it.

Ans.
mtf0=`stat -c %Y prac1.sh`
mtf1=`stat -c %Y prac20.sh`
dt=$(( mtf1 - mtf0 ))
[[ $dt -gt 0 ]] && echo "File F1 is newer than file F0"
ls -l | grep 'prac1.sh'
ls -l | grep 'prac20.sh'

Shivam 40417724416
36. Write a shell script to print Fibonacci series
Ans.

echo Enter a Number


read N
a=0
b=1
echo "The Fibonacci series is : "
for (( i=0; i<N; i++ ))
do
echo -n "$a "
fn=$((a + b))
a=$b
b=$fn
done

Shivam 40417724416
37. Write a shell script to display 100 even numbers
Ans.

for i in {1..99}
do
rem=$(($i % 2))
if [ "$rem" -eq "0" ]; then
echo $i
fi
done

Shivam 40417724416
38. Write a shell script to count the number of words enclosed between $ and # symbols
Ans.

echo "enter file"


read $filename

grep '\$(.?)#' $filename -o | wc –l

Shivam 40417724416
39. Write a script to search for the word ‘exam’ in a file and display total no. of matching words
Ans.
echo "enter filename in current directory"
read filename

echo "enter word to be searched"


read word

grep $word $filename -o | wc –l

Shivam 40417724416
40. Write a script to convert seconds accepted from user to hours and minutes.

Ans.
echo "enter seconds"
read secs

printf '%dh:%dm:%ds\n' $(($secs/3600)) $(($secs%3600/60)) $(($secs%60))

Shivam 40417724416

Das könnte Ihnen auch gefallen