DTG
DTG
SYLLABUS:
Shell programming. Ordinary and environment variables. The .profile. Read and read only commands.
Command line arguments. exit and exit status of a command. Logical operators for conditional
execution. The test command and its shortcut. The if, while, for and case control statements. The set and
shift commands and handling positional parameters. The here ( << ) document and trap command.
Simple shell program examples. File inodes and the inode structure. File links – hard and soft links.
Filters. Head and tail commands. Cut and paste commands. The sort command and its usage with
different options. The umask and default file permissions. Two special files /dev/null and /dev/tty.
[Topics from chapter 11, 12, 14 of text book 1,chapter 17 from text book2]
Text Books: 1.Sumitabha Das., Unix Concepts and Applications., 4th Edition., Tata McGraw Hill
2.Behrouz A. Forouzan, Richard F. Gilberg : UNIX and Shell Programming- Cengage Learning
– India Edition. 2009.
Note: Refer chapters 8 and 4 from M. G Venkateshmurthy
Prepared by,
TANUSHREE K N, Assistant professor, Department of CSE
The UNIX shell is both an interpreter as well as a scripting language. An interactive shell turns non
interactive when it executes a script.
Bourne Shell – This shell was developed by Steve Bourne. It is the original UNIX shell. It has strong
programming features, but it is a weak interpreter.
C Shell – This shell was developed by Bill Joy. It has improved interpretive features, but it wasn‟t
suitable for programming.
Korn Shell – This shell was developed by David Korn. It combines best features of the bourne and C
shells. Ithas features like aliases, command history. But it lacks some features of the C shell.
Bash Shell – This was developed by GNU. It can be considered as a superset that combined the features
of Korn and C Shells. More importantly, it conforms to POSIX shell specification
In the above example : #!/bin/sh is known as interpreter line. It denotes the pathname of the
shell to be used for running the script. Here it specifies Bourne shell and # denotes commented line
Execution steps:
To run the script make it executable first and then invoke the script name(2 diff way)
1. $chmod +x script.sh
$./ script.sh
2. $ sh script.sh
NOTE:
3. Shell variables.
A shell can be cons idered as a programming language as with any other language,
variables are defined and used with a shell.
There are three t ypes of variables ,they are
1. Local variables or user defined variable
2. System variables or environment variable
3. read-onl y variables
2) $x=37 output: 37
$echo $x
Note :A variable can be removed with unset and protected from reassignment by readonly. Both are
shell internal commands.
5. Environment variables.
System variables are set either during the boot sequence or immediatel y after logging
in.
The working environment under which a user works depends entirel y upon the values
of these variables, these variables are known as environment variables
These variables are similar to global variables .if required, values of these variable
scan be changed to have an environmen t to suit the user
By convention these variables are written using UPPERCASE letter onl y.
A list of all variables currentl y defined for user session can be viewed entering the
env command.(refer 195 page no from sumitabha das for env content)
o More directory can be added to the PATH using an assignment statement, new directory will also be
o The Bash and korn prompt can do much more than displaying such simple information as user name,
the name of machine and some indication about the present working directory. Some examples are
demonstrated next.
$ PS1=„[PWD] „
[/home/srm] cd progs
[/home/srm/progs] _
o Bash and Korn also support a history facility that treats a previous command as an event and
associates it with a number. This event number is represented as !.
$ PS1=”[!] “ $ PS1=”[! $PWD] “
[42] _ [42 /home/srm/progs] _
2. If number of values are more than the number of arguments, the first n -1 values
are assigned to the first n -1arguments and all the remaining input values are
Example:
#!/bin/bash
# Call this script with at least 3 parameters, for example
# sh scriptname 1 2 3
echo "first parameter is $1"
echo "Second parameter is $2"
echo "Third parameter is $3"
exit 0
The shell provides two operators that aloe conditional execution, the && and || Usage:
Syntax:
cmd1 && cmd2
cmd1 || cmd2
&& delimits two commands. cmd 2 executed only when cmd1 succeeds.
The || operator plays an inverse role:the second command is executed only only when the first fails.
Example1:
$ grep ‘director’ emp.lst && echo “Pattern found”
Output:
9876 Jai Sharma Director Productions
2356 Rohit Director Sales
Pattern found
Example 2:
$ grep ‘clerk’ emp.lst || echo “Pattern not found”
Output:
Pattern not found
Example 3:
grep “$1” $2 || exit 2
echo “Pattern Found Job Over”
Operator Meaning
-eq Equal to
-ne Not equal to
-gt Greater than
-ge Greater than or equal to
-lt Less than
2. String comparison
Test True if
S1=S2 String s1 equal to s2
S1!=S2 String s1 is not equal to s2
Example:
#!/bin/sh o/p:?
if [ ! -e $1] ; then
echo “file does not exist”
elif [ ! -r $1] ; then
echo “file is not readable” else
echo “file is not readable and does not exist”
fi
#!/bin/sh
echo "MENU
1. list of files 2. processes3. todays date 4. users of system 5. Quit enter your option"
read choice
case "$choice" in
1) ls –l ;;
2) ps –f ;;
3) date ;;
4) who ;;
5) exit ;;
*) echo "invalid option"
esac
shift transfers the contents of a positional parameter to its immediate lower numbered one. This is done
as many times the statement is called.
Example:
$ set 9876 2345 6213
$ echo "$@"
output:9876 2345 6213
$ echo $1 $2 $3
output: 9876 2345 6213
$ shift
$ echo $1 $2 $3
output: 345 6213 (shifted by one) //$1 value is 2345 and $2 value is 6213
The here document symbol (<<) is followed by two data lines and a delimiter (END). Shell treats every
line following the command and delimited by END as input to the command. The content of here
document is interpreted and processed by shell.
trap command
Trap helps user to interrupt a program. The statement is usually placed at the beginning of a shell script
and uses two lists
Syntax: trap ‘command list’ signal list
When script is sent any of the signals in signal_list, trap executes the commands in command_list.
17. File inodes and the inode structure or File Systems and inodes
A file is an object on a computer that stores data, information, settings, or commands that are used
with a computer program.
The hard disk is split into distinct partitions, with a separate file system in each partition. Every file
system has a directory structure headed by root.
n partitions = n file systems = n separate root directorie
All attributes of a file except its name and contents are available in a table and this table is called
inode (index node), accessed by the inode number.(unique identification number)
The inode structure contains the following attributes of a file:
File type
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
An array of pointers that keep track of all disk blocks used by the file
Please note that, neither the name of the file nor the inode number is stored in the inode.
To know inode number of a file:
$ls -i tulec05
o/p: 9059 tulec05
$ls -il tulec05 //- l for attributes and – I for inode number
o/p: 9059 -rw-r--r-- 1 kumar metal 51813 Jan 31 11:15 tulec05
HARD LINKS
Hard link acts like a mirror copy of the original file. These links share the same inodes. Changes made
to the original or hard linked file will reflect in the other. When you delete Hard Link nothing will
happen to the other file. Hard links can't cross file systems.
The link count is displayed in the second column of the listing. This count is normally 1, but the
following files have two links,
-rwxr-xr-- 2 kumar metal 163 Jull 13 21:36 backup.sh
-rwxr-xr-- 2 kumar metal 163 Jul 13 21:36 restore.sh
All attributes seem to be identical, but the files could still be copies. It’s the link count that seems to
suggest that the files are linked to each other. But this can only be confirmed by using the –i option to ls.
$ls -li backup.sh restore.sh
478274 -rwxr-xr-- 2 kumar metal163 jul 13 21:36 backup.sh
478274 -rwxr-xr-- 2 kumar metal163 jul 13 21:36 restore.sh
A file is linked with the ln command which takes two filenames as arguments (cp command). The
command can create both a hard link and a soft link and has syntax similar to the one used by cp.
The following command links emp.lst with employee:
Note: You can link multiple files, but then the destination filename must be a directory.
A file is considered to be completely removed from the file system when its link count drops to
zero. ln returns an error when the destination file exists. Use the –f option to force the removal of the
existing link before creation of the new one
NOTE: Points to remember
2. ls -l command shows all the links with the link column showing the number of links.
3. Links have actual file contents
4. Removing any link, just reduces the link count but doesn't affect the other links.
5. You cannot create a Hard Link for a directory.
6. Even if the original file is removed, the link will still show you the contents of the file.
2. ls -l command shows all links with second column value 1 and the link points to original file.
3. Soft Link contains the path for original file and not the contents.
4. Removing soft link doesn't affect anything but when the original file is removed, the link becomes
a 'dangling' link that points to nonexistent file.
5. A Soft Link can link to a directory
Filters are the commands which accept data from standard input manipulate it and write the results to
standard output.
Filters are the central tools of the UNIX tool kit, and each filter performs a simple function. Some
commands use delimiter, pipe (|) or colon (:).
Several UNIX commands are provided for text editing and shell programming. (emp.lst) - each line of
this file has six fields separated by five delimiters (separator).
The details of an employee are stored in one single line. This text file designed in fixed format and
containing a personnel database. There are 15 lines, where each field is separated by the delimiter |.
We can also address lines from the beginning of the file instead of the end. The +count option allows to
do that, where count represents the line number from where the selection should begin.
$tail +11 emp.lst // Will display 11th line onwards
Different options for tail are:
1. Monitoring the file growth (-f)
2. Extracting bytes rather than lines (-c)
Use tail –f when we are running a program that continuously writes to a file, and we want
to see how the file is growing. We have to terminate this command with the interrupt key.
When we cut with cut, it can be pasted back with the paste command, vertically ratherb than
horizontally.
We can view two files side by side by pasting them. In the previous topic, cut was used to create the
two files cutlist1 and cutlist2 containing two cut-out portions of the same file.
Example:
$paste cutlist1 cutlist2
$paste -d “|” cutlist1 cutlist2 // We can specify one or more delimiters with -d
Where each field will be separated by the delimiter |. Even though paste uses at least two files for
concatenating lines, the data for one file can be supplied through the standard input.
Note: please refer ppt for examples
22. The sort command and its usage with different options.
sort: ordering a file
Sorting is the ordering of data in ascending or descending sequence. The sort command orders a file and
by default, the entire line is sorted
Example: $ cat file.txt
abhishek
chitransh
satish
rajan
naveen
divyam
harsh
$sort file.txt
abhishek
chitransh
divyam
harsh
naveen
rajan
$ expr $x-$y
O/P;-2
$ expr $y/$x
O/P:1
$ expr 13%5
o/p:3
String Handling:
expr is also used to handle strings. For manipulating strings, expr uses two expressions separated by a
colon (:).
The string to be worked upon is closed on the left of the colon band a regular expression is placed on its
right. Depending on the composition of the expression expr can perform the following three functions:
1. Determine the length of the string.
2. Extract the substring.
3. Locate the position of a character in a string.
Example2:
while echo “Enter your name: \c” ;do
read name
if [`expe “$name” :’.*’` -gt 20] ; then
echo “Name is very long”
else
break
fi
done
imp Note:
2. Extract the substring.
3. Locate the position of a character in a string.
/dev/tty:
• This file indicates one’s terminal. In a shell script, some times user require to redirect the output of
some select statements explicitly to the terminal. In such cases redirect these explicitly to /dev/tty
inside the script.
• If you would like to execute a command but don’t like to see its contents on the screen, you may wish to
redirect the output of some select statements explicitly to the terminal. In such cases you can redirect
these explicitly to /dev/tty inside the script.