Linux Lab Manual,PESCE
-
Upload
gokul-b-s-mandya -
Category
Documents
-
view
231 -
download
0
Transcript of Linux Lab Manual,PESCE
-
8/3/2019 Linux Lab Manual,PESCE
1/22
P E S COLLEGE OF ENGINEERING, MANDYA-571401.[An Autonomous Institution Under VTU, Belguam]
Department of Electronics and Communication Engineering.
A Lab manual for
LINUX AND EMBEDDED SYSTEM
PROGRAMMING LABORATORY
Prepared by,
GOKUL B S
7th
semester (2011-12)
Dept. of E and C
-
8/3/2019 Linux Lab Manual,PESCE
2/22
SHELL
The shell is not a part of the operating system, it is just a C program to provide the interfacebetween the user and the operating system.
The shell commands given at the $ prompt can be grouped together and executed in batchmode. This is known as shell scripting.
The shell allows C like structures such as if-then-else, while-do done, for-do-done, etc.
SOME IMPORTANT INSTRICTIONS BEFORE START-UP
To execute a shell script one has to follow the following steps.1. Open Terminal2. Type vi .sh3. VI editor will be opened. Press 'i' to go to insert mode.4. Type the shell script program.5. Press 'esc'. Type :w to save.6. Press :q to quit.7. Type sh .sh in terminal to execute along with arguments if present.
1. Non-recursive shell script that accepts any number of arguments and prints them in the
reverse order. (For example, if the script rargs, then executing args A B C should produce C B A
on the standard output)
echo "no of arguments are : $#"a=$#while [ $a -ne 0 ]
doeval echo \$$aa=`expr $a - 1`done
RESULT: File name nonrecu.sh
-
8/3/2019 Linux Lab Manual,PESCE
3/22
2.a) Shell script to find the largest of two numbers.
echo "largest of 2nos."echo "enter a no."read xecho "enter another"read y
if [ $x -gt $y ];thenecho "$ x is large"elif [ $y -gt $x ];thenecho "$y is large"elseecho "$x is equal to $y"fi
Result: File name great.sh
2.b) Shell script to find the largest of three numbers.
echo "enter a number"read xecho "enter a number"read yecho "enter third number"
read zif [ $x -gt $y ];thenif [ $x -gt $z ];thenecho "$x is large"fielif [ $y -gt $z ];thenecho "$y is large"else
-
8/3/2019 Linux Lab Manual,PESCE
4/22
echo "$z is large"fi
Result: File name is large3.sh
3. Shell script to delete a name from the given file.
cat file1echo "Enter the name to be deleted:"
read agrep -v $a file1 > file3mv file3 file1cat file1
Result: File name is q1.sh
-
8/3/2019 Linux Lab Manual,PESCE
5/22
4. Write a Shell script display the contents of directories/bin and /user/ bin.
for name in /bin /usr/bindols $namedone
Result: It displays the contents of directories /bin and /usr/bin
5. a) Write a Shell script prints whether each file in a directory is readable or writable.
for word in `ls`doif test -r $wordthen echo "$word is readable"fi
if test -w $wordthen echo "$word is writable"fidone
Result: File name is readw.sh
-
8/3/2019 Linux Lab Manual,PESCE
6/22
5. b) Write a Shell script for file test whether the file is readable/ writable/executable.
if [ ! -e $1 ];thenecho "File does not exist"elif [ ! -r $1 ];thenecho "File is not readable"elif [ ! -w $1 ];then
echo "File is not writeable"elif [ ! -x $1 ];thenecho "File is not executable"elseecho "File is redable writeable and executablefi
Result: File name is erw.sh
6. Write C program that creates a child process to read commands from the standard input and
execute them ( a minimal implementation of a shell- like program ). you can assume that no
arguments will be passed to the commands to be executed.
#include#include
int main(){
char cmd[20];pid_t pid;int p,p1;int ch;pid=fork();p=getpid();p1=getppid();if(pid==0){
do{
printf("\n enter the cmd to be executed: \n");scanf("%s",cmd);system(cmd);printf("\n enter 1 to continue and 0 to exit: ");scanf("%d",&ch);
}while(ch!=0);}printf("processid=%d\n",p);printf("parentid=%d\n",p1);
-
8/3/2019 Linux Lab Manual,PESCE
7/22
wait();}
Result: File name is chexe.c
7. a) Shell scripts that accepts two file names as arguments, checks if the permissions for these files
are identical, outputs the common permissions, otherwise outputs each file name followed by its
permissions.
ls -l $1 | cut -d " " -f 1 > xls -l $2 | cut -d " " -f 1 > yif cmp x ythenecho "both are equal"cat xelseecho "differ"echo "first file $1"cat xecho "second file $2"cat yfi
Result: File name is perm.sh
-
8/3/2019 Linux Lab Manual,PESCE
8/22
7. b) Shell function that takes a valid directory names as an argument and recursively descends all the
sub directories, finds the maximum length of any file in that hierarchy and writes this maximum
value to the standard output.
echo "the max size of the file in directory $1 is: "ls -lR|grep '^-'|cut -c 25-26|sort -n|tail -1
Result: File name is maxsz.sh
8. Write a shell script to print the following shapes and other shapes.
-
8/3/2019 Linux Lab Manual,PESCE
9/22
FOR2:
echo "Can you see the following:"
for (( i=1; i
-
8/3/2019 Linux Lab Manual,PESCE
10/22
FOR4:
echo "Stars"
for (( i=1; i
-
8/3/2019 Linux Lab Manual,PESCE
11/22
FOR6:
echo "Stars"
for (( i=1; i
-
8/3/2019 Linux Lab Manual,PESCE
12/22
if [ $i -eq 3 ]; thenecho -n "______"echo -n -e ">> Powerd Server.\n"
elseecho "~~~~~"
fidone
Result: File name is for7.sh
FOR8:
MAX_NO=0
echo -n "Enter Number between (5 to 9) : "read MAX_NO
if ! [ $MAX_NO -ge 5 -a $MAX_NO -le 9 ] ; thenecho "I ask to enter number between 5 and 9, Okay"exit 1
fi
clear
for (( i=1; i=i; s-- ))do
echo -n " "donefor (( j=1; j
-
8/3/2019 Linux Lab Manual,PESCE
13/22
echo -n " ."doneecho ""
done
Result: File name is for8.sh
FOR 8{ STARS }
MAX_NO=0
echo -n "Enter Number between (5 to 9) : "
read MAX_NO
if ! [ $MAX_NO -ge 5 -a $MAX_NO -le 9 ] ; thenecho "I ask to enter number between 5 and 9, Okay"exit 1
fi
clear
for (( i=1; i=i; s-- ))do
echo -n " "
donefor (( j=1; j
-
8/3/2019 Linux Lab Manual,PESCE
14/22
donefor (( j=1; j
-
8/3/2019 Linux Lab Manual,PESCE
15/22
####for (( i=MAX_NO; i>=1; i-- ))do
for (( s=i; s
-
8/3/2019 Linux Lab Manual,PESCE
16/22
9. Shell script that accepts path names and creates all the components in that path names as
directives. For example, if the script name is mpe then the command mpe a/b/c/d should create
directories a, a/b, a/b/c and a/b/c/d.
if [ $# -lt 1 ]
thenecho " NO ARGUMENTS"
elseecho $1 | tr "/" " " > temp
for i in $tempdo
mkdir $icd $i
doneecho "ALL DIRECTORY ARE CREATED"
fi
Result: File name is createpath.sh
10. Shell scripts that accepts valid log-in names as arguments and prints their corresponding home
directories. If no arguments are specified, print suitable error message.
if [ $# -lt 1 ]then
echo "no arguments"else
for i in $*do
x=`cat /etc/passwd | cut -d ":" -f6 | grep -w "$i"`if [ -z $x ]then
echo "there is no user of the name "$ielse
echo "home directory of $i is "$xfidone
fi
Result: File name is log.sh
-
8/3/2019 Linux Lab Manual,PESCE
17/22
11. Shell script to display the calendar for current month with current data replaced by * or ** depending onwhether has one digits.
n=`date +%d`cal >tempif [ $n -lt 10 ]thensed s/"$n"/*/g tempelsesed s/"$n"/**/g tempfi
Result: File name is datedisp.sh
12. Shell script that accepts file names specified as arguments and create a shell script that contains this file as wellas code to recreate these files. Thus if the script generated by your script is executed, it would recreate the originalfiles(This is same as the bundle script described by Brain W. Kerighan and Rob Pike in The Unix Programming
Environment, Prentice Hall India).
echo '#to bundle,sh this file'for i in $*doecho "echo $i 1>&2"echo "cat>$icat $i
-
8/3/2019 Linux Lab Manual,PESCE
18/22
STUDY PROGRAMS
Q.1.Write Script to find out biggest number from given three nos. Nos are supplies as command line argument. Print error ifsufficient arguments are not supplied.
Q2. Script to find out biggest number## Algo:# 1) START: Take three nos as n1,n2,n3.# 2) Is n1 is greater than n2 and n3, if yes# print n1 is biggest no goto step 5, otherwise goto next step# 3) Is n2 is greater than n1 and n3, if yes
# print n2 is biggest no goto step 5, otherwise goto next step# 4) Is n3 is greater than n1 and n2, if yes# print n3 is biggest no goto step 5, otherwise goto next step# 5) END##
if [ $# -ne 3 ]then
echo "$0: number1 number2 number3 are not given" >&2exit 1
fin1=$1
n2=$2n3=$3if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ]then
echo "$n1 is Bigest number"elif [ $n2 -gt $n1 ] && [ $n2 -gt $n3 ]then
echo "$n2 is Bigest number"elif [ $n3 -gt $n1 ] && [ $n3 -gt $n2 ]then
echo "$n3 is Bigest number"elif [ $1 -eq $2 ] && [ $1 -eq $3 ] && [ $2 -eq $3 ]then
echo "All the three numbers are equal"else
echo "I can not figure out which number is biger"fi
Q.2. How to write shell script that will add two nos, which are supplied as command line argument, andif this two nos are not given show error and its usage
Q1.Script to sum to nos
if [ $# -ne 2 ]then
-
8/3/2019 Linux Lab Manual,PESCE
19/22
echo "Usage - $0 x y"echo " Where x and y are two nos for which I will print sum"exit 1
fiecho "Sum of $1 and $2 is `expr $1 + $2`"
Q.3.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.
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=$1sum=0sd=0while [ $n -gt 0 ]do
sd=`expr $n % 10`sum=`expr $sum + $sd`
n=`expr $n / 10`doneecho "Sum of digit for numner is $sum"
Q.4.Write Script to see current date, time, username, and current directory
echo "Hello, $LOGNAME"echo "Current date is `date`"echo "User is `who i am`"echo "Current direcotry pwd`"
Q.5. Write shell script to implement menus using dialog utility. Menu-items and action according toselect 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
-
8/3/2019 Linux Lab Manual,PESCE
20/22
name of directory given assumes current directory, then showall files only of that directory, Files must be shown on screenusing menus of dialog utility, let the user select the file, thenask the confirmation to user whether he/she wants to deleteselected file, if answer is yes then delete the file , report errorif 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 functionshow_datetime().show_datetime()
{dialog --backtitle "Linux Shell Tutorial" --title "System date and Time" --infobox "Date is `date`" 3 40readreturn
}show_cal(){
cal > menuchoice.temp.$$dialog --backtitle "Linux Shell Tutorial" --title "Calender" --infobox "`cat menuchoice.temp.$$`" 9 25readrm -f menuchoice.temp.$$return
}delete_file(){dialog --backtitle "Linux Shell Tutorial" --title "Delete file"\--inputbox "Enter directory path (Enter for Current Directory)"\10 40 2>/tmp/dirip.$$rtval=$?
case $rtval in
1) rm -f /tmp/dirip.$$ ; return ;;255) rm -f /tmp/dirip.$$ ; return ;;
esac
mfile=`cat /tmp/dirip.$$`
if [ -z $mfile ]then
mfile=`pwd`/*else
grep "*" /tmp/dirip.$$if [ $? -eq 1 ]then
mfile=$mfile/*fi
fi
for i in $mfiledo
if [ -f $i ]then
echo "$i Delete?" >> /tmp/finallist.$$fi
donedialog --backtitle "Linux Shell Tutorial" --title "Select File to Delete"\--menu "Use [Up][Down] to move, [Enter] to select file"\
-
8/3/2019 Linux Lab Manual,PESCE
21/22
20 60 12 cat /tmp/finallist.$$` 2>/tmp/file2delete.tmp.$$
rtval=$?
file2erase=`cat /tmp/file2delete.tmp.$$`
case $rtval in0) dialog --backtitle "Linux Shell Tutorial" --title "Are you shur"\
--yesno "\n\nDo you want to delete : $file2erase " 10 60if [ $? -eq 0 ] ; then
rm -f $file2eraseif [ $? -eq 0 ] ; then
dialog --backtitle "Linux Shell Tutorial"\--title "Information: Delete Command" --infobox "File: $file2erase is Sucessfully deleted,Press a key" 5 60readelsedialog --backtitle "Linux Shell Tutorial"\--title "Error: Delete Command" --infobox "Error deleting File: $file2erase, Press a key" 5 60
readfi
else
dialog --backtitle "Linux Shell Tutorial"\--title "Information: Delete Command" --infobox "File: $file2erase is not deleted, Action is canceled, Press a
key" 5 60read
fi;;
1) rm -f /tmp/dirip.$$ ; rm -f /tmp/finallist.$$ ;rm -f /tmp/file2delete.tmp.$$; return;;
255) rm -f /tmp/dirip.$$ ; rm -f /tmp/finallist.$$ ;rm -f / tmp/file2delete.tmp.$$; return;;
esacrm -f /tmp/dirip.$$rm -f /tmp/finallist.$$
rm -f /tmp/file2delete.tmp.$$return}
while truedodialog --clear --title "Main Menu" \
--menu "To move [UP/DOWN] arrow keys \n\[Enter] to Select\n\
Choose the Service you like:" 20 51 4 \"Date/time" "To see System Date & Time" \"Calender" "To see Calaender"\
"Delete" "To remove file"\"Exit" "To exit this Program" 2> menuchoice.temp.$$
retopt=$?
choice=`cat menuchoice.temp.$$`
rm -f menuchoice.temp.$$
case $retopt in0)
case $choice inDate/time) show_datetime ;;Calender) show_cal ;;Delete) delete_file ;;
-
8/3/2019 Linux Lab Manual,PESCE
22/22
Exit) exit 0;;esac
;;1) exit ;;255) exit ;;
esacdoneclear