26
Q.1. How to write shell script that will add two nos, which are supplied as command line argument, and if this two nos are not given show error and its usage. Answer: #!/bin/bash if [ $# -ne 2 ] then echo "Usage - $0 x y" echo " Where x and y are two nos for which I will print sum" exit 1 fi echo "Sum of $1 and $2 is `expr $1 + $2`" Q.2.Write Script to find out biggest number from given three nos. Nos are supplies as command line argument. Print error if sufficient arguments are not supplied. Answer: #!/bin/bash if [ $# -ne 3 ];then echo " " echo "Please provide three arguments to proceed" echo " " exit 1 fi FN=$1 SN=$2

Lab Lab2.Doc

Embed Size (px)

DESCRIPTION

LAB

Citation preview

Page 1: Lab Lab2.Doc

Q.1. How to write shell script that will add two nos, which are supplied as command line argument, and if this two nos are not given show error and its usage.Answer:

#!/bin/bash

if [ $# -ne 2 ]then echo "Usage - $0 x y" echo " Where x and y are two nos for which I will print sum" exit 1fi

echo "Sum of $1 and $2 is `expr $1 + $2`"

Q.2.Write Script to find out biggest number from given three nos. Nos are supplies as command line argument. Print error if sufficient arguments are not supplied.Answer:

#!/bin/bash

if [ $# -ne 3 ];then

echo " "

echo "Please provide three arguments to proceed"

echo " "

exit 1

fi

FN=$1

SN=$2

TN=$3

if [ $FN -gt $SN ] && [ $FN -gt $TN];then

echo "$FN is biggest number "

Page 2: Lab Lab2.Doc

elif [ $SN -gt $FN ] && [ $SN -gt $TN ];then

echo "$SN is biggest number"

elif [ $TN -gt $FN ] && [ $TN -gt $SN ];then

echo "$TN is biggest number"

elif [ $FN -eq $SN ] && [ $FN -eq $TN ] && [ $TN -eq $FN ];then

echo "All three numbers are equal"

else

echo "I can not figure out which number is bigger"

fi

Q.3.Write script to print nos as 5,4,3,2,1 using while loop.Answer:

#!/bin/bash

N=5

while test $N != 0

do

echo "$N"

N="`expr $N - 1 `"

done

Page 3: Lab Lab2.Doc

Q.4. Write Script, using case statement to perform basic math operation asfollows+ addition- subtractionx multiplication/ divisionThe name of script must be 'q4' which works as follows$ ./q4 20 / 3, Also check for sufficient command line arguments

Answer:

if [ $# -ne 3 ];then

echo "provide Two argument which you want to add, substract, multiplication, or division"

exit 1

fi

A=$1

B=$2

C=$3

case $2 in

+ ) echo "The sum of $A and $C = `expr $A + $C`" ;;

-) echo "The susbstaction value of $A and $C is `expr $A - $C`";;

\*) echo "The multiplication of $A and $C is `expr $A \* $C`";;

/) echo "The division of $A and $C is `expr $A / $C`";;

*) echo "Please use + ,- , / or * only";;

esac

Page 4: Lab Lab2.Doc

Q.5.Write Script to see current date, time, username, and current directoryAnswer:

#!/bin/bash

echo " "

echo -e "\t\t\t\t\t\t\t\t ## The current date is ## `date +"%D"`"

echo -e "\t\t\t\t\t\t\t\t ## The current time is ## `date +"%H:%M:%S"`"

echo -e "\t\t\t\t\t\t\t\t ## The logged in user is ## `whoami`"

echo -e "\t\t\t\t\t\t\t\t ## The current directory is ## `pwd`"

echo

Q.6.Write script to print given number in reverse order, for eg. If no is 123 it must print as 321.Answer:

#!/bin/bash

if [ "$#" -lt "1" ];then

echo " "

echo "Please enter '123' or '321' to continue"

exit 1

fi

A=$1

if [ $A == 123 ];then

echo "321"

elif [ $A == 321 ];then

echo "123"

fi

Page 5: Lab Lab2.Doc

Q.7.Write script to print given numbers sum of all digit, For eg. If no is 123 it's sum of all digit will be 1+2+3 = 6.Answer:

# Algo:

# 1) Input number n

# 2) Set sum=0, sd=0

# 3) Find single digit in sd as n % 10 it will give (left most digit)

# 4) Construct sum no as sum=sum+sd

# 5) Decrment n by 1

# 6) Is n is greater than zero, if yes goto step 3, otherwise next step

# 7) Print sum

#

if [ $# -ne 1 ]

then

echo "Usage: $0 number"

echo " I will find sum of all digit for given number"

echo " For eg. $0 123, I will print 6 as sum of all digit (1+2+3)"

exit 1

fi

n=$1

sum=0

sd=0

while [ $n -gt 0 ]

Page 6: Lab Lab2.Doc

do

sd=`expr $n % 10`

sum=`expr $sum + $sd`

n=`expr $n / 10`

done

echo "Sum of digit for numner is $sum"

Q.8.How to perform real number (number with decimal point) calculation in Linux

Solution: Use Linux's bc command

Q.9.How to calculate 5.12 + 2.5 real number calculation at $ prompt in Shell ?Solution: Use command as , $ echo 5.12 + 2.5 | bc , here we are giving echo commands output to bc to calculate the 5.12 + 2.5

Q.10.How to perform real number calculation in shell script and store result tothird variable , lets say a=5.66, b=8.67, c=a+b?Answer:

#!/bin/bash

A="5.99"

B="7.69"

C=`echo $A + $B |bc`

echo $C

Q.11.Write script to determine whether given file exist or not, file name is supplied as command line argument, also check for sufficient number of command line argumentAnswer:

#!/bin/bash

if [ $# -ne 1 ];then

echo " "

Page 7: Lab Lab2.Doc

echo "Please provide an file name to continue"

exit 1

fi

if [ -f $1 ];then

echo "$1 file exist"

echo "Shell script name is $0"

echo "No of argument = $#"

fi

Q.12.Write script to determine whether given command line argument ($1) contains "*" symbol or not, if $1 does not contains "*" symbol add it to $1, otherwise show message "Symbol is not required". For e.g. If we called this script Q12 then after giving ,$ Q12 /binHere $1 is /bin, it should check whether "*" symbol is present or not if not it should print Required i.e. /bin/*, and if symbol present then Symbol is not required must be printed. Test your script as$ Q12 /bin$ Q12 /bin/*Answer:

cat "$1" > /tmp/file.$$ 2>/tmp/file0.$$

grep "*" /tmp/file.$$ >/tmp/file0.$$

if [ $? -eq 1 ]then echo "Required i.e. $1/*"else echo "Symbol is Not required" fi

rm -f /tmp/file.$$rm -f /tmp/file0.$$

Page 8: Lab Lab2.Doc

Q.13. Write script to print contains of file from given line number to next given number of lines. For e.g. If we called this script as Q13 and run as$ Q13 5 5 myf , Here print contains of 'myf' file from line number 5 to next 5 line of that file.Answer:

if [ $# -eq 0 ]then echo "$0:Error command arguments missing!" echo "Usage: $0 start_line uptoline filename" echo "Where start_line is line number from which you would like to print file" echo "uptoline is line number upto which would like to print" echo "For eg. $0 5 5 myfile" echo "Here from myfile total 5 lines printed starting from line no. 5 to" echo "line no 10." exit 1fi

## Look for sufficent arg's#

if [ $# -eq 3 ]; then if [ -e $3 ]; then tail +$1 $3 | head -n$2 else echo "$0: Error opening file $3" exit 2 fi else echo "Missing arguments!" fi

Q.14. Write script to implement getopts statement, your script should understand following command line argument called this script Q14,Q14 -c -d -m -eWhere options work as-c clear the screen-d show list of files in current working directory-m start mc (midnight commander shell) , if installed-e { editor } start this { editor } if installedAnswer:

# Q14# -c clear# -d dir# -m mc# -e vi { editor }

Page 9: Lab Lab2.Doc

#

## Function to clear the screen#cls(){ clear echo "Clear screen, press a key . . ." read return}

## Function to show files in current directory #show_ls(){ ls echo "list files, press a key . . ." read return}

## Function to start mc#start_mc(){ if which mc > /dev/null ; then

mcecho "Midnight commander, Press a key . . ."read

elseecho "Error: Midnight commander not installed, Press a key . . ."read

fi return}

## Function to start editor #start_ed(){ ced=$1 if which $ced > /dev/null ; then

$cedecho "$ced, Press a key . . ."read

elseecho "Error: $ced is not installed or no such editor exist, Press a

key . . ."read

fi return}

Page 10: Lab Lab2.Doc

## Function to print help#print_help_uu(){

echo "Usage: $0 -c -d -m -v {editor name}"; echo "Where -c clear the screen"; echo " -d show dir"; echo " -m start midnight commander shell"; echo " -e {editor}, start {editor} of your choice"; return

}

## Main procedure start here## Check for sufficent args#

if [ $# -eq 0 ] ; then print_help_uu exit 1fi

## Now parse command line arguments#while getopts cdme: optdo case "$opt" in

c) cls;;d) show_ls;;m) start_mc;;e) thised="$OPTARG"; start_ed $thised ;;\?) print_help_uu; exit 1;;

esac

done

Q.15. Write script called sayHello, put this script into your startup file called .bash_profile, the script should run as soon as you logon to system, and it print any one of the following message in infobox using dialog utility, if installed in your system, If dialog utility is not installed then use echo statement to print message : -Good MorningGood AfternoonGood Evening , according to system time.Answer:

Page 11: Lab Lab2.Doc

temph=`date | cut -c12-13`

dat =`date +"%A %d in %B of %Y (%r)"`

if [ $temph -lt 12 ];then

mess="Good Morning $LOGNAME, Have a nice day!"

fi

if [ $temph -gt 12 -a $temph -le 16 ];then

mess="Good Afternoon $LOGNAME"

fi

if [ $temph -gt 16 -a $temp -lt 18 ];then

mess="Good Evening $LOGNAME"

fi

if which dialog > /dev/null;then

dialog --backtitle "Linux Shell Script" \

--title "(-: Welcome to Linux :-)" \

--infobox "\n$mess\nThis is $dat" 6 60

echo -n " Press a Key to continue. . . "

read

clear

else

Page 12: Lab Lab2.Doc

echo -e "$mess\nThis is $dat"

fi

Q.16. How to write script, that will print, Message "Hello World" , in Bold and Blink effect, and in different colors like red, brown etc using echo command.Answer:

#!/bin/bash

# To Print bold character #

echo -e "\033[1m Hello World"

# blink effect #

echo -e "\033[5m Blink"

# Back to nnormal #

echo -e "\033[0m Hellow World"

# Red Color Effect#

echo -e "\033[31m Hellow World"

# Green Color Effect #

echo -e "\033[32m Hellow World"

# Blew Color Effect #

echo -e "\033[34m Hellow World"

echo -e "\033[35m Hello World"

echo -e "\033[36m Hellow World"

Page 13: Lab Lab2.Doc

#################################

echo -e "\033[41m Hello World"

echo -e "\033[42m Hello World"

echo -e "\033[43m Hello World"

echo -e "\033[44m Hello World"

echo -e "\033[45m Hellow World"

echo -e "\033[46m Hellow World"

## Back To Original##

echo -e "\033[0m Hello World"

Q.17. Write script to implement background process that will continually print current time in upper right corner of the screen , while user can do his/her normal job at $ prompt.Answer:

echo echo "Digital Clock for Linux"echo "To stop this clock use command kill pid, see above for pid"echo "Press a key to continue. . ."

while :do ti=`date +"%r"` echo -e -n "\033[7s" #save current screen postion & attributes # # Show the clock # tput cup 0 69 # row 0 and column 69 is used to show clock echo -n $ti # put clock on screen echo -e -n "\033[8u" #restore current screen postion & attributs # #Delay fro 1 second # sleep 1

Page 14: Lab Lab2.Doc

done

Q.18. Write shell script to implement menus using dialog utility. Menu-items and action according to select menu-item is as follows:

Menu-Item Purpose Action for Menu-Item

Date/time To see current date time Date and time must be shown using infobox of dialog utility

Calendar To see current calendar Calendar must be shown using infobox of dialog utility

Delete To delete selected file

First ask user name of directory where all files are present, if no name of directory given assumes current directory, then show all files only of that directory, Files must be shown on screen using menus of dialog utility, let the user select the file, then ask the confirmation to user whether he/she wants to delete selected file, if answer is yes then delete the file , report  errors if any while deleting file to user.

Exit To Exit this shell script Exit/Stops the menu driven program i.e. this script

Note: Create function for all action for e.g. To show date/time on screen create function show_datetime().

#!/bin/bash# SCRIPT : menu_dialog.sh# PURPOSE : A menu driven Shell script using dialog utility# which has following options:# Display Today's Date and Time.# Display calendar.# Delete selected file from supplied directory.# List of users currently logged in# Disk Statistics# Exit################################################################################ Checking availability of dialog utility ###############################################################################

# dialog is a utility installed by default on all major Linux distributions.# But it is good to check availability of dialog utility on your Linux box.

which dialog &> /dev/null

[ $? -ne 0 ] && echo "Dialog utility is not available, Install it" && exit 1

Page 15: Lab Lab2.Doc

############################################################################### Define Functions Here ###############################################################################

###################### deletetempfiles function ##############################

# This function is called by trap command# For conformation of deletion use rm -fi *.$$

deletetempfiles(){ rm -f *.$$}

######################## Show_time function #################################

# Shows today's date and time

show_time(){ dialog --backtitle "MENU DRIVEN PROGRAM" --title "DATE & TIME" \ --msgbox "\n Today's Date: `date +"%d-%m-%Y"` \n\n \ Today's Time: `date +"%r %Z"`" 10 60}

####################### show_cal function ###################################

# Shows current month calendar

show_cal(){ dialog --backtitle "MENU DRIVEN PROGRAM" --title "CALENDAR" \ --msgbox "`cal`" 12 25}

####################### deletefile function #################################

# Used to delete file under supplied directory, not including sub dirs.

deletefile(){

dialog --backtitle "MENU DRIVEN PROGRAM" --title "Directory Path" \ --inputbox "\nEnter directory path (Absolute or Relative) \\nPress just Enter for current directory" 12 60 2> temp1.$$

if [ $? -ne 0 ] then rm -f temp1.$$

Page 16: Lab Lab2.Doc

return fi

rmdir=`cat temp1.$$`

if [ -z "$rmdir" ] then dirname=$(pwd) # You can also use `pwd` rmdir=$dirname/* else

# remove trailing * and / from directory path

echo "$rmdir" | grep "\*$" &> /dev/null && rmdir=${rmdir%\*} echo "$rmdir" | grep "/$" &> /dev/null && rmdir=${rmdir%/}

# Check supplied directory exist or not

( cd $rmdir 2>&1 | grep "No such file or directory" &> /dev/null )

# Above codeblock run in sub shell, so your current directory persists.

if [ $? -eq 0 ] then dialog --backtitle "MENU DRIVEN PROGRAM" \ --title "Validating Directory" \ --msgbox "\n $rmdir: No such file or directory \\n\n Press ENTER to return to the Main Menu" 10 60 return fi

# Do you have proper permissions ?

( cd $rmdir 2> /dev/null )

if [ $? -ne 0 ] then dialog --backtitle "MENU DRIVEN PROGRAM" \ --title "Checking Permissions" \ --msgbox "\n $rmdir: Permission denied to access this directory \\n\n Press ENTER to return to the Main Menu" 10 60 return fi

if [ ! -r $rmdir ] then dialog --backtitle "MENU DRIVEN PROGRAM" \ --title "Checking Permissions" \ --msgbox "\n $rmdir: No read permission \\n\n Press ENTER to return to the Main Menu" 10 60

Page 17: Lab Lab2.Doc

return fi

dirname=$rmdir rmdir=$rmdir/* # get all the files under given directory

fi

for i in $rmdir # process each file do

# Store all regular file names in temp2.$$

if [ -f $i ] then echo " $i delete? " >> temp2.$$ fi

done

if [ -f temp2.$$ ] then dialog --backtitle "MENU DRIVEN PROGRAM" \ --title "Select File to Delete" \ --menu "Use [UP/DOWN] keys to move, then press enter \\nFiles under directory $dirname:" 18 60 12 \ `cat temp2.$$` 2> file2delete.$$ else dialog --backtitle "MENU DRIVEN PROGRAM" --title "Select File to Delete" \ --msgbox "\n\n There are no regular files in $dirname directory" 10 60 return fi

rtval=$?

file2remove=`cat file2delete.$$`

case $rtval in

0) dialog --backtitle "MENU DRIVEN PROGRAM" --title "ARE YOU SURE" \ --yesno "\nDo you Want to Delete File: $file2remove" 7 70

if [ $? -eq 0 ] then rm -f $file2remove 2> Errorfile.$$

# Check file successfully deleted or not.

if [ $? -eq 0 ]

Page 18: Lab Lab2.Doc

then dialog --backtitle "MENU DRIVEN PROGRAM" \ --title "Information : FILE DELETED" \ --msgbox "\nFile : $file2remove deleted" 8 70 else dialog --backtitle "MENU DRIVEN PROGRAM" \ --title "Information : ERROR ON DELETION" \ --msgbox "\nProblem in Deleting File: $file2remove \\n\nError: `cat Errorfile.$$` \n\nPress ENTER to return to the Main Menu" 12 70 fi

else dialog --backtitle "MENU DRIVEN PROGRAM" \ --title "Information : DELETION ABORTED" \ --msgbox "Action Aborted: \n\n $file2remove not deleted" 8 70 fi ;;

*) deletetempfiles # Remove temporary files return ;; esac

deletetempfiles # remove temporary files return}

########################## currentusers function ############################

currentusers(){ who > userslist.$$ dialog --backtitle "MENU DRIVEN PROGRAM" \ --title "CURRENTLY LOGGED IN USERS LIST" \ --textbox userslist.$$ 12 60}

############################ diskstats function #############################

diskstats(){ df -h | grep "^/" > statsfile.$$ dialog --backtitle "MENU DRIVEN PROGRAM" \ --title "DISK STATISTICS" \ --textbox statsfile.$$ 10 60}

############################################################################### MAIN STRATS HERE ###############################################################################

trap 'deletetempfiles' EXIT # calls deletetempfiles function on exit

Page 19: Lab Lab2.Doc

while :do

# Dialog utility to display options list

dialog --clear --backtitle "MENU DRIVEN PROGRAM" --title "MAIN MENU" \ --menu "Use [UP/DOWN] key to move" 12 60 6 \ "DATE_TIME" "TO DISPLAY DATE AND TIME" \ "CALENDAR" "TO DISPLAY CALENDAR" \ "DELETE" "TO DELETE FILES" \ "USERS" "TO LIST CURRENTLY LOGGED IN USERS" \ "DISK" "TO DISPLAY DISK STATISTICS" \ "EXIT" "TO EXIT" 2> menuchoices.$$

retopt=$? choice=`cat menuchoices.$$`

case $retopt in

0) case $choice in

DATE_TIME) show_time ;; CALENDAR) show_cal ;; DELETE) deletefile ;; USERS) currentusers ;; DISK) diskstats ;; EXIT) clear; exit 0;;

esac ;;

*)clear ; exit ;; esac

done

Q.19. Write shell script to show various system configuration like1) Currently logged user and his logname2) Your current shell3) Your home directory4) Your operating system type5) Your current path setting6) Your current working directory7) Show Currently logged number of users8) About your os and version ,release number , kernel version9) Show all available shells10) Show mouse settings11) Show computer cpu information like processor type, speed etc

Page 20: Lab Lab2.Doc

12) Show memory information13) Show hard disk information like size of hard-disk, cache memory, model etc14) File system (Mounted)Answer

#!/bin/bash

echo "logged user is = `whoami`" >> /tmp/info.$$$

echo "login name is = "$LOGNAME"" >> /tmp/info.$$$

echo "Current shell is $SHELL" >> /tmp/info.$$$

echo "Home directory is $HOME" >> /tmp/info.$$$

echo "Current path setting is $PATH" >> /tmp/info.$$$

echo "Current working directory $PWD" >> /tmp/info.$$$

echo "Currently `w | awk -F" " '/pts|tty/ {print $1}' | wc -l` accounts login" >> /tmp/info.$$$

echo "The kernel version `uname -r` and relase `uname -v`" >> /tmp/info.$$$

echo "### ###" >> /tmp/info.$$$

echo " " >> /tmp/info.$$$

echo "All available shells" >> /tmp/info.$$$

echo " " >> /tmp/info.$$$

echo "`cat /etc/shells`" >> /tmp/info.$$$

echo " " >> /tmp/info.$$$

echo "# CPU type and speed is #" >> /tmp/info.$$$

echo `cat /proc/cpuinfo |awk -F":" '/vendor_id|cpu MHz/ {print $2}'` >> /tmp/info.$$$

echo " " >> /tmp/info.$$$

echo "# Memory Detail #" >> /tmp/info.$$$

echo "`cat /proc/meminfo |head -n 4`" >> /tmp/info.$$$

echo " " >> /tmp/info.$$$

echo "# Hard Disk Size is #" >> /tmp/info.$$$

Page 21: Lab Lab2.Doc

echo "`fdisk -l /dev/sda | awk -F" " '/Disk/ {print $3 " " $4}' |sed -n '1p' | awk -F"," '{print $1}'`" >> /tmp/info.$$$

echo " " >> /tmp/info.$$$

echo "# Hard disk Scsi id is #" >> /tmp/info.$$$

echo " " >> /tmp/info.$$$

echo "`scsi_id -ug /dev/sda`" >> /tmp/info.$$$

echo " " >> /tmp/info.$$$

echo "# File system detail #" >> /tmp/info.$$$

echo "`df -hT`" >> /tmp/info.$$$

echo " " >> /tmp/info.$$$

if which dialog > /dev/null

then

dialog --backtitle "Linux Info Script" --title "Press UP/Down keys to move " --textbox /tmp/info.$$$ 21 70

else

cat /tmp/info.$$$ | more

fi

rm -f /tmp/info.$$$

Q.20.Write shell script using for loop to print the following patterns on screen

Page 22: Lab Lab2.Doc

Q.21.Write shell script to convert file names from UPPERCASE to lowercase file names or vice versa.Answer