114
1. #! is called as Ans. shebang 2. Which of the following is not a kind of shell Ans. dsh 3. [ is eqvivalent to Ans. test 4. The difference between printf and echo is Ans. Echo adds a new line after printing, printf does not 5. ". " is used to match Ans. Any one character 6. Which of the following symbols is used as prefix to access the value of variables in scripting Ans. $ 7. The comparison operator " -eq " is used for Ans. Numbers 8. A comment line in a script begins with Ans. #

Quize on scripting shell

Embed Size (px)

Citation preview

Page 1: Quize on scripting shell

1. #! is called as

Ans. shebang

2. Which of the following is not a kind of shell

Ans. dsh

3. [ is eqvivalent to

Ans. test

4. The difference between printf and echo is

Ans. Echo adds a new line after printing, printf does not

5. ". " is used to match

Ans. Any one character

6. Which of the following symbols is used as prefix to access the value of variables in scripting

Ans. $

7. The comparison operator " -eq " is used for

Ans. Numbers

8. A comment line in a script begins with

Ans. #

9. Every line in a shell script ends with

Page 2: Quize on scripting shell

Ans. There is no rule

10. Scripts are made executable using the command

Ans. chmod

Linux/Unix Shell related questions

1. How do you find out what’s your shell? - echo $SHELL

2. What’s the command to find out today’s date? - date

3. What’s the command to find out users on the system? - who

4. How do you find out the current directory you’re in? - pwd

5. How do you remove a file? - rm

6. How do you remove a directory and its subdirectories - rm -rf

7. How do you find out your own username? - whoami

8. How do you send a mail message to somebody? - mail [email protected] -s ‘Your subject’ -c ‘[email protected]

9. How do you count words, lines and characters in a file? - wc

10. How do you search for a string inside a given file? - grep string filename

11. How do you search for a string inside a directory? - grep string *

12. How do you search for a string in a directory with the subdirectories recursed? - grep -r string *

13. What are PIDs? - They are process IDs given to processes. A PID can vary from 0 to 65535.

14. How do you list currently running process? - ps

15. How do you stop a process? - kill pid

16. How do you find out about all running processes? - ps -ag

17. How do you stop all the processes, except the shell window? - kill 0

18. How do you fire a process in the background? - ./process-name &

Page 3: Quize on scripting shell

19. How do you refer to the arguments passed to a shell script? - $1, $2 and so on. $0 is your script name.

20. What’s the conditional statement in shell scripting? - if {condition} then … fi

21. How do you do number comparison in shell scripts? - -eq, -ne, -lt, -le, -gt, -ge

22. How do you test for file properties in shell scripts? - -s filename tells you if the file is not empty, -f filename tells you whether the argument is a file, and not a directory, -d filename tests if the argument is a directory, and not a file, -w filename tests for writeability, -r filename tests for readability, -x filename tests for executability

23. How do you do Boolean logic operators in shell scripting? - ! tests for logical not, -a tests for logical and, and -o tests for logical or.

24. How do you find out the number of arguments passed to the shell script? - $#

25. What’s a way to do multilevel if-else’s in shell scripting? - if {condition} then {statement} elif {condition} {statement} fi

26. How do you write a for loop in shell? - for {variable name} in {list} do {statement} done

27. How do you write a while loop in shell? - while {condition} do {statement} done

28. How does a case statement look in shell scripts? - case {variable} in {possible-value-1}) {statement};; {possible-value-2}) {statement};; esac

29. How do you read keyboard input in shell scripts? - read {variable-name}

30. How do you define a function in a shell script? - function-name() { #some code here return }

31. How does getopts command work? - The parameters to your script can be passed as -n 15 -x 20. Inside the script, you can iterate through the getopts array as while getopts n:x option, and the variable $option contains the value of the entered option.

13. Write a script calculate, which accepts 4 arguments a, b, c, d and prints the value

of a × 20 − b × 2 + c ÷ d to standard output.

An example of executing the script:

$ calculate 2 12 5 2

The value of "2*20 - 12*2 + 5/2" is 18

Page 4: Quize on scripting shell

r=$(((($1*20))-(($2*2))+(($3/$4))))

echo $r

[abcd@linux unix]$ chmod +x u13.sh

[abcd@linux unix]$ ./u13.sh 1 1 1 1

19

Chapter 8 Solutions

Review Questions

1. Because Standard Error and Standard Ouput represent the results of a command and Standard Input represents the input required for a command, only Standard Error and Standard Ouput can be redirected to/from a file. True or False?

Answer: False

2. Before a user-defined variable can be used by processes that run in subshells, that variable must be __________.

a. imported

b. validated by running the env command

c. exported

d. redirected to the BASH shell

Answer: c

3. The alias command can be used to make a shortcut to a single command. True or False?

Page 5: Quize on scripting shell

Answer: True

4. Which of the following files is always executed immediately after a user logs in to a Linux system and receives a BASH shell?

a. /etc/profile

b. ~/.bash_profile

c. ~/.bash_login

d. ~/.profile

Answer: a

5. Which command could you use to see a list of all environment and user-defined shell variables as well as their current values?

a. ls /var

b. env

c. set

d. echo

Answer: c

6. Every if construct begins with if and must be terminated with?

a. end

b. endif

c. stop

d. fi

Answer: d

7. Which of the following will display the message welcome home if the cd /home/user1 command is successfully executed?

a. cd /home/user1 && echo “welcome home”

Page 6: Quize on scripting shell

b. cat “welcome home” || cd /home/user1

c. cd /home/user1 || cat “welcome home”

d. echo “welcome home” && cd /home/user1

Answer: a

8. The current value for the HOME variable is displayed by which of the following commands? (Choose all that apply.)

a. echo HOME=

b. echo ~

c. echo $HOME

d. echo ls HOME

Answer: b, c

9. Which of the following file descriptor numbers represents stdout?

a. 2

b. 0

c. 1

d. 3

Answer: c

10. Which of the following operators reverses the meaning of a test statement?

a. #!

b. -o

c. -a

d. !

Answer: d

Page 7: Quize on scripting shell

11. What would be the effect of using the alias command to make an alias for the date command named cat in honor of your favorite pet?

a. It cannot be done as there already is an environment variable cat associated with the cat command.

b. It cannot be done as there already is a command cat on the system.

c. When you use the cat command at the command prompt with the intention of viewing a text file, the date appears instead.

d. There is no effect until the alias is imported as it is a user-declared variable.

Answer: c

12. How do you indicate a comment line in a shell script?

a. There are no comment lines in a shell script.

b. Begin the line with #!.

c. Begin the line with !.

d. Begin the line with #.

Answer: d

13. You have redirected Standard Error to a file called Errors. You view the contents of this file afterward and notice that there are six error messages. After repeating the procedure, you notice that there are only two error messages in this file. Why?

a. After you open the file and view the contents, the contents are lost.

b. The system generated different Standard Ouput.

c. You did not append the Standard Error to the Error file and as a result, it was overwritten when the command was run a second time.

Page 8: Quize on scripting shell

d. You must specify a new file each and every time you redirect as the system creates the specified file by default.

Answer: c

14. The sed and awk commands are filter commands commonly used to format data within a pipe. True or False?

Answer: True

15. What is wrong with the following command string ls /etc/hosts >listofhostfile?

a. Nothing is wrong with the command.

b. The file descriptor was not declared; unless 1 for Standard Ouput or 2 for Standard Error is indicated, the command will fail.

c. The ls command is one of the commands that cannot be used with redirection; you must use | to pipe instead.

d. The file listofhostfile will always only contain Standard Error as a file descriptor was not declared.

Answer: a

16. Which of the following is not necessarily generated by every command on the system? (Choose all that apply.)

a. Standard Input

b. Standard Deviation

c. Standard Ouput

d. Standard Error

Answer: a, b

17. Which construct can be used in a shell script to read Standard Input and place it in a variable?

a. read

Page 9: Quize on scripting shell

b. sum

c. verify

d. test

Answer: a

18. A variable identifier must _________.

a. not begin with a number

b. not begin with a capital letter

c. start with a number

d. start with an underscore “_”

Answer: a

19. What does >> accomplish when entered on the command line after a command?

a. It redirects both Standard Error and Standard Ouput to the same location.

b. It does not accomplish anything.

c. It redirects Standard Error and Standard Input to the same location.

d. It appends Standard Output to a file.

Answer: d

20. Consider the following shell script:

echo -e “What is your favorite color?--> \c”

read REPLY

if [ “$REPLY” = “red” –o “$REPLY” = “blue” ]

then

echo “The answer is red or blue.”

Page 10: Quize on scripting shell

else

echo “The answer is not red nor blue.”

fi

What would be displayed if a user executes this program and answered Blue when prompted?

a) The answer is red or blue.

b) The answer is not red nor blue.

c) The code would cause an error.

d) The answer is red or blue. The answer is not red nor blue.

Answer: b

#! /bin/bash

#this file displays a list of currently logged in users #followed by the system hostname, time and date, disk #usage, current working directory and pathname to the BASH #shell

echo “Users currently on the system: "

who

echo “\nThe system’s hostname is: \c"

echo $HOSTNAME

echo “\nThe current date and time is: \c"

date

echo “\nCurrent disk usage is: "

df

echo “\nYour present working directory is: \c“

echo $PWD

Page 11: Quize on scripting shell

echo “\nThe pathname to the bash shell is: \c“

echo $BASH

Discovery Exercise 7

#!/bin/bash

#This program calculates a grade from a number entered by #the user

echo “Please enter a grade between 0 and 100 -->\c"

read GRADE

if [ $GRADE –lt 50 ]

then

echo “The grade is F”

elif [ $GRADE –lt 60 –a $GRADE –ge 50 ]

then

echo “The grade is D”

elif [ $GRADE –lt 70 –a $GRADE –ge 60 ]

then

echo “The grade is C”

elif [ $GRADE –lt 80 –a $GRADE –ge 70 ]

then

echo “The grade is B”

elif [ $GRADE –le 100 –a $GRADE ge 80 ]

then

Page 12: Quize on scripting shell

echo “The grade is A”

else

echo "Invalid number – please try again"

fi

Exercise 1: Write a shell script that accepts a file name, starting and ending line numbers as arguments and displays all the lines between the given line numbers. Solution 2 ...

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#

# 01readlines1.sh

#

# Author: Mohammed Ahsan Siddiqui ([email protected])

#

# Synopsis: This script displays the lines of a text file between given starting

# line number and ending line number. It uses 'read' command to read individual

Page 13: Quize on scripting shell

# lines of text file

#

# Arguments: Expects 3 arguments. First argument is the file name, second

# argument is the starting line number (an integer) and third argument also

# an integer which indicates the ending line number

#

# Syntax: ./01readlines1.sh <text_file> <start_line_num> <end_line_num>

#

# Returns: All the text lines between starting line number and ending line

# number

#

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Page 14: Quize on scripting shell

#!/bin/bash # Direct the script to use bash shell for its execution

# Check to see if enough arguments are passed

if [ $# -lt 3 ]

then

echo "Usage: ./01readlines1.sh <text_file> <start_line_num> <end_line_num>"

exit 1

fi

# Ignore if extra arguments supplied

if [ $# -gt 3 ]

then

Page 15: Quize on scripting shell

echo "Usage: ./01readlines1.sh <text_file> <start_line_num> <end_line_num>"

echo "Warning !!!: Ignoring extra arguments !!!"

fi

file_name=$1 # Read the file name

start_line_num=$2 # Read the starting line number

end_line_num=$3 # Read the ending line number

# Check if the text file exists

if [ ! -f $file_name ]

then

echo "File $file_name does not exist"

Page 16: Quize on scripting shell

exit 2

fi

# Check if the starting line number is supplied as an integer

if ! [[ $start_line_num =~ ^[0-9]+$ ]]

then

echo "Starting line number should be an integer"

exit 3

fi

# Check if the ending line number is supplied as an integer

if ! [[ $end_line_num =~ ^[0-9]+$ ]]

then

Page 17: Quize on scripting shell

echo "Ending line number should be an integer"

exit 3

fi

exec 3<&0 # Redirect standard input temporarily to file descriptor 3

exec 0<$file_name # Redirect the standard input from the text file

i=0 # Initiate a variable to keep track of current line read

# from input file

# Read next line, and keep looping while there are still more lines to read

while read line

Page 18: Quize on scripting shell

do

i=`expr $i + 1` # Update the line number by incrementing it by 1

# Check to see if the current line number is between the range

if ( [ $i -ge $start_line_num ] && [ $i -le $end_line_num ] )

then

echo $i " " $line # Display the line number and the line text

fi

done

exec 0<&3 # Restore back the original standard input

Write a shell script that allows a user to enter his or her top three ice cream flavors. Your script should then print out the name of all three flavors.

Page 19: Quize on scripting shell

#!/bin/bash

read -p "Enter your three ice cream flavors : " ice1 ice2 ice3

echo "Thanks $USER!"

echo "1# ${ice1}"

echo "2# ${ice2}"

echo "#3 ${ice3}"

Write a shell script that allows a user to enter any Internet domain name (host name such as www.cyberciti.biz). Your script should than print out the IP address of the Internet domain name.

#!/bin/bash

# Version 1

read -p "Enter any Internet domain name : " domainname

host "${domainname}"

OR

#!/bin/bash

# Version 2

read -p "Enter any Internet domain name : " domainname

host "${domainname}" | grep 'has address'

. Write a shell script that allows a user to enter any existing file name. The program should then copy file to /tmp directory.

#!/bin/bash

Page 20: Quize on scripting shell

# Version 1 (blind copy)

read -p "Enter any file name : " filename

cp $filename /tmp

OR

#!/bin/bash

# Version 2 (first check for $filename and than copy it, else display an error message)

read -p "Enter any file name : " filename

# if file exists, than copy it

if [ -f "${filename}" ]

then

cp -v "$filename" /tmp

else

echo "$0: $filename not found."

fi

9. Write a shell script that allows a user to enter directory name. The program should then create directory name in /tmp directory.

#!/bin/bash

# Version 1 (blind "mkdir directory" command)

read -p "Enter any directory name : " directory

Page 21: Quize on scripting shell

mkdir "/tmp/${directory}"

OR

#!/bin/bash

# Version 2 (Make sure dir does not exist, else display an error message)

read -p "Enter any directory name : " directory

# Make sure dir does not exits

if [ ! -d "/tmp/${directory}" ]

then

mkdir -v "/tmp/${directory}"

else

echo "$0: /tmp/${directory} already exits."

fi

OR

#!/bin/bash

# Version 3

# Make sure dir does not exist, else display an error message

# Use variables

BASE="/tmp"

read -p "Enter any directory name : " directory

Page 22: Quize on scripting shell

# create a path

mydir="${BASE}/${directory}"

# Make sure dir does not exits

if [ ! -d "${mydir}" ]

then

mkdir -v "${mydir}"

else

echo "$0: ${mydir} already exists."

fi

10. Write a shell script that allows a user to enter three file names. The program should then copy all files to USB pen.

#!/bin/bash

# Version 1

PEN="/media/usb"

read -p "Enter three file names : " f1 f2 f3

cp -v "$f1" "$f2" "$f3" $PEN

OR

Page 23: Quize on scripting shell

#!/bin/bash

# Version 2

# Make sure file exits and usb pen is mounted at $PEN

# Set path

PEN="/media/usb"

read -p "Enter three file names : " f1 f2 f3

# Make sure pen drive exits else die

[ ! -d "$PEN" ] && { echo "$0: USB pen drive not found at $PEN"; exit 1; }

# Make sure pen drive is mounted else die

if grep -wq "$PEN" /etc/mtab

then

# Make copy only if file exists, else display an error

[ -f "$f1" ] && cp -v "$f1" $PEN || echo "$0: $f1 not found."

[ -f "$f2" ] && cp -v "$f2" $PEN || echo "$0: $f2 not found."

[ -f "$f3" ] && cp -v "$f3" $PEN || echo "$0: $f3 not found."

else

echo "$0: USB pen is not mounted at $PEN."

fi

11. Write a simple shell script where the user enters a pizza parlor bill total. Your script should then display a 10 percent tip.

Page 24: Quize on scripting shell

#!/bin/bash

# Version 1

clear

echo "*************************"

echo "*** Joes Pizza Parlor ***"

echo "*************************"

echo

echo "Today is $(date)"

echo

read -p "Enter a pizza parlor bill : " bill

tip=$(echo "scale=2; (${bill}*10) / 100" | bc -l)

total=$(echo "scale=2; $tip + $bill" | bc -l)

echo "Pizza bill : $bill"

echo "Tip (10%) : ${tip}"

echo "--------------------------"

echo "Total : ${total}"

echo "--------------------------"

12. Write a simple calculator program that allows user to enter two numeric values and operand as follows. The program should then print out the sum of two numbers. Make sure it works according to entered operand.

#!/bin/bash

Page 25: Quize on scripting shell

read -p "Enter two values : " a b

read -p "Enter operand ( +, -, /, *) : " op

ans=$(( $a $op $b ))

echo "$a $op $b = $ans"

Exercise 2: Write a shell script that deletes all lines containing a specified word in one or more files supplied as arguments to it

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#

# 02dellines1.sh

#

# Author: Mohammed Ahsan Siddiqui ([email protected])

#

# Synopsis: This script deletes all the lines in a given set of files (passed

# as arguments) whenever a line contains a given word (also passed as argument)

#

Page 26: Quize on scripting shell

# Arguments: Expects atleast 2 arguments. First argument is the word that will

# be searched in every line of each file. Starting with second argument and

# afterwards all the remaining arguments will be treated as file names

#

# Syntax: ./02dellines1.sh <search_word> <file_name> [<file_name> ...]

#

# Returns: All the text lines from each mentioned file not containing the

# specified word

#

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#!/bin/bash # Direct the script to use bash shell for its execution

Page 27: Quize on scripting shell

# Check to see if enough arguments are passed

if [ $# -lt 2 ]

then

echo "Usage: ./02dellines1.sh <search_word> <file_name> [<file_name> ...]"

exit 1

fi

search_word=$1 # Read the search word

# Loop through all the supplied arguments

for file_name in "$@"

do

Page 28: Quize on scripting shell

# Skip the search word

if [ "$file_name" = "$1" ]

then

continue

fi

echo $file_name

echo "--------------------"

# Check if the text file exists

if [ ! -f $file_name ]

then

Page 29: Quize on scripting shell

echo "File \"$file_name\" does not exist"

exit 2

fi

# Loop through the file line by line

while read line

do

# if word is not found in current line then display it

if ( ! ( echo $line | grep "$search_word" > /dev/null ) )

then

echo $line # Display the line

fi

Page 30: Quize on scripting shell

done < $file_name

done

Lab Exercise-4

1) Write a shell script to ask your name, program name and enrollment number and print it on the screen.

Echo “Enter your name:”

Read Name

Echo “Enter your program name:”

Read Prog

Echo “Enter your enrollment number:”

Read Enroll

Clear

Echo “Details you entered”

Echo Name: $Name

Echo Program Name: $Prog

Echo Enrolment Number: $Enroll

2) Write a shell script to find the sum, the average and the product of the four integers entered

Echo “Enter four integers with space between”

Read a b c d

Page 31: Quize on scripting shell

Sum =`expr $a + $b + $c + $d`

Avg =`expr $sum / 4`

Dec =`expr $sum % 4`

Dec =`expr \ ($dec \* 1000 \) / 4`

Product =`expr $a \* $b \* $c \* $d`

Echo Sum = $sum

Echo Average = $avg. $dec

Echo Product = $product

3) Write a shell program to exchange the values of two variables

Echo “Enter value for a:”

Read a

Echo “Enter value for b:”

Read b

Clear

Echo “Values of variables before swapping”

Echo A = $a

Echo B = $b

Echo Values of variables after swapping

a = `expr $a + $b`

b = `expr $a – $b`

a = `expr $a – $b`

Echo A = $a

Echo B = $b

Page 32: Quize on scripting shell

4) Find the lines containing a number in a file

Echo “Enter filename”

Read filename

Grep [0-9] $filename

5) Write a shell script to display the digits which are in odd position in a given 5 digit number

Echo “Enter a 5 digit number”

Read num

n = 1

while [ $n -le 5 ]

do

a = `Echo $num | cut -c $n`

Echo $a

n = `expr $n + 2`

done

6) Write a shell program to reverse the digits of five digit integer

Echo “Enter a 5 digit number”

Read num

n = $num

Page 33: Quize on scripting shell

rev=0

while [ $num -ne 0 ]

do

r = `expr $num % 10`

rev = `expr $rev \* 10 + $r`

num = `expr $num / 10`

done

Echo “Reverse of $n is $rev”

7) Write a shell script to find the largest among the 3 given numbers

Echo “Enter 3 numbers with spaces in between”

Read a b c

1 = $a

if [ $b -gt $l ]

then

l = $b

fi

if [ $c -gt $l ]

then

l = $c

fi

Echo “Largest of $a $b $c is $l”

Page 34: Quize on scripting shell

8) Write a shell program to search for a given number from the list of numbers provided using binary search method

Echo “Enter array limit”

Read limit

Echo “Enter elements”

n = 1

while [ $n -le $limit ]

do

Read num

eval arr$n = $num

n = `expr $n + 1`

done

Echo “Enter key element”

Read key

low = 1

high = $n

found = 0

while [ $found -eq 0 -a $high -gt $low ]

do

mid = `expr \( $low + $high \) / 2`

eval t = \$arr$mid

if [ $key -eq $t ]

then

found = 1

Page 35: Quize on scripting shell

elif [ $key -lt $t ]

then

high = `expr $mid – 1`

else

low = `expr $mid + 1`

fi

done

if [ $found -eq 0 ]

then

Echo “Unsuccessful search”

else

Echo “Successful search”

fi

9) Write a shell program to concatenate two strings and find the length of the resultant string

Echo “Enter first string:”

Read s1

Echo “Enter second string:”

Read s2

s3 = $s1$s2

len = `Echo $s3 | wc -c`

len = `expr $len – 1`

Echo “Concatenated string is $s3 of length $len ”

Page 36: Quize on scripting shell

10) Write a shell program to find the position of substring in given string

Echo “Enter main string:”

Read main

l1 = `Echo $main | wc -c`

l1 = `expr $l1 – 1`

Echo “Enter sub string:”

Read sub

l2 = `Echo $sub | wc -c`

l2 = `expr $l2 – 1`

n = 1

m = 1

pos = 0

while [ $n -le $l1 ]

do

a = `Echo $main | cut -c $n`

b = `Echo $sub | cut -c $m`

if [ $a = $b ]

then

n = `expr $n + 1`

m = `expr $m + 1`

pos = `expr $n – $l2`

r = `expr $m – 1`

if [ $r -eq $l2 ]

Page 37: Quize on scripting shell

then

break

fi

else

pos = 0

m = 1

n = `expr $n + 1`

fi

done

Echo “Position of sub string in main string is $pos”

11) Write a shell program to display the alternate digits in a given 7 digit number starting from the first digit

Echo “Enter a 7 digit number”

Read num

n = 1

while [ $n -le 7 ]

do

a = `Echo $num | cut -c $n`

Echo $a

n = `expr $n + 2`

done

12) Write a shell program to find the gcd for the 2 given numbers

Page 38: Quize on scripting shell

Echo “Enter two numbers with space in between”

Read a b

m = $a

if [ $b -lt $m ]

then

m = $b

fi

while [ $m -ne 0 ]

do

x = `expr $a % $m`

y = `expr $b % $m`

if [ $x -eq 0 -a $y -eq 0 ]

then

Echo “gcd of $a and $b is $m”

break

fi

m = `expr $m – 1`

done

13) Write a shell program to check whether a given string is palindrome or not.

Echo “Enter a string to be entered:”

Read str

Echo

Page 39: Quize on scripting shell

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”

14) Write a shell program to find the sum of the series sum=1+1/2+…+1/n

Echo “Enter a number”

Read n

i = 1

sum = 0

Page 40: Quize on scripting shell

while [ $i -le $n ]

do

sum = `expr $sum + \ ( 10000 / $i \)`

i = `expr $i + 1`

done

Echo “Sum n series is”

i = 1

while [ $i -le 5 ]

do

a = `Echo $sum | cut -c $i`

Echo -e “$a\c”

if [ $i -eq 1 ]

then

Echo -e “.\c”

fi

i = `expr $i + 1`

done

15) Write a shell script to find the smallest of three numbers

Echo “Enter 3 numbers with spaces in between”

Read a b c

s = $a

if [ $b -lt $s ]

then

Page 41: Quize on scripting shell

s = $b

fi

if [ $c -lt $s ]

then

s = $c

fi

Echo “Smallest of $a $b $c is $s”

16) Write a shell program to add, subtract and multiply the 2 given numbers passed as command line arguments

add = `expr $1 + $2`

sub = `expr $1 – $2`

mul = `expr $1 \* $2`

Echo “Addition of $1 and $2 is $add”

Echo “Subtraction of $2 from $1 is $sub”

Echo “Multiplication of $1 and $2 is $mul”

17) Write a shell program to convert all the contents into the uppercase in a particular file

Echo “Enter the filename”

Read filename

Echo “Contents of $filename before converting to uppercase”

Echo —————————————————-

cat $filename

Page 42: Quize on scripting shell

Echo —————————————————-

Echo “Contents of $filename after converting to uppercase”

Echo —————————————————

tr ‘[a-z]‘ ‘[A-Z]‘ < $filename Echo ————————————————— 18) Write a shell program to count the characters, count the lines and the words in a particular file Echo “Enter the filename” Read file w = `cat $file | wc -w` c = `cat $file | wc -c` l = `grep -c “.” $file` Echo “Number of characters in $file is $c” Echo “Number of words in $file is $w” Echo “Number of lines in $file is $l” 19) Write a shell program to concatenate the contents of 2 files Echo “Enter first filename” Read first Echo “Enter second filename” Read second cat $first > third

cat $second >> third

Echo “After concatenation of contents of entered two files”

Echo —————————————————-

cat third | more

Echo —————————————————-

20) Write a shell program to count number of words, characters, white spaces and special symbols in a given text

Echo “Enter a text”

Read text

w = `Echo $text | wc -w`

w = `expr $w`

c = `Echo $text | wc -c`

c = `expr $c – 1`

s = 0

alpha = 0

j = ` `

Page 43: Quize on scripting shell

n = 1

while [ $n -le $c ]

do

ch = `Echo $text | cut -c $n`

if test $ch = $j

then

s = `expr $s + 1`

fi

case $ch in

a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z) alpha=`expr $alpha + 1`;;

esac

n = `expr $n + 1`

done

special = `expr $c – $s – $alpha`

Echo “Words = $w”

Echo “Characters = $c”

Echo “Spaces = $s”

Echo “Special symbols = $special”

24) Write a shell program to find factorial of given number

Echo “Enter a number”

Read n

fact = 1

i = 1

Page 44: Quize on scripting shell

while [ $i -le $n ]

do

fact = `expr $fact \* $i`

i = `expr $i + 1`

done

Echo “Factorial of $n is $fact”

25) Write a shell script to find the average of the numbers entered in command line

n = $#

sum = 0

for i in $*

do

sum = `expr $sum + $i`

done

avg = `expr $sum / $n`

Echo “Average=$avg”

26) Write a shell script to sort the given numbers in descending order using Bubble sort

Echo

i = 1

k = 1

Page 45: Quize on scripting shell

Echo “Enter no. of integers to be sorted”

Read n

Echo “Enter the numbers”

while [ $i -le $n ]

do

Read num

x[$k] = `expr $num`

i = `expr $i + 1`

k = `expr $k + 1`

done

x[$k] = 0

k = 1

Echo “The number you have entered are”

while [ ${x[$k]} -ne 0 ]

do

Echo “${x[$k]}”

k = `expr $k + 1`

done

k = 1

while [ $k -le $n ]

do

j = 1

while [ $j -lt $n ]

do

y = `expr $j + 1`

Page 46: Quize on scripting shell

if [ ${x[$j]} -gt ${x[$y]} ]

then

temp = `expr ${x[$j]}`

x[$j] = `expr ${x[$y]}`

x[$y] = `expr $temp`

fi

j = `expr $j + 1`

done

k = `expr $k + 1`

done

k = 1

Echo “Number in sorted order…”

while [ ${x[$k]} -ne 0 ]

do

Echo “${x[$k]}”

k = `expr $k + 1`

done

27) Write a shell program to find the sum of all the digits in a given 5 digit number

Echo “Enter a 5 digit number”

Read num

sum = 0

while [ $num -ne 0 ]

Page 47: Quize on scripting shell

do

r = `expr $num % 10`

sum = `expr $sum + $r`

num = `expr $num / 10`

done

Echo “sum = $sum”

28) Write a shell script to generate fibonacci series

Echo “how many fibonacci numbers do u want “

Read limit

a = 0

b = 1

d = 1

Echo “————————————————————-”

Echo -n $a

Echo -n ” “

while test $d -le $limit

do

c = `expr ${a} + ${b}`

Echo -n $c

Echo -n ” “

b = $a

a = $c

d = `expr $d + 1`

Page 48: Quize on scripting shell

done

29) Shell Script to check whether given year is leap year or not

Echo -n “Enter the year(yyyy) to find leap year :- “

Read year

d = `expr $year % 4`

b = `expr $year % 100`

c = `expr $year % 400`

if [ $d -eq 0 -a $b -ne 0 -o $c -eq 0 ]

then

Echo “year is leap year”

else

Echo “not leap year”

fi

30) Shell Script to print alternate digit when a 7 digit number is passed

Echo -n “Enter a 7 digit number:- “

Read number

len = `echo $number | wc -c`

flag = 1

while test $flag -le $len

do

Echo $number | cut -c$flag

Page 49: Quize on scripting shell

flag = `expr $flag + 2`

done

31) Shell script to find average of number at given command line

total = 0

count = $#

for i #or u can append ( in $*) to get same result.

do

total = `expr $total + $i`

done

avg1 = `expr $total / $count`

avg2 = `expr $total % $count`

avg2 = `expr $avg2 \* 100 / $count`

Echo “The Average is :- $avg1.$avg2″

32) Shell Script to reverse a inputted string and show it

Echo -n “enter the string u want to reverse:-”

Read string

len = `Echo -n $string |wc -c`

Echo “no of character is:- $len”

while test $len -gt 0

do

rev = $rev`Echo $string |cut -c $len`

Page 50: Quize on scripting shell

len = `expr $len – 1`

done

Echo “the reverse string is:-$rev “

33) Shell script to find occurrence of particular digit in inputted number

Echo -n “enter any number:-”

Read number

Echo -n “which digit number do u want to count:-”

Read digit

len = `echo -n $number |wc -c`

Echo “the length of number is:-$len”

count = 0

while test $len -gt 0

do

flag = `Echo -n $number |cut -c $len`

if test $flag -eq $digit

then

count = `expr $count + 1`

fi

len = `expr $len – 1`

done

Echo “|$digit| occurred |$count| times in number ($number)”

34) Shell Script to find whether number given is even or odd

Page 51: Quize on scripting shell

Echo -n “enter any integer number to find even and odd :-”

Read number

rem = `expr $number % 2`

if test $rem -eq 0

then

Echo “number is even”

else

Echo “number is odd”

fi

35) write shell script to generate fibonacci series

#!/bin/bash

#shell script to generate fibonacci series

echo “how many fibonacci numbers do u want “

read limit

a=0

b=1

d=1

echo “————————————————————-”

echo -n $a

echo -n ” “

while test $d -le $limit

do

c=`expr ${a} + ${b}`

echo -n $c

Page 52: Quize on scripting shell

echo -n ” “

b=$a

a=$c

d=`expr $d + 1`

done

36) write shell script to find wheather a particular year is a leap year or not

#!/bin/bash

#shell script to find wheather a particular year is a leap year or not

echo -n “Enter the year(yyyy) to find leap year :- “

read year

d=`expr $year % 4`

b=`expr $year % 100`

c=`expr $year % 400`

if [ $d -eq 0 -a $b -ne 0 -o $c -eq 0 ]

then

echo “year is leap year”

else

echo “not leap year”

fi

37) write shell script to print alternate digits when a 7 digit number is passed as input

Page 53: Quize on scripting shell

#!/bin/bash

#shell script to print alternate digits when a 7 digit number is passed as input

echo -n “Enter a 7 digit number:- “

read number

len=`echo $number | wc -c`

flag=1

while test $flag -le $len

do

echo $number | cut -c$flag

flag=`expr $flag + 2`

done

38) write shell script to find average of numbers given at command line

#Tue May 28 11:12:41 MUT 2002

total=0

count=$#

for i #or u can append ( in $*) to get same result.

do

total=`expr $total + $i`

done

avg1=`expr $total / $count`

avg2=`expr $total % $count`

avg2=`expr $avg2 \* 100 / $count`

echo “The Average is :- $avg1.$avg2″

Page 54: Quize on scripting shell

39) write shell script to find wheather a given word is palindrome or not

#Sun Jun 9 12:06:14 MUT 2002 –By Mukesh

clear

echo -n “enter the name :-”

read name

len=`echo -n $name | wc -c`

echo “Length of the name is :-”$len

while [ $len -gt 0 ]

do

rev=$rev`echo $name | cut -c$len`

len=`expr $len – 1`

done

echo “Reverse of the name is :-”$rev

if [ $name = $rev ]

then echo “It is a palindrome”

else

echo “It is not a palindrome”

fi

40) write shell script to reverse a inputed string and show it.

#!/bin/bash

#shell script to reverse a inputed string and show it.

Page 55: Quize on scripting shell

echo -n “enter the string u want to reverse:-”

read string

len=`echo -n $string |wc -c`

echo “no of character is:- $len”

while test $len -gt 0

do

rev=$rev`echo $string |cut -c $len`

len=`expr $len – 1`

done

echo “the reverse string is:-$rev “

41) write shell script to count occurence of a perticular digit in inputted number.

#!/bin/bash

#shell script to count occurence of a perticular digit in inputted number.

echo -n “enter any number:-”

read number

echo -n “which digit number do u want to count:-”

read digit

len=`echo -n $number |wc -c`

echo “the length of number is:-$len”

count=0

while test $len -gt 0

Page 56: Quize on scripting shell

do

flag=`echo -n $number |cut -c $len`

if test $flag -eq $digit

then

count=`expr $count + 1`

fi

len=`expr $len – 1`

done

echo “|$digit| occured |$count| times in number ($number)”

42) write shell script to find even or odd.

#!/bin/bash

#shell script to find even or odd.

echo -n “enter any integer number to find even and odd :-”

read number

rem=`expr $number % 2`

if test $rem -eq 0

then

echo “number is even”

else

echo “number is odd”

fi

Page 57: Quize on scripting shell

Exercise 6: Write a shell script to list all of the directory files in a directory.

Synopsis: This script lists all the sub-directories in a given directory

#

# Arguments: Expects 0 or 1 argument. Argument should be the name of a

# directory. If argument is omitted then the script will work on current

# directory.

#

# Syntax: ./06listdirs1.sh [<dir_name>]

#

# Returns: The list of all directories in a given directory/current directory

#

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Page 58: Quize on scripting shell

#!/bin/bash # Direct the script to use bash shell for its execution

# Check to see if correct number of arguments are passed

if [ $# -gt 1 ]

then

echo "Usage: ./06listdirs1.sh [<dir_name>]"

exit 1

elif [ $# -eq 1 ] # A directory is passed as an argument

then

if ! [ -d $1 ] # Check if the directory exists

then

echo "$1 is not a directory"

Page 59: Quize on scripting shell

exit 2

fi

dir_to_search=$1 # Read the argument as the name of directory to search

else

dir_to_search="." # Directory to be searched is the current directory

fi

# Go to the search directory

cd $dir_to_search

# Loop through all the contents of the directory

for file_name in `ls`

do

Page 60: Quize on scripting shell

# Check if the current file is a directory and if so display it

[ -d $file_name ] && echo $file_name "is a directory"

done

Exercise 5: Write a shell script that receives any number of file names as its arguments, counts and reports the occurrence of each word that is present in the first argument file on other argument files.

Synopsis: This script counts the frequency of each word (supplied in a text

# file) occuring in a group of files (also supplied as arguments)

#

# Arguments: Expects atleast 2 arguments. First argument is the name of the

# file which contains a list of words which are to be searched. Remaining

# arguments are the names of files in which the words are to be searched

#

# Syntax: ./05countwords.sh <search_file> <file_name> [<file_name> ...]

Page 61: Quize on scripting shell

#

# Returns: The frequency of each word in every file mentioned

#

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#!/bin/bash # Direct the script to use bash shell for its execution

# Check to see if enough arguments are passed

if [ $# -lt 2 ]

then

echo "Usage: ./05countwords.sh <search_file> <file_name> [<file_name> ...]"

exit 1

fi

Page 62: Quize on scripting shell

search_file=$1 # Read the search file name

# Loop through each file supplied as argument to the command

for file_name in "$@"

do

# First file contains search words, so skip it

if [ "$file_name" = "$1" ]

then

continue

fi

Page 63: Quize on scripting shell

# Display the file name

echo "--------------------"

echo $file_name

echo "--------------------"

# Check if the text file exists

if [ ! -f $file_name ]

then

echo "File \"$file_name\" does not exist"

exit 2

fi

# Loop through the search file reading one word per line

Page 64: Quize on scripting shell

while read search_word

do

# Count the frequency of current search word in current file.

# To do that, first replace all tabs (011) and spaces (040) with

# newlines (012). Then remove all the characters except a-z, A-Z

# 0-9, - and newlines. Finally frequency of current search word

word_freq=`tr "[\011\040]" "[\012\012]" < $file_name | \

tr -cd "[a-zA-Z0-9-\012]" | \

grep -c "$search_word"`

# Display the word and its frequency

echo $search_word $word_freq

done < $search_file

Page 65: Quize on scripting shell

done

Exercise 4: Write a shell script that receives any number of file names as its arguments, checks if every argument supplied is a file or a directory and reports accordingly. Whenever the argument is a file, the number of lines on it is also reported.

Synopsis: This script accepts any number of arguments as the names of files

# and directories, checks each argument if it is a file or a directory and

# reports accordingly, and also reports the number of lines if it is a file

#

# Arguments: Expects atleast 1 argument. Arguments should be the names of files

# and/or directories

#

# Syntax: ./04fileordir1.sh <file_name|dir_name> [<file_name|dir_name> ...]

#

# Returns: The supplied arguments as file names along with the type of file and

Page 66: Quize on scripting shell

# number of lines if it is a file

#

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#!/bin/bash # Direct the script to use bash shell for its execution

# Check to see if enough arguments are passed

if [ $# -lt 1 ]

then

echo "Usage: ./04fileordir1.sh <file_name|dir_name> [<file_name|dir_name> ...]"

exit 1

fi

# Loop through all the supplied arguments

for file_name in "$@"

do

# Check if the current file is regular

if [ -f $file_name ]

then

Page 67: Quize on scripting shell

echo $file_name "is a file, and it contains " `cat $file_name | wc -l` \

"lines"

fi

# Check if the current file is a directory

if [ -d $file_name ]

then

echo $file_name "is a directory"

fi

done

Exercise 7: Write a shell script to find factorial of a given number

Synopsis: This script calculates the factorial a number passed as an argument

Page 68: Quize on scripting shell

# to it

#

# Arguments: Expects 1 arguments which must be numeric

#

# Syntax: ./07fact.sh <number>

#

# Returns: Factorial of the number supplied as argument

#

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#!/bin/bash # Direct the script to use bash shell for its execution

# Check to see if 1 argument is passed and it is a number

Page 69: Quize on scripting shell

if ( [ $# -ne 1 ] || echo $1 | grep -E "[^0-9]+" > /dev/null )

then

echo "Usage: ./07fact.sh <number>"

exit 1

fi

i=$1 # A counter

f=1 # Initiate factorial

# Decrease the counter and multiply with current factorial

# till counter becomes 1

while [ $i -gt 0 ]

do

Page 70: Quize on scripting shell

f=`expr $f \* $i` # Update the factorial

i=`expr $i - 1` # Decrease the counter by 1

done

echo $f # Display the factorial

1-. Write a Shell Script that takes a search string and file name from the terminal & displays the results.

read a

read b

word= ‘grep $a $b’

if test ‘echo $word |wc –c’-eq1

then

echo “patern not found”

else

grep $a $b

fi

output-

sh ss1

enter the string to be searched

ashs

enter the file name

Page 71: Quize on scripting shell

ss2

patern not found

2- Write a Shell Script that takes pattern and file name as command line arguments and displays the results appropriately i.e. pattern found/pattern not found.

if test $# -ne 2

then

echo “Invalid no. of arguments”

else

word=’grep $1 $2

if test ‘word | wc –c’ –eq1

then

echo ”pattern not found ”

else

grep $1 $2

echo “pattern found”

fi

fi

output

sh ss2 contents ss12

echo “ \n” content are same second file is being deleted

Page 72: Quize on scripting shell

echo “ \n” content are different

pattern found

3- Write a Shell Script that accepts only three arguments from the command line. The first argument is the pattern string, the second argument is the file name in which the pattern is to be searches and the third argument is the file name in which the result is to be stored.

if test $# -ne3

then echo “Invalid no. of arguments”

else

grep $1 $2 | cat>$3

if test –s $3

then

echo “pattern found”

cat $3

else

echo “pattern not found”

fi

output:

sh ss3 echo ss12 output

pattern found

echo “\n ” content are same second file is being deleted

Page 73: Quize on scripting shell

echo “ \n” content are different

echo “ \n” file does not exist

cat output

echo “ \n” content are different

echo “ \n” file does not exist.

4- Write a Shell Script that accepts a file name as a command line argument and finds out if its a regular file or a directory. If its a regular file, then performs various tests to see if it is readable, writable, executable etc.

if [-d $1]

then

echo It’s a directory

elif [-f $1]

then

echo file exist

if [-r $1]

then

echo file has read permission

echo the content are ----

cat $1

else

file don’t have read permission

fi

if [-w $1]

then

Page 74: Quize on scripting shell

echo “ ”file have write permission

cat >>$1

else

echo you do not have write permission

fi

if [-x $1]

then

echo “ ” file have execute permission

else

you don’t have execute permission

fi

else

echo Nothing exist by this name

fi

Output:

$ sh ss4 free

file exist

file has read permission

the content are _ _ _ _ _

Ashish is a mca student

__ _ _ _ _ _ _ _

You have execute permission

Page 75: Quize on scripting shell

5- Write a Shell Script that computes the factorial of a given number

echo “Enter the no. to compute its factorial”

read num

i=1

fact=1

while test $i –le $num

do

fact = “factorial of : $num is: $fact”

Output:

sh ss6

Enter the no. to compute its factorial

6

Factorial of :6 is: 720

6- Write a Shell Script that works like a calendar reminding the user of certain things depending on the day of the week.

a= `date + % A`

echo “\n” welcome Ashish

echo “\n ” Today is $a

Page 76: Quize on scripting shell

echo your task for today is as follows

case $a in

Monday) echo complete ur Monday task

;;

Tuesday) echo complete ur Tuesday task

;;

Wednesday) echo complete ur Wednesday task

;;

Thursday) echo complete ur Thursday task

;;

Friday) echo complete ur Friday task

;;

Saturday) echo complete ur Saturday task

;;

Sunday) echo complete ur Sunday task

;;

Esac

Output:

Sh ss7

Welcome ashish

Today is Sunday

Complete ur Sunday taske

Page 77: Quize on scripting shell

7- Write a Shell Script that changes the extension of a group of files from txt to doc

echo Before

ls *.txt

for i in `ls *.txt`

domv $i `echo $i|cut -f1 -d"."`.doc

done

echo After

ls *.doc

Output :

$sh ss8

Before

d.txt f.txt r.txt

After

d.doc e?q?w.doc f.doc q?w.doc r.doc w.doc

8- Write a Shell Script that accepts both file name and a set of patterns as positional parameters to a script.

fn=$1

shift

for i in $*

do

Page 78: Quize on scripting shell

grep $i

$fn

done

Output:

ashish@ASHISH-PC:~/File$ sh SS9 ss8 txt doc

ls *.txt

for i in `ls *.txt`

mv $i `echo $i|cut -f1 -d"."`.doc

ls *.doc

ashish@ASHISH-PC:~/File$

9- Write a Shell Script which will redirect the output of the date command without the time into a file.

echo Enter the file name

read file

a=`date|cut -b 1-11,25-28`

echo $a|tee -a $file

clear

echo "\n"$file sucessfully created

echo "\n""Content of file is :"`cat $file`

Output :

Page 79: Quize on scripting shell

sh ss10

Enter the file name

ss2

Thu Nov 20 2008

ss2 sucessfully created

Content of file is :if test $# -ne 2 then echo "Invalid no. of arguments" else word=`grep $1 $2` if test `echo $word|wc -c` -eq 1 then echo "Pattern not found" else grep $1 $2 fi fi Thu Nov 202008

10- Write a Shell Script (using while loop) to execute endlessly (until terminated by user) a loop which displays contents of current directory, disk space status, sleep for 30 seconds and display the users currently logged in on the screen.

char=y

while [ $char ="y" ]

do

ls

df -t

sleep 30

who

echo"Want to continue\(y/n\)?"

read char

done

Page 80: Quize on scripting shell

Output :

sh ss11

cold gold sold ss11 ss14 SS17 ss2 ss22 SS25 SS28 SS30 ss6 SS9

e.txt output ss1 ss12 ss15 ss18 SS20 ss23 SS26 SS29 ss4 ss7 tr.c

f1 q.txt ss10 ss13 ss16 SS19 ss21 SS24 SS27 ss3 SS5 ss8 w.txt

Filesystem 1K-blocks Used Available Use% Mounted on

/dev/sda6 4845056 2476544 2124328 54% /

varrun 452316 96 452220 1% /var/run

varlock 452316 0 452316 0% /var/lock

udev 452316 56 452260 1% /dev

devshm 452316 12 452304 1% /dev/shm

lrm 452316 39760 412556 9% /lib/modules/2.6.24-19-generic/volatile

gvfs-fuse-daemon 4845056 2476544 2124328 54% /home/ashish/.gvfs

ashish tty7 2008-11-20 11:20 (:0)

ashish pts/0 2008-11-20 11:25 (:0.0)

Want to continue\(y/n\)?

11- Write a Shell Script that receives two file names as arguments. It should check whether content of the two files is same or not. If they are same, second file should be deleted.

if [ -f $1 -a -f $2 ]

then

if diff $1 $2

then

Page 81: Quize on scripting shell

cat $1

echo "\n"

cat $2

echo "\n" Contents are same Second file is being deleted

rm $2

else

echo"\n" Contents are different

fi

else

echo "\n" File does not exist

fi

Output:

$ sh ss12 df rt

Ashish

Ashish

Contents are same Second file is being deleted

$

12 - If a number is input through the keyboard, WASS to calculate sum of its digits.

echo Enter a no.

read num

sum=0

Page 82: Quize on scripting shell

while true

do

if test `expr $num % 10` -gt 0

then

temp=`expr $num % 10`

sum=`expr $sum + $temp`

num=`expr $num / 10`

else

echo $sum

exit

fi

Output:

sh ss13

Enter a no.

2345

14

13- Write a Shell Script that performs a count-down either from 10 (default) or from the value that is entered by the user.

echo "Enter the Countdown time."

read n

clear

Page 83: Quize on scripting shell

while [ $n -ge 0 ]

do

echo $n

sleep 1

n=`expr $n – 1`

done

echo Count down timer stopped

Output:

sh ss14

Enter the Countdown time.

3

3

2

1

0

Count down timer stopped

14- Write a Shell Script which takes a command line argument of Kms and by default converts that number into meters. Also provide options to convert km to dm and km to cm.

Km=$1

mt=`expr $km \* 1000`

echo "1.) km to dm"

Page 84: Quize on scripting shell

echo "2 ) km to cm"

echo Enter your choice

read num

case $num in

1)dm=`expr $km \* 10000`

echo $km in meters is :$mt and in decimeters is : $dm

;;

2)cm=`expr $km \* 100000`

echo $km in meters is :$mt and in centimeters is : $cm

;;

esac

Output:

sh ss15 5

5 kms in meters is 5000

km to dm

km to cm

Enter your choice

1

5 in meters is- 5000 and in decimeters is 50000

15- Write a Shell Script using for loop, which displays the message "Welcome to the UNIX System".

Page 85: Quize on scripting shell

for var in $*

do

echo "Welcome to Unix System"

shift 1

done

Output:

sh ss16

Welcome to Unix System

16- Write a Shell Script to change the file name of all files in a directory from lower-case to upper-case.

for i in *

do

mv $i `echo $i|tr "[:lower:]" "[:upper:]"`

done

Output:

sh SS17

mv: `COLD' and `COLD' are the same file

mv: `E.TXT' and `E.TXT' are the same file

mv: `F1' and `F1' are the same file

Page 86: Quize on scripting shell

mv: `GOLD' and `GOLD' are the same file

mv: `Q.TXT' and `Q.TXT' are the same file

mv: `SOLD' and `SOLD' are the same file

mv: `SS1' and `SS1' are the same file

COLD GOLD SOLD SS11 SS14 SS17 SS2 SS22 SS25 SS28 SS30 SS6 SS9

E.TXT OUTPUT SS1 SS12 SS15 SS18 SS20 SS23 SS26 SS29 SS4 SS7 TR.C

F1 Q.TXT SS10 SS13 SS16 SS19 SS21 SS24 SS27 SS3 SS5 SS8 W.TXT

17- Write a Shell Script that examines each file in the current directory. Files whose namesend in old are moved to a directory named old files and files whose names end in .c aremoved to directory named cprograms.

echo Before "\n"

ls -l

mkdir oldfiles cprograms

for var in `ls`

do

if test $var = *old

then

echo "\n" File $var is moved to old files directory

mv $var old files

fi

if test $var = *.c

then

echo"\n" File $var is moved to cprograms directory

mv $var cprograms

Page 87: Quize on scripting shell

fi

done

cd oldfiles

echo "\n" Files in oldfiles

ls -l

cd ..

echo "\n" After"\n"

ls -l

Output:

sh SS18

Before

total 144-rwxrwxrwx 1 ashish ashish 66 2008-11-20 10:07 COLD

-rwxrwxrwx 1 ashish ashish 0 2008-11-20 10:07 E.TXT

-rwxrwxrwx 1 ashish ashish 7 2008-11-20 10:07 F1

-rwxrwxrwx 1 ashish ashish 54 2008-11-20 10:07 GOLD

Files in oldfiles

total 0

After

total 152

-rwxrwxrwx 1 ashish ashish 66 2008-11-20 10:07 COLD

drwxr-xr-x 2 ashish ashish 4096 2008-11-20 12:04 cprograms

-rwxrwxrwx 1 ashish ashish 0 2008-11-20 10:07 E.TXT

-rwxrwxrwx 1 ashish ashish 7 2008-11-20 10:07 F1

Page 88: Quize on scripting shell

-rwxrwxrwx 1 ashish ashish 54 2008-11-20 10:07 GOLD

18- Write a Shell Script which searches all files in the given directory (to be taken as command line argument) for the file having the title (to be taken as command line argument), as the first line in the file.

a) Display the contents of the searched file.

b) In the end, printthe the file is ###, where

### is small-sized if total no. of lines is <50 data-blogger-escaped-span="span">

### is medium-sized if total no. of lines between 50&100

### is large-sized.

for i in `ls $dirnm`

do

f=`echo $1/$i`

if [ -f $f ]

then

if [ `cat $f|head -1` = $2 ]

then

cat $f

if [ `cat $f|wc -l` -lt 50 ]

then

echo $i is small sized

fi

if [ `cat $f|wc -l` -ge 50 -a `cat $f|wc -l` -lt 100 ]

then

Page 89: Quize on scripting shell

echo $i is a medium sized

fi

if [ `cat $f|wc -l` -gt 100 ]

then

echo $i is large sized

fi

fi

fi

done

Output:

sh ss19 newdir AMITY

AMITY

Amity University

file1 is small sized

19- Write a shell script which reports names and sizes of all files in a directory (directory would be supplied as an argument to the shell script) whose size is exceeding 1000 bytes.The file names should be printed in descending order of their sizes. The total number of such files should also be reported.

Cd $1

mkdir

tmp$1

for i in *

Page 90: Quize on scripting shell

do

if [ -f $i ]

then

tmp=`ls -l $i|cut -f5 -d" "`

if [ $tmp -gt 1000 ]

then

ln $i tmp$1/$i

fi

fi

done

ls -lS tmp$1

echo Total number of such files is : `ls tmp$1|wc -w`

rm -r tmp$1

output:

sh SS20

total 4-rw-r--r-- 2 ashish ashish 1392 2008-11-20 11:02 unix output

Total number of such files is : 1

20- WASS for renaming each file in the directory such that it will have the current shell PID as an extension. The shell script should ensure that the directories do not get renamed.

for var in `ls`

do

Page 91: Quize on scripting shell

if test -f $var

then

a=`echo $$`

mv $var $var.$a

fi

done

echo "\n" File name changed:"\n"

ls -l

Output:

sh SS21.7600.a

File name changed:

total 152

-rwxrwxrwx ashish ashish 66 2008-11-20 10:07 COLD.7600.a.a

drwxr-xr-x 2 ashish ashish 4096 2008-11-20 12:04 cprograms

-rwxrwxrwx 1 ashish ashish 0 2008-11-20 10:07 E.TXT.7600.a.a

-rwxrwxrwx 1 ashish ashish 7 2008-11-20 10:07 F1.7600.a.a

-rwxrwxrwx 1 ashish ashish54 2008-11-20 10:07 GOLD.7600.a.a

drwxr-xr-x 2 ashish ashish 4096 2008-11-20 12:04 oldfiles

21- WAP to calculate and print the first m Fibonacci numbers.

echo Enter the series length

Page 92: Quize on scripting shell

read num

x=0

y=1

if test $num -eq 1

then echo $x

else if test $num -eq 2

then echo "$x\n$y"

else

echo "$x\n$y"

i=3

while test $i -le $num

do

temp=`expr $y + $x`

x=$y

y=$temp

echo $y

i=`expr $i + 1`

done

fi

fi

Output:

sh SS22

Enter the series length

Page 93: Quize on scripting shell

6

0

1

1

2

3

22- WASS that will receive any number of file names as arguments. The shell script should check whether such files already exist. If they do, then it should be reported. The files that do not exist should be created in a sub-directory called my dir. The shell script should first check whether the sub-directory my dir exists in the current directory. If it doesn’t exist,then it should be created. If my dir already exists, then it should be reported along with the number of files that are currently present in my dir.

if [ -e mydir ]

then

echo "Directory : mydir exist"

else

echo Do not exist

mkdir mydir

fi

for a in $*

do

echo $a

then

echo "File does not exist "

Page 94: Quize on scripting shell

else

echo “file d

touch $a

mv $a mydir

fi

done

Output:

sh SS23 SS22

Directory : mydir exist

SS22

File does not exists

23- A shell script receives even number of file names. Suppose four file names are supplied,then the first file should get copied into second file, the third file should get copied into fourth and so on. If odd number of file names is supplied then no copying should take place and an error message should be displayed.

if [ `expr $# % 2` -ne 0 ]

thenecho Enter even number of parameters

else

i=0

for k in $*

do

i=`expr $i + 1`

Page 95: Quize on scripting shell

if [ $i -eq 1 ]

then

temp1=$k

fi

if [ $i -eq 2 ]

then

temp2=$k

i=0

cp $temp1 $temp2

fi

done

fi

cat

Output:

$ cat>txt

File Ashish lives in Delhi$ cat>doc

Ashish is a student of MCA$ cat>tree

Ashish is a good student$ cat>wee

His roll no- is A1004807024

$ sh SS24 txt doc tree wee

His roll no- is A1004807024 Ashish is good student Ashish lives id Delhi Ashish is a student of BCA

Page 96: Quize on scripting shell

24- WASS to identify all zero-byte files in the current directory and delete them. Before proceeding with deletion, the shell script should get a conformation from the user.

for i in *

do

if [ -e $i -a -f $i ]

then

if [ -s $i ]

then

echo

else

rm -i $i

fi

fi

done

Output:

sh SS25

rm: remove regular empty file `E.TXT'? y

rm: remove regular empty file `Q.TXT'? n

rm: remove regular empty file `W.TXT'? n

25- WASS to compute the GCD and LCM of two numbers.

echo Enter First number

Page 97: Quize on scripting shell

read n1

echo Enter Second number

read n2

if [ $n1 -lt $n2 ]

then

i=$n1

else

i=$n2

fi

flag=0

while [ $flag -eq 0 ]

do

if [ `expr $n1 % $i` -eq 0 -a `expr $n2 % $i` -eq 0 ]

then

echo GCD of $n1 and $n2 is $i

flag=1

fi

i=`expr $i – 1`

done

Output:

sh SS26

Enter First number

4

Page 98: Quize on scripting shell

Enter Second number

8

GCD of 4 and 8 is 4

26- Two numbers are entered through the keyboard. WAP to find the value of one number raised to the power of another.

read b

echo Enter power

read p

powr=$p

result=1

while [ $p -ge 1 ]

do

result=`expr $result \* $b`

p=`expr $p – 1`

done

echo $b raised to the power $powr is $result

Output:

sh SS27

Enter a number

4

Enter power

2

Page 99: Quize on scripting shell

4 raised to the power 2 is 16

27- WASS that prompts the user for the password. The user has maximum of 3 attempts. If the user enters the correct password, the message “Correct Password” is displayed else the message “Wrong Password”.

echo Set the password first

read passw

i=0

while [ $i -lt 3 ]

do

echo Enter password

read p

if [ $p = $passw ]

then

echo Correct Password

i=3

else

echo Wrong password

i=`expr $i + 1`

fi

done

Output:

sh SS28

Page 100: Quize on scripting shell

Set the password first

ashish

Enter password

ashish

Correct Password

28- WASS that repeatedly asks the user repeatedly for the “Name of the Institution” until the user gives the correct answer.

Flag=0

while [ $flag -eq 0 ]

do

echo Enter name of your institute in capital letters

read inst

if [ $inst = "AMITY" ]

then

echo Correct Answer

flag=1

else

echo Enter Again

fi

done

output:

sh SS29

Page 101: Quize on scripting shell

Enter name of your institute in capital letters

AMITY

Correct Answer

29- WAP to generate all combinations of 1, 2 and 3 using for loop.

for i in 1 2 3

do

for j in 1 2 3

do

for k in 1 2 3

do

echo $i$j$k

done

done

done

Output:

sh SS30

111

112

113

121

122

Page 102: Quize on scripting shell

123

131

132

133

211

212

213

221

222

223

231

232

233

311

312

313

321

322

323

331

332

333