Unix m4
Unix m4
m
VAR_1
VAR_2
TOKEN _A
print it on STDOUT –
#!/bin/sh
vt
NAME=“Sumitabha Das“
echo $NAME
PATH : Indicates search path for commands.It is a colon separated list of directories in which the shell
looks for commands.
PWD: Indicates the current working directory as set by the cd command.
RANDOM: Generates a random integer between 0 and 32767 each time it is referenced.
SHLVL: Increments by one each time an instance of bash is created.
UID: Expands to the numeric user ID of the current user initialized at shell prompt.
$ echo $TERM
xterm
m
$ echo $PATH
/usr/local/bin:/bin:/usr/bin:/home/amrood/bin:/usr/local/bin
co
$
m
Structure of shell script:
#!/bin/sh
# script.sh: Sample shell script
echo “ Todays date: `date`”
echo “This month calendar”
cal `date` “+%m 20%y” co
p.
echo “My Shell: $SHELL”
output:
oo
$sh script.sh
Todays date : Mon Nov 7 10:03:42 IST 2016
This month's calendar:
November 2016
ul
vt
My shell: /bin/sh
m
the variable name. since this is a form of assignment , no $ is used before the name.
A single read statement can be used with one or more variables to let you enter multiple
arguments.
read pname flname
co
The script asks for a pattern to be entered. Input the string director, which is assigned to the
variable pname. Next the script asks for the filename enter the string emp.lst which is assigned
to the variable flname.
p.
grep runs with these two variables as arguments
#!/bin/sh
#emp1.sh
oo
#
echo "Enter the pattern to be searched : \c"
read pname
echo " Enter the file to be used : \c"
ul
read flname
echo " Searching for $pname from file $flname"
grep "$pname" $flname
vt
Output:
$ sh emp2.sh director emp.lst
Program: emp2.sh
The number of arguments specified is:2
m
The arguments are director emp.lst
101| sharma|director|production|12/03/70|7000
102|barun|director|marketing|11/06/67|7800
job over
Its through the exit command or function that every command returns an exit status to the caller.
Further a command is said to return true exit status if it executes successfully and false if its fails.
THE PARAMETER $? :It stores the exit status of the last command. It has the value 0 if the
command succeeds and a non zero value if it fails. This parameter is set by exit’s argument If
no exit status is specified then $? is set to zero(true).
Consider two files file1 which exist in current directory and file2 which does not exist
$ ls –l file1; echo $? /*file1 attributes are listed
Output :0 /*exit status $?=0, since cmd executed successfully
m
1082|sumith| manager|marketing|09/09/73| 7090
• The && delimits two commands ; the command cmd2 is executed only when cmd1 succeeds.
$ grep “director” emp.lst && echo “Pattern found in file”
Output:
1066| sharma | director |sales |03/09/66 | 7000
1098| Kumar |director| production|0/08/67 | 8200
Pattern found in file
co
p.
• The || operator plays inverse role. The second command is executed only when the first fails.
$grep “ deputy manager” emp.lst || echo “Pattern not found”
oo
Output:
Pattern not found /* cmd1 -deputy manager is not found in emp.lst.
Hence cmd1 fails. Therefore cmd2 “pattern not found”
executes.
ul
The if statement makes two way decision making depending on the fulfillment of a certain condition.
#!/bin/sh
a=10
b=20
if [ $a==$b ]
then
echo “a is equal to b”
elif [ $a –gt $b ]
then
m
echo “ a is greater than b”
elif [ $a -lt $b ]
then
echo “ a is lesser than b”
else
echo “ None of the conditions met”
fi co
p.
output:
a is lesser than b
oo
pattern2 ) commands2 ;;
pattern3 ) commands3 ;;
……..
esac
case first matches expression with pattern1. If the match succeeds, then it executes commands1, which
may be one or more commands. If the match fails, then pattern2 is matched and so on….Each
command list is terminated with a pair of semicolons and the entire construct is closed with esac .
#!/bin/sh
#menu.sh
# echo “ MENU \n
1.List of files\n 2.Processes of user\n 3.Todays date\n
4.Users of system\n 5.Quit\n
Enter your option: \”
read choice
case “$choice” in
1 ) ls –l ;;
2 ) ps –f ;;
3 ) date ;;
4 ) who ;;
5 ) exit ;;
* ) echo “invalid option”
esac
m
3. Todays date
4.Users of system
5. Quit
Enter your option : 3
Sun Nov 6 18:03:06 IST 2016
4.12.2.1 Matching multiple patterns:
co
case can also specify same action for more than one pattern.
p.
For example the expression y|Y can be used to match y in both upper and lower case letters.
esac
4.12.2.2 Wild cards: case uses them
case has a string matching feature that uses wild cards.
vt
It uses the filename matching meta characters *, ? and the character class but only to match
strings but not the files in the current directory.
case “$answer” in
[yY][eE] * ) ;;
[nN][oO] ) exit ;;
* ) echo “Invalid response”
esac
4.13 USING test and [] to evaluate the expressions.
Test uses the certain operators to evaluate the condition on its right and returns either true or false exit
status which is then used by if for making decision .
Numeric comparison in the shell is confined to integer values only , decimal values are simply
truncated.
$ x=5; y=7; z=7.2
$ test $x –eq $y ; echo $?
Output : 1
m
$ test $x –lt $y ; echo $?
Output: 0
Test True if
oo
Example:
#!/bin/sh
a=”abc”
b=”efg”
if [ $a = $b ]
then
echo “a is equal to b”
else
echo “a is not equal to b”
fi
output:
a is not equal to b
Sandeepa G S, Asst Prof, Page 78
Dept of CSE, GMIT
UNIX AND SHELL PROGRAMMING
4.13.3.FILE TESTS
test can be used to test the various file attributes like its type(file, directory or symbolic link) or its
permissions(read,write,execute)
m
$ls –l emp.lst
-rw-rw-rw- 1 kumar group 870 Sep 8 15:52 emp.lst
$ [ -f emp.lst ] ; echo $?
0
$ [ -x emp.lst ] ; echo $?
co
// -f ( emp.lst file exist and its regular file)
// Yes
// -x (emp.lst file is executable or not)
p.
1 //No
4.14 while Looping
The while statement repeatedly performs a set of instructions until the control command return
oo
commands
done
The commands enclosed by do and done are executed repeatedly as long as condition remains
vt
true.
m
commands
done
The loop body also uses the keyword do and done. But the additional parameters here are variable and
is executed .
Ex: co
list. Each whitespace separated word in list is assigned to variable and commands are executed until list
p.
$for file in chap20 chap21 chap22
do
cp $file {$file}.bak
oo
echo $file copied to $file.bak
done
Output:
chap20 copied to chap20.bak
ul
m
note. //txt stripped off
and 779 to $3
Ex:
$echo “\$1 is $1, \$2 is $2, \$3 is $3”
Output: $1 is 989, $2 is 878, $3 is 779
$echo “The $# arguments are $*”
Output: The 3 arguments are 989 878 779
$shift
$ echo $1 $2 $3 $4 $5
Output: Nov 9 09:04:30 IST 2016
$shift 2
$echo $1 $2 $3
Output: 09:04:30 IST 2016
m
MARK
The here document symbol(<<) followed by three lines of data and a delimiter (the string
MARK)
command.
co
The shell treats every line following the command and delimited by MARK as input to the
Sharma at the other end will see the three lines of message text with the date inserted by
command substitution and the evaluated filename.
p.
4.18 trap: INTERRUPTING A PROGRAM
oo
By default shell scripts terminate whenever the interrupt key is pressed. It may leave a lot of
temporary files on disk .
The trap statement lets you do things you want in case the script receives a signal. The
statement is normally placed at the beginning of a shell script and uses two lists
ul
The signal_list can contain the integer values or names of one or more signals.
trap ‘rm $$* ; eho “Program Interrupted” ; exit ’ HUP INT TERM
trap ‘cmd_list’ sig_list
trap is a signal handler.
Here it first removes all the files expanded from $$*, echoes a message and finally terminates
the script when the signals SIGHUP(1), SIGINT(2), SIGTERM(15) are sent to the shell process
running the script.
When the interrupt key is pressed it sends the signal number 2.
Of these multiple file systems, one of them is considered to be the main one and contains the
most of the essential files of the Unix system. This is the root file system.
Every file is associated with a table that contains all that you could possibly need to know about
a file except its name and contents. This table is called the inode and is accessed by inode
number.
The inode contains the following attributes of a file
File type(regular,directory,device etc)
File permissions
Number of links
The UID of the owner
The GID of the group owner
File size in bytes
Date and time of last modification
Date and time of last access
Date and time of last change of the inode
m
An array of pointers that keep track of all disk blocks used by the file
co
4.20.1 HARD LINKS: is merely an additional name for an existing file.
Creating hard links:ln command
A file is linked with the ln command which takes two filenames as arguments.
The following command links file1 to file2
p.
$ln file1 file2
-i option:The –i option to ls shows the inode number of the files
$ls –li file1 file2
oo
Output:
Inode number permissions links owner group size last modified time filename
29518 -rwxr-xr-x 2 Kumar metal 915 May 4 09:58 file1
29518 -rwxr-xr-x 2 Kumar metal 915 May 4 09:58 file2
ul
Original and link file will have same inode number: all files with inode number 29518
File size is same for original and linked files:915
vt
LIMITATIONS
Hard links cannot be used to have two linked filenames in two filesystem.
Hard links cannot be used to link a directory even within the same file system.
m
- Syntax to create symbolic link
-s option along with ln command is used to create soft link
Consider two files note and note.sym. Creating soft link is as follows:
9948
9952
$ln –s note note.sym
$ls –li note note.sym
-rw-r—r-- 1 kumar group 80
lrwxrwxrwx 1 kumar group 4 Feb co
Feb 16
15
14:52 note
15:07 note.symnote
p.
The inode number of linked file is 9952 whereas that of original file is 9948
The file size of the linked file is 4 whereas the original file is 80
oo
Original and link file will have same inode Inode number of the link file will be different
number
vt
If original file is deleted, still link file exist If original file is deleted , link file will not be
accessible
Size of hardlink file is same as original file Size of soft link file is smaller than original
file.
It cannot be created across the partitions It can be created across the partitions
a. pr :PAGINATING FILES
The pr command prepares file for printing by adding suitable header, footers and formatted text.
$pr filename
$pr dept.lst
Sandeepa G S, Asst Prof, Page 84
Dept of CSE, GMIT
UNIX AND SHELL PROGRAMMING
Output:
pr options
-k option
pr's -k option prints in k columns
-d option
Doublespaces input
m
-n option
Number lines
-o n
offset lines by n spaces.
When used without an option it displays the first ten lines of the file
$head emp.lst
option
-n option
$head -n 3 emp.lst
Output: /*displays first three lines of file
2233|a.k shukla |general manager|sales |12/12/52|6000
9876|jai sharma |director |production|03/06/50|7000
5678|sumit chakrobarty|deputy manager |marketing|04/09/43|8000
Output
a.k shukla general manager
m
jai sharma director
sumit chakrobarty deputy manager
barun sengupta director
n.k.gupta
v.k.agarwal
2.cutting fields(-f)
chairman
general manager
co
p.
cut uses the tab as the default field delimiter.
Two options need to be used here
-d for the field delimiter
oo
5678|marketing|04/09/43|8000
2365|personnel|05/11/47|7600
5423|admin |08/07/56|5400
0110|accounts |12/03/45|9900
e. paste:Pasting files
paste command can be used as follows
m
paste can also be used with delimiter option -d
$paste -d "|" cutlist1 cutlist2
a.k shukla | general manager | 2233|sales |12/12/52|6000
jai sharma |director
24568799
vinod sharma
[email protected]
vt
87764543
barun gupta
[email protected]
45943890
m
-n Sorts numerically
-r Reverses sort order
-m list Merges sorted files in list
-c
-o filename
co
Checks if file sorted
Places output in file filename
p.
Consider a sample file named shortlist with employee details
$cat shortlist
2233|a.k shukla| general manager|sales|12/12/52|6000
9876|jai sharma |director|production|03/06/50|7000
oo
5423|n.k.gupta|chairman|admin|08/07/56|5400
9876|jai sharma |director|production|03/06/50|7000
2365|barun sengupta|director|personnel|05/11/47|7600
2233|a.k shukla| general manager|sales|12/12/52|6000
3. Sorting on secondary key(-k m,n)
Sorting can be done on more than one key i,e you can provide a secondary key to sort.
For ex: If the primary key is third field,and the secondary key is second field, then you need to
specify for every -k option
$sort -t "|" -k 3,3 -k 2,2 shortlist
Output:
5423|n.k.gupta|chairman|admin|08/07/56|5400
5678|sumit chakrobarty|deputy manager|marketing|04/09/43|8000
2365|barun sengupta|director|personnel|05/11/47|7600
9876|jai sharma |director|production|03/06/50|7000
2233|a.k shukla| general manager|sales|12/12/52|6000
m
4.Sorting on columns(-k m.n)
Sorting can also be done on a specific character position within field to be the beginning of the
sort.
For ex:
co
If you need to sort the file according to the date of birth, then you need to sort on the seventh
and eight h columns positions within fifth field. 19/04/43- this is the fifth field
p.
$sort -t "|" -k 5.7, 5.8 shortlist
Output:
5678|sumit chakrobarty|deputy manager|marketing|04/09/43|8000
oo
2365|barun sengupta|director|personnel|05/11/47|7600
9876|jai sharma |director|production|03/06/50|7000
2233|a.k shukla| general manager|sales|12/12/52|6000
5423|n.k.gupta|chairman|admin|08/07/56|5400
ul
5.Numeric sort(-n)
$sort numfile
vt
m
$ sort –o shortlist shortlist
g. Tr-translating characters
• The syntax is
co
• tr translate filter command manipulates individual characters in a line.
9876~jai sharma~director~production~03-05-50~7000
5678~sumit chakrobarty~deputy manager~marketing~14-9-43~8000
It replaces each occurence of |(vertical bar) by ~ (tilde sign)
and each occurence of /(forward slash ) by -(hyphen) sign
ul
tr options
1. Deleting characters: (-d)
To delete characters |/ from the file emp.lst.
$tr -d '|/' < emp.lst
output:
2233 a.k shukla general manager sales 210252 6000
9876 jai sharma director production 030550 7000
5678 sumit chakrobarty deputy manager marketing 14943 8000
m
a.k.shukla
general manager
sales
12/12/52
6000
co
p.
4.22. The umask command and default permissions
• When you create files and directories , the permissions assigned to them depend on the system
default settings.
oo
• The UNIX system has the following default file and directory permissions.
rw-rw-rw-(octal 666 ) for regular files
rwxrwxrwx(octal 777) for directories.
• To evaluate the current value of mask by using umask command
ul
$umask
022
• This is an octal number that has to be subtracted from the system default to obtain the actual
vt
default.
• This becomes 644(666-022) for files and 755(777-022) for directories.
• A user can also use this command to set a new default.
zero.This facility is useful in redirecting the error messages away from the terminal so that they
don’t appear on screen.
/dev/tty:stands for controlling the terminal for the current process.For the shell process you are in
/dev/tty is the terminal you are now using.
Consider for instance that kumar is working on terminal /dev/pts/1 and sharma on /dev/pts/2.
However both can refer to their own terminals with the same filename /dev/tty.
Thus if kumar issues the command
who > /dev/tty
The list of current users is sent to terminal he is currently using /dev/pts/1.
Similarly sharma an issue the same command to see the output on his terminal /dev/pts/2
Thus /dev /tty can be accessed independently by several users at same time without conflict.
m
co
p.
oo
ul
vt