UP MOD2@AzDOCUMENTS - in PDF
UP MOD2@AzDOCUMENTS - in PDF
Objectives
1. ls - l : Listing fileAttributes
2. The –d option : Listing DirectoryAttributes
3. Fileownership
4. Filepermissions
5. chmod : Changing FilePermissions
6. Directory Permissions
7. Changing File Ownership
You created files and directories , navigated the file system , and copied
moved and removed files without anyproblem.
You may have problems when handling a file or directory. Your file may
be modified or even deleted byothers.
A File also has a number of attributes(properties) that are stored in the
inode.
We will use ls –l command with additional options to display these
attributes.
We will mainly consider the two basic attributes permissions and and
ownership.
The UNIX file system allows the user to access other files not belonging to
them and without infringing onsecurity.
ls - l : LISTING FILE ATTRIBUTES
ls –l to list seven attributes of all files in the current directory.
It’s the –l(long) option that reveals most. This option displays most
attributes of a file-like its permissions ,size ,and ownershipdetails.
ls lists seven attributes of all files in the current directory and they are:
File type andPermissions
Links
Ownership
Group ownership
Filesize
Last Modification date andtime
Filename
Unix
$ ls –l
total 72
Thelistisprecededbythewordstotal72,whichindicatesthatatotalof72 blocks
are occupied by these files on disk.each block consisting of 512 bytes.
1) File type andpermissions:
The first column shows the type and permission associated with eachfile.
The first character in this column is mostly a – (Ordinary file), d
(Directory file), a,b or c(Devicefile).
In the UNIX system , a file can have three types of permissions r (read),
w(write),x(execute).
2) Links:
ThesecondcolumnindicatestheNumberofLinksassociatedwiththefile.
The number of file names maintained by thesystem.
A Link count greater than one indicates that the file has more than one
name. This does not mean that there are two copies of thefile.
3) Ownership:
When you create a file, you Automatically become its owner. The Third
column shows kumar as the owner of thesefiles.
The owner has the full Authority to tamper with a file’s contents and
permissions.
The owner can create, modify or remove files in adirectory.
4) GroupOwnership:
Whenopeningauseraccount,systemadministratoralsoassignstheuser to
somegroup.
Fourth column represents the group owner of the file.Every user is
attached to a groupowner.
5) Filesize:
The fifth column represents the sizes of the file in bytes .i.e amount of
data it contains.
Unix
Size is only the character count of the file, not a measure of disk space
that itoccupies.
The dept.lst contains 84 bytes , it would occupy 1024 bytes on diskon
system that use a block size of 1024bytes.
6) Last Modificationtime:
The 6th,7th,and 8thcolumn indicates last modification time of thefile.A
file said to be modified only if contents havechanged.
If you changed permissions,ownership then modification time remains
unchanged.
If the file is old more than one year , its last modification date,year
won’t be displayed.
Ex: In the file genie.sh has been modified more than a year ago.
7) Filename:
The last column displays the filename arranged in ASCII Collating
sequence.
THE –d OPTION : LISTING DIRECTORY ATTRIBUTES
ls to list the attributes of a directory, rather than its contents, you need to
use the –d(directory)option.
Example:
$ ls –ld helpdir progs
drwxr-xr-x 2kumarmetal 512may 9 10:31helpdir
drwxr-xr-x 2kumarmetal 512may 9 09:57progs
Directoriesareeasilyidentifiedinthelistingbythe1stcharacterofthe
1stcolumn , here shows asd.
Note:ls -d will not list all subdirectories in the current directory
FILE OWNERSHIP
Whenyoucreateafile,youbecomeitsowner,showsinthe3rdcolumn:
Group owner of the file (fourth column).
Several users may belong to a single group, people working on a project
aregenerallyareassignedacommongroup,andallfilescreatedbygroup
members (have separate user-id) will have same groupowner.
But the privileges of the group are set by the owner of the file and not by
the groupmembers.
Whenthesystemadministratorcreatesauseraccount,hehastoassign
$ ls-l cse
- r w - r - - r - -(default permission for createdfile)
The chmod (change mode) command is used to set the permissions of one
or more files for all three categories(user,group,other).
The command can be used in two ways:
In a relative manner by specifying the changes to the currentpermissions
Relative Permissions
Whenchangingapermissioninarelativemanner,chmodonlychanges the
permissions specified in the command line and leaves the other
permissions unchanged.
In this mode it uses the followingsyntax:
chmod category operation permission filename(s)
(u,g,o) (+,-,=) (r,w,x)
Chmod takes as its argument an expression comprising some letters and
symbols that describe category and type of permission being assigned or
removed. The expression contains threecomponents:
user category (user, group,others)
operation to be performed (assign or remove apermission)
Type of permission (read, write,execute)
Abbreviations used by chmod
permissions remain unchanged. Now can you execute the file if you are
owner of the file but other categories(group,others) stillnot.
To enable all of them to execute this file, you have to use multiple
characters to represents the usercategory(ugo).
The string ugo combines all three categories(user,group ,others).UNIX
also offers a shorthand symbol a(all) to act as a synonym for thestring.
Change permission to all group
$ chmodugo+xcbit or
$chmoda+x cbit or
$chmod+x cbit ; ls -lcbit
// You can use any of the above will give same output
Absolute Permissions
Here, we need not to know the current filepermissions.
Wecansetallninepermissionsexplicitly.Astringofthreeoctaldigitsis used as
anexpression.
Thepermissioncanberepresentedbyoneoctaldigitforeachcategory.For each
category, we add octaldigits.
If we represent the permissions of each category by one octal digit, this is
how the permission can berepresented:
Read permission – 4 (octal100)
Write permission – 2 (octal010)
Execute permission – 1 (octal001)
Permissions Significance
- -- nopermissions
- -x execute only
-w- writeonly
- wx write andexecute
r-- readonly
r-x read andexecute
rw- read andwrite
rwx read, write andexecute
Wehavethreecategoriesandthreepermissionsforeachcategory,sothree octal
digits can describe a file’s permissionscompletely.
The most significant digit represents user and the least one represents
Binary Octalcan use this three-digit string as theexpression.
others. chmod
000
Example: 0
001Using relative1 permission, we have,
$ chmod a+rw xstart
010 2
ls –l xstart
011 3
100 4
101 5
Unix
Note: The 6 indicates read and write permissin(4+2).To restore the original
permissions to the file, you need to remove the write permission (2) from group
and others.
To restore the original permission to the file
$ chmod 644 xstart
ls -l xstart
-r w - r - - r-- 1 kumar metal 1906 may 10 20:30 xstart
willassignallpermissionstotheowner,readandwritepermissionsforthe group
and only execute permission to theothers.
Ex:$ chmod 761 xstart
The expression 777 signifies all permission for all categories , while 000
indicates absence of all permissions for allcategories.
The Security Implications
Let the default permission for the file xstart is
-r w - r - - r-- 1 kumar metal 1906 may 1020:30 xstart
These permissions are fairly safe ;only the user can edit the file.What are
the implications if we remove all permissions in either of theseways.
$ chmod u-rw,go-r xstart
or
$ chmod 000 xstart
The listing in either case will look like this
- - - - - - - -- - 1 kumar metal 1906 may 1020:30 xstart
This setting renders the file virtually useless, you can’t do anything with
it ;But still user can delete thisfile.
Unix
On the other hand you must not careless ,enable all permissions for all
categories using neither of thesecommand.
$ chmod a+rwx xstart
or
$ chmod 777 xstart
The resulting permissions setting is simply dangerous:
-r w x r w x rwx 1 kumar metal 1906 may 1020:30 xstart
The UNIX system by default, never allows this situation as you cannever
have a secure system. Hence, directory permissions also play a very vital
rolehere.
Using chmod Recursively (-R)
It’s possible to make chmod descend a directory hierarchy and applythe
expression to every file and subdirectory it finds. This is done with-R
chmod -R a+x shell_scripts
This makes all the files and subdirectories found in the shell_scripts directory,
executable by all users.
DIRECTORY PERMISSIONS
It is possible that a file cannot be accessed even though it has read
permission, and can be removed even when it is writeprotected.
The default permissions of a directoryare,
r w x r - x r-x (755)
A directory must never be writable by group and others
Example:
$ mkdirc_progs
$ ls –ldc_progs
d r w x r - x r - x 2 kumarmetal512 May 9 09:57 c_progs
If a directory has write permission for group and others also, be assured
that every user can remove every file in thedirectory.
As a rule, you must not make directories universally writable unless you
have definite reasons to doso.
CHANGING FILE OWNERSHIP
Usually, on BSD (Berkeley’s Software Distribution) and AT&T systems,
there are two commands meant to change the ownership of a file or
directory.
If kumar creates a file he become the owner and metal be the group
owner. Only kumar can change the file major attributes like (permissions
and groupownership).
Unix
If sharma copies a file of kumar, then sharma will become its owner and
he can manipulate theattributes.
chown changing file owner and chgrp changing groupowner
On BSD, only system administrator can usechown
On other systems, only the owner can changeboth
chown: changing File Owner
This command can be used to change the ownership of afile
Syntax:
chown USERNAME FILENAME
Changing ownership requires superuser permission, so use sucommand
$ su
Password:******* //This is rootpassword
#- // This is anothershell
After the password successfully entered, su returns a # prompt ,same
prompt used by root su lets acquire
Ex: $ ls -lnote
-r w x r - - --x 1 kumar metal 347 may 10 20:30note
$ chown sharmanote //note is name of thefile
$ ls -l note
-r w x r - - -- x 1 sharma metal 347 may 10 20:30note
Once ownership of the file has been given away to sharma, the user file
permissions that previously applied to Kumar now apply tosharma.
Thus, Kumar can no longer edit note since there is no write privilege for
groupandothers.Hecannotgetbacktheownershipeither.Buthecancopy the
file to his own directory, in which case he becomes the owner of the
copy.
chgrp:changing group owner
Thiscommandchangesthefile’sgroupowner.Nosuperuserpermissionis
required.
chgrp shares the similar syntax with chown,in the following example
kumar changes the group of dept.lst to dba.
Ex:$ ls -l dept.lst
-r w- r - - r-- 1 kumar metal 139 jun816:43 dept.lst
$ chgrp dba dept.lst
$ ls –l dept.lst
-r w - r - - r -- 1 kumar dba 139 jun 8 16:43 dept.lst
This command will work on a BSD-based system if kumar is also a
member of the group.if he is not,then only the superser can make the
command work.
Kumarcanreversethisactionandrestorethepreviousgroupownership(to
metal) because he is still owner of the fileand consequently retains all
related toit.
UNIX allows the administrator to use only chown to change both owner
and group.
The syntax requires the two arguments to be separated by a:
Example:
chown sharma :dba deptlist // ownership to sharma,group to dba
Note:
Like chmod,both chown and chgrp use the –R option to perform their
operations in a recursive manner.
SHELL OFFERINGS:
Categories of shell:
The Bourne family comprising the Bourne shell (/bin/sh) and its
derivatives the korn shell (/bin/ksh) andBash(/bin/bash)
The C Shell (/bin/csh) and its derivatives ,Tcsh(/bin/tcsh).
Whenyourunecho$SHELLtheoutputdisplaystheabsolutepathnameof the
shell’s commandfile.
Unix
cp??????Progs //copiestoprogsdirectoryallfileswithsixcharacter
names.
Removing the special meaning of wild cards (ESCAPING AND
QUOTING):
The output below shows a file namedchap*
$ lschap*
chap chap* chap01 chap02 chapx chapv chapt
Tryingrmchap* would be dangerous; it removes the other filenames
beginning with chapalso.
We must able to protect all special character including (wildcards).
The shell provides two solutions to prevent its own interference:
Escaping: providing a \ (backslash) before the wild card to remove
(escape) the specialmeaning.
Quoting: Enclosing the wild card or even the entire pattern within quotes
(like ‘chap*’).
ESCAPING (\) :
Placinga \ immediately before a metacharacter turns off its special
meaning.
we can remove the file chap* without affecting the other filenames begin
with chap.
$ rmchap\* // Doesn’t remove chap1,chap2
The\supressesthewild-cardnatureofthe*,thuspreventingtheshellfrom
performing filename expansion on it. this feature is known asescaping.
Toconsideranotherexample,ifyouhavefileschap01,chap02andchap03 in
your current directory and still dare to create a file chap0[1-3] using echo
>chap0[1-3] //creates a filechap0[1-3]
then you should escape the two rectangular brackets when accessing the
file:
$ ls chap0\[1-3\] Must escape the[and]
chap[1-3]
$ rm chap0\[1-3\]
$ ls chap\[1-3\]
chap0[1-3]not found File removed
Escaping the Space: Apart from metacharactes, there are other character
like spacecharacter.
Ex: rmMy\Document.doc without the \ rm would see twofiles
Escapingthe\itself:Sometimesneedtointerpretethe\itselfliterally.you need
another \ beforeit.
Ex: $ echo \\
\
Unix
1) StandardInput:
• The standard input can represent three inputsources:
1) The keyboard, the defaultsource.
2) A file using redirection with the <symbol.
3) Another program using apipeline.
• By default, the shell directs standard input from thekeyboard.
Use wc without an argument and no symbols like <, | in command linewc
obtain input from default source.provide input from the keyboard and
mark end of input with[ctrl-d].
Ex: $wc
Hello
World
[ctrld] //end ofinput
2 2 10 //output
The shell’s manipulative nature finds place here .It can reassign the
standard input file to a disk file.It can redirect the standard input to
originate from a file on disk.This redirection requires the <symbol
Ex: $catsample.txt
Hello
World
$ wc < sample.txt
2 2 10 //outputs
2) Standardoutput:
• The standard output can represent three possible destinations:
1] The terminal, the defaultdestination.
2] A file using the redirection symbols > and >>.
3] As input to another program using a pipeline.
• By default, the shell directs standard output from a command to thescreen.
The shell can effect redirection of this stream when it sees the > or >>
symbols in the command line.You can replace the default destination
with any file using > (right chevron) operator, followed by the
filename.
Ex:$wc sample.txt >temp.txt
$cat remp.txt
2 2 10 //output of c stored in temp.txt
The 1stcommand sends the word count of sample.txt to temp.txt;The
Unix
shell also provide the >> symbol (used twice) to append a file.
$wc sample.txt >> temp.txt
2 210
2 210
3) Standard Errors: Each of the three standard files is represented by a
number called filedescriptor.
Afileisopenedbyreferringtoitspathname,butsubsequentreadandwrite
operations identify the file by this filedescriptor.
The kernel maintains a table of file descriptors for every process running
in the system.The 1stthree slots are generally allocated to three standard
streams in thismanner.
0 Standardinput
1 Standardoutput
2 Standard error
Trying to “cat “ a non-existent file produces the errorstream.
Ex: $ catfoo
cat: cannot open foo
Cat files to open the file and writes to standard error.if you are not using
the c shell you can redirect this stream to afile.
The redirect output symbol (>) instructs the shell to redirect the error
messages of acommandto the specified file instead of to thescreen.
Ex: $cat foo>errorfile
cat:cannotopenfoo //error stream can’t be captured with>
Redirecting the standard error requires use of 2>symbols.
Ex: cat foo2>errorfile
$cat errorfile
cat:cannot open foo
arithmetic expressions;
Ex: $cat calc.txt
2^32
25*50
30*25 + 15^2
Youcanredirectbc’sstandardinputtocomefromthisfileandsaveoutput in
yetanother,
$ bc <calc.txt>result.txt
$ cat result.txt
4294967296 //this is2^32
1250 //this is25^50
975 //this is 30*25+15^2
Regular Expression
We often need to search a file for a pattern, either to see the lines containing (or not containing) it or to
have it replaced with something else. This chapter discusses two important filters that are specially suited
for these tasks – grep and sed. grep takes care of all search requirements we may have. sed goes further
and can even manipulate the individual characters in a line. In fact sed can de several things, some of
then quite well.
It scans the file / input for a pattern and displays lines containing the pattern, the line numbers or
filenames where the pattern occurs. It’s a command from a special family in UNIX for handling search
requirements.
will display lines containing sales from the file emp.lst. Patterns with and without quotes is possible. It’s
generally safe to quote the pattern. Quote is mandatory when pattern involves more than one word. It
returns the prompt in case the pattern can’t be located.
grep options
grep is one of the most important UNIX commands, and we must know the options that POSIX
requires grep to support. Linux supports all of these options.
-i ignores case formatching
-v doesn’t display lines matchingexpression
-n displays line numbers along withlines
-c displays count of number ofoccurrences
-l displays list of filenames only
-e exp specifies expression with thisoption
-x matches pattern with entireline
-f file takes pattrens from file, one perline
-E treats pattren as an extendedRE
-F matches multiple fixedstrings
‘director’ emp*.lst
all the above three patterns are stored in a separate file pattern.lst
It is tedious to specify each pattern separately with the -e option. grep uses an expression of a
different type to match a group of similar patterns. If an expression uses meta characters, it is termed a
regular expression. Some of the characters used by regular expression are also meaningful to theshell.
BRE charactersubset
The basic regular expression character subset uses an elaborate meta character set,
overshadowing the shell’s wild-cards, and can perform amazing matches.
grep supports basic regular expressions (BRE) by default and extended regular expressions
(ERE) with the –E option. A regular expression allows a group of characters enclosed within a pair of [ ],
in which the match is performed for a single character in the group.
A single pattern has matched two similar strings. The pattern [a-zA-Z0-9] matches a single alphanumeric
character. When we use range, make sure that the character on the left of the hyphen has a lower ASCII
value than the one on the right. Negating a class (^) (caret) can be used to negate the character class.
When the character class begins with this character, all characters other than the ones grouped in the
class are matched.
The *
The asterisk refers to the immediately preceding character. * indicates zero or more occurrences of the
previous character.
Notice that we don’t require to use –e option three times to get the same output!!!!!
The dot
A dot matches a single character. The shell uses ? Character to indicate that.
Most of the regular expression characters are used for matching patterns, but there
are two that can match a pattern at the beginning or end of a line. Anchoring a pattern is often
Unix
necessary when it can occur in more than one place in a line, and we are interested in its occurance only at
a particular location.
It is possible that some of these special characters actually exist as part of the text. Sometimes,
we need to escape these characters. For example, when looking for a pattern g*, we have to use \
To look for [, we use \[ To look for
.*, we use \.\*
If current version of grep doesn’t support ERE, then use egrep but without the –E option. -E
option treats pattern as an ERE.
SHELL PROGRAMMING
Shell Programming
• A shell script contains a list of commands which have to be executed regularly.
• The user can execute the shell script itself to execute commands in it.
• A shell script runs in interpretive mode. i.e. the entire script is compiled internally in memory and then
executed.
• Hence, shell scripts run slower than the high-level language programs.
/bin/sh
echo “Welcome to Shell Programming” # print message
echo “Today’s date : `date`” # print date
echo “My Shell :$SHELL” # print shell name
• The shell ignores all the characters that follow the # symbol. However, this does not apply to the first line.
"#! /bin/sh" indicates the path where the shell script is available.
• There are 2 ways to execute a shell script:
• By default, script is not executable. So, the chmod command can be used to make the script executable.
• The child shell reads and executes each statement in interpretive mode.
• The user can also execute a shell script by specifying the interpreter in the command line.
• Here, the script neither requires a executable permission nor an interpreter line.
Run:
$ sh program1.sh //Execute using sh interpreter
$ bash program1.sh //Execute using bash interpreter
Output:
Welcome to Shell Programming
Today’s date: Mon Nov 4 11:02:45 IST 2017
My Shell: /bin/sh
Environment Variable
• Environmental variables are used to provide information to the programs you use.
• If environment variables are not set properly, the users may not be able to use some commands.
• Environment variables are so called because they are available in the user's total environment
i.e. the sub-shells that run shell scripts and mail commands and editors.
• Some variables are set by the system, others by the users, others by the shell programs.
• For example:
$ env
HOME=home/kumar
9. IFS
• This variable contains a string of characters that are used as word separator in the command line.
• The string normally consists of the space, tab and newline characters.
10. LOGNAME
• This variable shows the username.
11. MAIL
• This variable specifies the path to user’s mailbox.
12. MAILCHECK
• This variable determines how often the shell checks the file for the arrival of new mail.
13. PATH
• This variable specifies the locations in which the shell should look for commands.
$PATH=/bin:/usr/bin
14. PS1 and PS2
• The shell has 2 prompts:
• The primary prompt $ is the one the user normally sees on the monitor. $ is stored in PS1.
The user can change the primary prompt as follows:
$ PS1="C>"
C> //similar to windows
• The secondary prompt > is stored in PS2.
16. TERM
• This variable indicates the terminal type that is used.
• Every terminal has certain characteristics that are defined in a separate control file in the terminfo
directory.
• If TERM is not set correctly, vi will not work and the display will be faulty.
• The value assigned can be a number, text, filename, device, or any other type of data.
• Syntax:
• For example:
$ x=50
$ echo $x //displays 50
• In command line, all words that are preceded by a $ are identified and evaluated as variables.
• A variable can be removed with unset and protected from reassignment by readonly. Both are shell
internal commands.
$ set count=5
$ readonly size = 10
• The variables exist only for a short time during the execution of a shell script.
• The variables are not available for the other scripts or processes.
• As the variables are defined and used by specific users, they are also called user-defined variables.
File .profile
• A profile file is a start-up file of an UNIX user.
• This file is a shell script that will be present in the home directory of each user.
• The system admin provides each user with a profile with a minimum working environment.
• However, the user can customize the profile as per their requirement.
A specific file for each individual user with responsibility for the user environment.
A universal file for all users with responsibility for the general environment.
• The user can view his ".profile" as follows:
$ cat .profile
MAIL= /var/mail/kumar
PATH=/bin:/usr/bin
PS1='$'
PS2='>'
SHELL=/usr/bin/bash
TERM= tty1
read and readonly Commands
read Command
• read command can be used for taking input from the keyboard.
• Syntax:
• The variables are used to hold inputs given with the standard input.
• Example: A shell script (program4.sh) to read a search string and filename from the terminal.
#!/bin/bash
echo "What is your name?"
read PERSON
echo "Hello, $PERSON"
Run:
$
program4.sh
Output:
What is your name?
RAMA Hello, RAMA
readonly Command
• readonly command can be used to make variables readonly i.e. the user cannot change the value of
variables.
• During shell scripting, we may need a few variables, which cannot be modified.
• Syntax:
variable=value
• For example:
$ readonly PI=3.14
$ echo $PI //displays 3.14
$ PI=6.12 // this will result in error
• ,'. Shell scripts can be run non-interactively and be used with redirection and pipelines.
• The arguments are assigned to special shell variables called shell parameters.
5) $?: Stores the exit status of the last command that was executed.
6) $$: Stores Pid of the current shell.
• Example: A shell script (program2.sh) to read and display various shell parameters from the command
line.
#!/bin/sh
echo "Total Number of Parameters : $#"
echo "File Name: $0"
echo "First Parameter : $1"
echo "Second Parameter : $2"
echo "Quoted Values: $*" echo
"Quoted Values: $@"
$echo "Exit value: $?"
echo "PID of current shell: $$"
Run:
$ program2.sh "RAJA RAM"
"MOHAN ROY" Output:
Total Number of Parameters
: 2 File Name : program2.sh
First Parameter : RAJA RAM
Second Parameter : MOHAN
ROY
Quoted Values: RAJA RAM MOHAN ROY // stored as "RAJA RAM MOHAN
ROY"
Quoted Values: RAJA RAM MOHAN ROY // stored as array= {"RAJA
RAM" , "MOHAN ROY"} Exit value: 0 // zero implies success
exit and Exit
PIDStatus of a Command
of current shell: 12345
• exit command can be used to terminate a program(or script).
• Exit status is a numerical value returned by every command upon its completion.
• Exit status can be used to devise program-logic that branches into different paths depending on success or
failure of a command.
• Example: A shell script to find relationship between 2 numbers. #!
/bin/usr
x=5; y=7
test $x –eq $y; echo "5=7: $? \n" test
$x –ne $y; echo "5!=7: $? \n" test $x –
gt $y; echo "5>7: $? \n " test $x –ge
$y; echo "5>=7: $? \n " test $x –lt $y;
echo "5<7: $? \n " test $x –le $y; echo
"5<=7: $? \n"
Output:
5=7: 1 // Returns nonzero exit status i.e. failure → False
5!=7: 0 // Returns zero exit status i.e. success → True
5>7: 1 // False
5>=7: 1 // False
5<7: 0 // True
5<=7: 0 // True
1) && Operator
• Syntax:
2) || Operator
• Syntax:
cmd1 || cmd2
• Here, cmd2 gets executed only when cmd1 fails.
$ cat student.lst
4 | MH | 10 | IS | 111
4 | MH | 11 | CS | 401
4 | GW | 11 | CS | 402
4 | VV | 11 | CS | 403
$ grep ‘VV’ student.lst && echo “Pattern found”
4 | VV | 11 | CS | 403
Pattern found
• So, test command can be used to handle the true or false value returned by evaluation of an expression.
• Test command
• Test command
Numeric Comparison
Operator Meaning
-eq Equal to
• Numeric comparison can be done on integer values only. (The decimal values are truncated).
/bin/usr
x=5; y=7
test $x –eq $y; echo "5=7: $? \n" test
$x –ne $y; echo "5!=7: $? \n" test $x –
gt $y; echo "5>7: $? \n " test $x –ge
$y; echo "5>=7: $? \n " test $x –lt $y;
echo "5<7: $? \n" test $x –le $y; echo
"5<=7: $? "
Output:
5=7: 1 // False
5!=7: 0 // True
5>7: 1 // False
5>=7: 1 // False
5<7: 0 // True
5<=7: 0 // True
String Comparison
• Test command is also used for testing strings.
Operator True if
#!/bin/sh
echo “Enter the first string: \c”
read str1
if [ -z “$str1” ] ; then
echo “You have not entered the string”; exit 1
echo “Enter the second string: \c”
read str2
if [ -z “$str2” ] ; then
echo “You have not entered the string”; exit 1
if[ $str1= $str2]
then
else
echo "Both strings are equal" echo "Strings
are unequal"
Output:
Enter the first string:
MAM Enter the second
string: MAM Both strings
are equal
File Tests
• Test command can be used to check various file attributes such as file type (-, d or l) & file permission (r,
w, x).
Test True if
• Example: A shell script (program8.sh) to check whether a file has permission for read, write and execute.
#! /bin/usr
echo -n "Enter file name:"
read file
if [–e $file] ;
then
else fi
echo “File exists \n”
Run:
$ ls –l student.lst
-rw-rw-rw- 1 kumar group 870 jun 8 15:52 student.lst
$ program8.sh
Output:
Enter file name: student.lst File
exists
File is readable
File is writable
File is not executable
if Statement
• if statement is basically a “two-way” decision statement.
1) if...fi statement
2) if...else...fi statement
3) if...elif...else...fi statement
• Syntax 1:
if command is successful
then
execute statements
fi
• Syntax 2:
if command is successful
then
else execute statements
fi execute statements
• Syntax 3:
if command is successful
then
execute statements
elif command is successful
then
/bin/sh
echo “Enter any non zero integer: \n”
read num
if [$num -gt 0]; then
echo “Number is positive number”
else
echo “Number is negative number”
Output:
Enter any non zero
integer: 5
Number is positive number
case Statement
• case statement is basically a “multi-way” decision statement.
• This also handles string tests, but in a more efficient manner than if statement.
• Syntax:
case expression in
pattern1) statement1 ;;
pattern2) statement2 ;;
pattern3) statement3 ;;
…
esac
• Here is how it works:
• This can match only strings but cannot handle numeric and file tests.
However, this can also handle numbers but treating them as strings.
• This is very effective when the string is fetched by command substitution.
/bin/sh
echo “enter grade A to D \n”
read grade
case “$grade” in
A) echo “Excellent!” ;;
Output:
enter grade A to
DB
Well done
Your grade is B
Matching Multiple Patterns
• case statement can also specify the same action for more than one pattern.
• Example: A script to test a user response for both y and Y (or n and N). #!
/bin/sh
echo “Do you wish to continue? [y/n]:”
read ans
case “$ans” in
Y | y ) ;;
N | n ) exit ;;
esac
/bin/sh
echo “Do you wish to continue? [y/n]:”
read ans
case “$ans” in
[Yy] [eE]* ) ;; # Matches YES, yes, Yes, yEs, etc
[Nn] [oO] ) exit ;; # Matches no, NO, No, nO
* ) echo “Invalid Response”
esac
• Syntax:
$ x=5 y=3
$ expr $x + $y // outputs 8
$ expr $x - $y // outputs 2
$ expr $x \* $y // * must be escaped to prevent shell from interpreting * as wildcard
//outputs 15
$ expr $x / $y //outputs 1
[Dept. of CSE ]Page 40
[Unix notes]
$ expr $x % $y // outputs 2
$ z =`expr $x + $y` // command substitution to assign a variable
$ echo $z // outputs 8
2) String Handling
• Syntax:
• The regular expression ".*" is used to print the number of characters matching the pattern.
• Syntax:
• expr command can be used to extract a string enclosed by the escape characters "\(" and "\)".
• Syntax:
• expr command can be used to find the location of the first occurrence of a character inside a string.
• Syntax:
while Statement
[Dept. of CSE ]Page 41
[Unix notes]
• while loop can be used to execute a set of statements repeatedly as long as a given condition is true.
• Syntax:
/bin/sh
num=1
while [$num -le 3]
do
echo " Welcome to Shell Programming "
expr $num = $num +1;
done
Output:
Welcome to Shell
Programming Welcome to
Shell Programming
for Statement
Welcome to Shell
• for loop can be used
Programming to iterate over all items(or strings) within a list.
• Syntax:
• The iteration continues until all items are picked from the array.
#! /bin/sh
print("Here are the numbers in the list: \n"); for
var in 10 20 30 40 50 60;
do
echo “$var \t”
done
Output:
Here are the numbers in the
list 10 20 30 40 50 60
Output:
Dream Believe Achieve
#! /bin/sh
for var in `date`
do
echo “$var \t”
done
Output:
Mon Nov 4 08:02:45 IST 2017
#! /bin/sh
for file in *.pdf
do
echo "Printing $file \n"
lp $file
done
Output:
Printing
chap1.pdf
Printing
chap2.pdf
4) List from
Printing
Positional Parameters
chap3.pdf
• Example: A script (program4.sh) to read & display a positional parameters using for-loop. #!
/bin/sh
for var in "$*" # even "$@" can be used
do
echo "$var \t"
done
Run:
$ program4.sh A
B C Output:
A B C
• This command can be used for picking up individual fields from the output of a program.
• Example:
$ set 98 23 62
• Here, above line assigns
→ 98 to $1
→ 23 to $2
→ 62 to $3.
• This command can also be used to assign the other parameters $# and $*.
• Example:
$ set `date`
$ echo $*
Mon Nov 4 08:02:45 IST 2017
• Example:
shift
• shift command is a shell built-in that operates on the positional parameters.
• Each time shift command is called, it shifts/transfers all the positional parameters down by one.
$3 becomes $2
$4 becomes $3, and so on.
• Example:
When set command is used with command substitution, the output of the command may begin with a
-(hypen). In this case, set command interprets -(hypen) as an option and does not work correctly.
• For example:
here document.
• The term 'here' signifies that the data is here rather than in the file.
• Any command using standard input can also take input from a here document.
• Syntax:
• The shell treats every line delimited by MARK as input to the command mailx.
• kumar at the other end will see 3 lines of message text with the date inserted by command.
• For example:
$ wc -l << END
Decide
Commit
Succeed
END
3 //outputs number of lines = 3
trap
• trap is a signal handler.
• Whenever the interrupt key (Ctrl+C) is pressed, a signal SIGINT is sent to terminate the shell script.
• However, it is not a good practice. For instance, the user may end up leaving a lot of temporary files on the
disk.
• trap command can be used to perform clean up operation when a script receives a terminate signal.
• Syntax:
• The command_list contains the commands to be executed when the signals are received by the script.
• Example:
Ignoring Signals
• A script can be made to ignore a specific signal by using a null command list.
• Example:
trap ‘ ’ SIGINT
• Here, the script ignores a signal SIGINT when it is received.
1) A shell script to accept a filename as argument and displays the last modification time if the file exists
2) A shell script to accept 2 file names & check if the permission for these files are identical and if they are
Output:
Enter 2 filenames: p1.c p2.c
Different file permissions
file permission for p1.c is rw-r-
-r-- file permission for p2.c is
rwxr-xr-x
3) A shell script to print first 10 numbers (1 to 10)
#!/bin/sh
x=0
while [$x –le 10];
do
Output:
1 2 3 4 5 6 7 8 9 10
4) A shell script (program4.sh) to accept any number of arguments and print them in a reverse order. For
Run:
$ program4.sh A
B C Output:
CBA
5) A shell script to create a menu, which displays the list of files, process status, current date and current
Output:
MENU
1. List of files 2. Processes of user
3. Today’s Date 4. Users of system
5. Quit
Enter your option: 3
Mon Oct 8 08:02:45 IST 2007 // date command executed
• A shell script to read a string from terminal and display suitable message if it doesn't have at least 10
characters using expr.
#!/bin/sh
echo “Enter a string: \c”
read str
length = `expr “$str” : ".*" `
if [ $length -lt 10 ]
then
echo "The string has less than 10 characters"
else echo "The string has $length characters"
fi
Output:
Enter a string:
vtunotesbysri The string
has 13 characters
• A shell script to read a string from terminal and display suitable message if it doesn't have at least 10
characters using case.
#!/bin/sh
echo “Enter a string: \c”
read str
length = (${#str}<10)
case $length in
• echo "The string has less than 10 characters" ''
*) echo "The string has $length characters" ;;
esac
Output:
Enter a string:
vtunotesbysri The string
has 13 characters
• A shell script to read a pattern and filename from the terminal. And search for the pattern in the file.
#! /bin/sh
echo “Enter the pattern to be searched: \c”
read pname
echo “Enter the file to be used: \c”
read fname
echo “Searching for pattern $pname from the file $fname”
grep $pname $fname
echo “Selected records shown above”
Output:
Enter the pattern to be searched :
MH Enter the file to be used:
student.lst
Searching for pattern MH from the file
student.lst 4 | MH | 10 | IS | 111
4 | MH | 11 | CS | 401
Selected records shown above
• A shell script (program10.sh) to compute sum of numbers passed in command line
#!/bin/sh
sum=0
for I in “$@”
do
sum =`expr $sum + $I`
done
echo “sum is $sum”
Run:
$ program10.sh 2 4
6 Output:
sum is 12
Run:
$ cat
student.lst
RAMA
KRISHNA
$
program11.sh
Output:
string is
RAMA
length is 4
string is
KRISHNA
length is 7
Output:
ch1 copied to
ch1.doc ch2 copied
to ch2.doc ch3
copied to ch3.doc
• A shell script to check if the length of the name is greater than 20 characters.
#!/bin/sh
echo “Enter your name: \c”
read name
if [`expr “$name” : ".*" `-gt 20] ; then
echo “Name is very long”
else
fi echo “You can proceed!”