The UNIX File System Contains Several Different Types of Files

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

UNIX AND SHELL PROGRAMMING

MODULE 2: File System and Basic File attributes.

UNIX system has thousands of files. If you write a program, you add one more file to the system. When
you compile it you add some more. Files grow rapidly, and if they are not organized properly, you will
find it difficult to locate them. So UNIX has a file system (UFS) to manage or organizes its own files in
directory.
1. UNIX FILES AND BASIC FILE TYPES/CATEGORIES
FILES SUPPORTED BY UNIX FILE SYSTEM
File is a collection of records. So, files are divided into three categories
a. Ordinary file
b. Directory file
c. Device file
The UNIX file system contains several different types of files:
a.Ordinary Files or regular files
It contains only data as a stream of characters.
An ordinary files itself divided into 2 types
Text file: contains only printable characters, and you can often view the contents and make sense
out of them. All C and Java files are example of text file. A text file contains lines of characters
where every line is terminated with the newline character, also known as linefeed (LF) when you
press Enter while inserting text, the LF character is appended to every line. You won’t see this
character normally, but there is command (od) which can make it visible.
Binary file: it contains both printable and unprintable characters that cover the entire ASCII
range(0 to 255).most UNIX commands are example of binary files.
b. Directory files
i. Contains no data, but keeps some details of the files and subdirectories that it contains.
ii. A directory file contains an entry for every file and sub directory that it houses. Each entry has
two components
• The filename
• A unique Identification number for the file or directory( called the inode number)
iii. A directory contains the filename but not the contents of file.
iv. When you create or remove a file the kernel automatically updates its corresponding
directory by adding or removing the enter i.e inode number associated with that file.
c. Device files
i. Used to represent a real physical device such as a printer, tape drive or terminal, used for
Input/Ouput (I/O) operations
ii. Unix considers any device attached to the system to be a file - including your terminal:
iii. By default, a command treats your terminal as the standard input file (stdin) from which to
read its input
iv. Your terminal is also treated as the standard output file (stdout) to which a command's output
is sent.
v. stdin and stdout will be discussed in more detail later
vi. Two types of I/O: character and block
vii. Usually only found under directories named /dev

Padmaja.k, Asst Prof, Dept of Page 30


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

2. NAMING FILES OR WHAT’S IN A (FILE) NAME


a. UNIX permits file names to use most characters, but avoid spaces, tabs and characters that have a
special meaning to the shell, such as:
& ; () | ? \ ' " ` [] {} <> $ - ! /
b. It is recommended that only the following characters be used in filenames.
c. Alphabetic characters and numerals
d. The period(.), the hyphen(-) and underscore(_)
e. Case Sensitivity: uppercase and lowercase are not the same! These are three different files:
NOVEMBER November november
f. Length: can be up to 256 characters
g. Extensions: may be used to identify types of files
libc.a - archive, library file
program.c - C language source file
alpha2.f - Fortran source file
xwd2ps.o - Object/executable code
mygames.Z - Compressed file

3. PARENT CHILD RELATIONSHIP/ UNIX FILE SYSTEM


All files in UNIX are related to one another. The file system in unix is a collection of all ordinary,
directory and device files and organized in a hierarchical structure as shown in below fig.

The implicit feature of every UNIX file system is that there is a top which serves as reference point for
all files.This top is called root & is represented by a /(front slash). Root is actually a directory. The root
Padmaja.k, Asst Prof, Dept of Page 31
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

directory has a number of sub directories under it. These sub directories in turn have more sub directories
and others files under them.
For instance bin and usr are two directories directly under root, while a second bin and kumar are sub
directories under usr.
Every file apart from root must have a parent. Thus the home directory is the parent of kumar , while /
is the parent of home and grandparent of kumar. If you create a file login.sql under the kumar directory
,then kumar will be the parent of this file.
The first group contains the files that are made available during system installation
• /bin and /usr/bin: these are the directories where all the commonly used UNIX commands are
found.
• /sbin and /usr/sbin: If there’s a command that you can’t execute but the system administrator
can execute, it would be probably in one of these directories.
• /etc: this directory contains the configuration files of the system. You can change a very important
aspect of system functioning by editing a text file in this directory. Your login name and password
are stored in files /etc/passwd and etc/shadow
• /dev: This directory contains all device files. These files don’t occupy space on disk.there could
be more sub directories like pts, dsk and rdsk in this directory
• /lib and /usr/lib: Contains shared library files and sometimes other kernel-related files.
• /usr and /include: contains the standard header files used by C programs. The statement
#include<stdio.h> used in most C programs referes to the file stdio.h in this directory.
• /usr/share/man: this is where the man pages are stored. There are separate subdirectories
here(like man1,man2 etc) that contains the pages for each section. For instance, the man page of
ls can be found in /usr/share/man/man1
User also work with their own files, they write programs, send and receive mail and also create temporary
files. These files are available in the second group shown below
• /tmp: the directory where users are allowed to create temporary files. These files are wiped
away regularly by the system
• /var: The variable part of the file system. Contains all your print jobs and your outgoing and
incoming mail.
• /home:On many systems users are housed here.Kumar would have his home directory in
/home/kumar

4. THE HOME VARIABLE and THE PATH VARIABLE


HOME DIRECTORY : When log on to the system, UNIX automatically places you in a directory
called the home directory.
• It is created by the system when user account is opened.
• If you log in using the login name sharma , you will land up in a directory that could have the
pathname
/home/sharma
• The shell variable HOME known’s yours home directory
$echo $HOME
/home/sharma
You will be doing much of your work in your home directory and subdirectories.
• Home variable: it is also called environment variables. Environment variables are a set of
dynamic named values that can affect the way running processes will behave on a computer.
• Here $HOME is a environment variable it indicates the home directory of the current user: the
default argument for the cd built-in command.
Padmaja.k, Asst Prof, Dept of Page 32
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

5. PATH VARIABLE:
• The PATH environment variable is a colon-delimited list of directories that your shell searches
through when you enter a command.
• Program files (executables) are kept in many different places on the Unix system. Your path
tells the Unix shell where to look on the system when you request a particular program.
• To find out what your path is, at the Unix shell prompt echo $PATH
• Your path will look something like the following.
/usr2/username/bin:/usr/local/bin:/usr/bin:.
You will see your username in place of username. Using the above example path, if you enter the ls
command, your shell will look for the appropriate executable file in the following order: first, it would
look through the directory /usr2/username/bin, then /usr/local/bin, then /usr/bin, and finally the local
directory, indicated by the . (a period).

6. DIRECTORY COMMANDS – PWD, CD, MKDIR, RMDIR COMMANDS


6.1 pwd (PRINT WORKING DIRECTORY) (checking your current directory)
As the name states, command ‘pwd‘ prints the current working directory or simply the directory user is,
at present. It prints the current directory name with the complete path starting from root (/). This
command is built in shell command and is available on most of the shell – bash, Bourne shell, ksh,zsh,
etc.
Basic syntax
$pwd [option]
Options Description
-L (logical) Use PWD from environment, even if it contains symbolic links
-P (physical) Avoid all symbolic links
–help Display this help and exit
–version Output version information and exit

If both ‘-L‘ and ‘-P‘ options are used, option ‘L‘ is taken into priority. If no option is specified at the
prompt, pwd will avoid all symlinks, i.e., take option ‘-P‘ into account.

6.2 cd: CHANGING THE CURRENT DIRECTORY


• The cd command, which stands for "change directory", changes the shell's current working
directory.
• The cd command is one of the commands you will use the most at the command line in UNIX.
• It allows you to change your working directory. You use it to move around within the hierarchy
of your file system.
Ex 6.2.1 When used with an argument it changes the current directory to the directory specified as
argument for example assume gmit is a directory under user directory Kumar.To change from Kumar
directory to gmit directory , issue the command as follows
$pwd
/home/kumar
$cd gmit
$pwd
/home/kumar/gmit

Ex 6.2.2:When cd used without arguments: cd when used without arguments reverts to home directory
Padmaja.k, Asst Prof, Dept of Page 33
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

$pwd
/home/kumar/gmit
$cd
cd without argument will change directory from gmit to its home directory Kumar
$pwd
/home/kumar

Ex 6.2.3: If your present working directory is /home/Kumar and you need to switch to /bin directory
directly, use absolute pathname i.e /bin wd cd command
$pwd
/home/kumar
$cd /bin
$pwd
/bin

6.3 mkdir: "making directory".


• mkdir is used to create directories on a file system.
• If the specified DIRECTORY does not already exist,mkdir creates it.
• More than one DIRECTORY may be specified when calling mkdir.
mkdir syntax
mkdir [OPTION ...] DIRECTORY ...

Ex 6.3.1: To create a directory named gmit, issue the following command.


$mkdir gmit
gmit directory is created under present working directory.
Assume that pwd is /home/kumar , then gmit directory is created under kumar directory.

Ex 6.3.2: To create three directories at a time, named patch, dbs, doc, pass directory names as argu-
ments.
$mkdir patch dbs doc

Ex 6.3.3:To create a directory tree:


To create a directory named gmit and create two subdirectories named cse and ise under gmit, issue the
command. gmit is a parent directory.
$mkdir parent directory sub-directories
$mkdir gmit gmit/cse gmit/ise

Ex 6.3.4: Error while creating a directory tree


$mkdir gmit/cse gmit/ise
mkdir: Failed to make a directory “gmit/cse”; no such file or directory
mkdir: Failed to make a directory “gmit/ise”; no such file or directory

Padmaja.k, Asst Prof, Dept of Page 34


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

Error is due to the fact that the parent directory named gmit is not created before creating sub directo-
ries cse and ise.
Ex 6.3.5: $mkdir test
mkdir: Failed to make directory “test”; Permission denied.
This can happen due to:
a. The directory named test may already exist
b. There may be an ordinary file by the same name in the current directory.
c. The permissions set for the current directory do not permit the creation of files and directories by the
user.

6.4 rmdir: REMOVING DIRECTORIES


The rmdir utility removes the directory entry specified by each directory argument, provided the direc-
tory is empty.
Ex 6.4.1: $rmdir progs
removes the directory named progs
Arguments are processed in the order given. To remove both a parent directory and a subdirectory of that
parent, the subdirectory must be specified first, so the parent directory is empty when rmdir tries to
remove it.
The reverse logic of mkdir is applied.
$rmdir subdirectories parent directory
$rmdir gmit/cse gmit/ise gmit
• You cant delete a directory with rmdir unless it is empty.In this example gmit directory cannot be
removed until the sub directories cse and ise are removed.
• You cant remove a sub directory unless you are place in a directory which is hierarchically above
the one you have chosen to remove.

6.5 ABSOLUTE PATHNAMES:


• If the first character of a pathname is / the files location must be determined with respect to root(/)
. Such a pathname is called absolute pathname.
cat /home/kumar
• When you have more than one / in a pathname for such / you have to descend one level in the file
system. Thus Kumar is one level below home and two levels below root.
• When you specify a file y using frontslashes to demarcate the various levels,you have a
mechanism of identifying a file uniquely.No two files in a UNIX system can have same absolute
pathnames.
• When you specify the date command, the system has to locate the file date from a list of
directories specified in the PATH variable and then execute it.
• However if you know the location of a command in prior, for example date is usually located in
/bin or /usr/bin . Use absolute pathname i,e precede its name with complete path
$/bin/date
For example if you need to execute program less residing in /usr/local/bin you need to enter
the absolute pathname
$/usr/local/bin/less

Padmaja.k, Asst Prof, Dept of Page 35


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

6.6 RELATIVE PATHNAMES


• Pathnames that don’t begin with / specify locations relative to your current working directory.
• Uses either the current or parent directory as reference and specifies path relative to it.
• A relative pathname uses one of these cryptic symbols.
. (a single dot)-→ this represents the current directory.
.. (two dots)→this represents the parent directory

Command Function
cd Returns you to your login directory
cd ~ Also returns you to your login directory
cd / Takes you to the entire system’s root directory
cd /root Takes you to the home directory of the root or superuser,account
created at installation, you must be root user to access this directory.
cd /home Takes you to the home directory where user login directories are
usually stored
cd .. Moves you up one directory
cd ~otheruser Takes you to the otheruser’s login directory
cd /dir/subdirfoo Regardless of which directory you are in, the absolute path takes you
directly to subdirfoo, a subdirectory of dir.

Ex .6.6.1: Assume the current directory is /home/kumar/progs/data/text, using cd .. will move one level
up
$pwd
/home/kumar/progs/data/text
$ cd ..
$pwd
/home/kumar/progs/data

Ex 6.6.2 : To move two levels up


$pwd
/home/kumar/progs
$ cd ../..
$pwd
/home

Ex 6.6.3: My present location is /etc/samba and now I want to change directory to /etc.
Using relative path: $ cd ..
Using absolute path: $cd /etc

Ex 6.6.4: My present location is /var/ftp/ and I want to change the location to /var/log
Using relative path: cd ../log
Using absolute path: cd /var/log

Ex 6.6.5: My present location is /etc/lvm and I want to change my location to /opt/oradba


Using relative path: cd ../../opt/oradba
Using absolute path: cd /opt/oradba

Padmaja.k, Asst Prof, Dept of Page 36


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

7. ls : listing directory contents:


To obtain a list of all filenames in the current directory.
Numerals first
Uppercase next
Lowercase Then

$ls
Output:08_packets.html
calendar
dept.lst
emp.lst
helpdir
uskdsk06

ls options:
• Output in multiple columns(-x):
$ls -x
08_packets.html calendar dept.lst emp.lst
helpdir progs usdsk07 usdsk07

• Identifying directories and executables(-F)


$ ls –Fx
08_packets.html calendar* cptodos.sh* dept.lst
emp.lst helpdir / progs / usdsk07
The * indicates the file contains the executable code and / refers to directory
• Showing Hidden files also(-a):
$ls –axF
.profile .exrc .kshrc .xinitrc
08_packets.html calendar* cptodos.sh* dept.lst emp.lst
helpdir / progs / usdsk07
The hidden files are indicated by . (dot) displayed before filename.
• Listing directory contents:
$ls –x helpdir progs
helpdir:
forms.obd graphics.obd
progs:
array.pl n2words.pl
Padmaja.k, Asst Prof, Dept of Page 37
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

If we specify two directories named helpdir and progs , the contents of the directory i,e filenames are
listed out.
• Recursive listing(-R)
The recursive option lists all sub-directories and files in a directory tree structure.
$ls -xR
08_packets.html calendar cptodos.sh dept.lst
emp.lst helpdir progs usdsk07
./helpdir
forms.hlp graphics.hlp
./progs
arrays.pl n2words.pl

8. Cat command : Displaying and creating files


cat is one of the most well known commands of UNIX system.
Cat is useful for creating a file .
Its mainly used to display the contents of a small file on the terminal.
• Using cat to create a file:
Enter the command cat, followed by >(right chevron) character and the filename.
Example: take a filename named foo
$ cat > foo
> Symbol following command means that the output goes to filename following it.
[ctrl+d] /* to terminate or to signify end of the input.
$
• Using cat to display a file
Enter the cat command followed by filename
$ cat foo
Symbol following command means that the output goes to filename following it.
Cat options (-v and -n)
Displaying Non printing characters(-v)
cat is normally used for displaying text files only. If you have non-printing ASCII characters in
your input , you can see cat with -v option to display these characters
Numbering lines(-n)
The -n option numbers lines.
Cat with more than one filename as arguments:
cat filename1 filename2 ....
cat chap01 chap02
The contents of second file are displayed immediately after the first file without any header
information.
9. cp: copying a file
• cp command copies a file or a group of files.it creates an exact image of the file on the disk with
the different name.
• The syntax requires atleast two filenames to be specified in the command line.
• When both are ordinary files, the first is copied to second file.
cp source file destination file
Padmaja.k, Asst Prof, Dept of Page 38
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

cp chap01 unit1
if destination file i.e unit1 does not exist, first it will be created before copying.if not it will
be simply overwritten without any warning.
• Copying a file to another directory
ex: assume there is a file named chap01 and it has to be copied to progs directory
cp chap01 progs
output: chap01 is now copied to directory named progs with the same name chap01.
• Copying a file to another directory with different name
ex: assume there is a file named chap01 and it has to be copied to progs directory with chap01
file renamed as unit1
cp chap01 progs/unit1
output: chap01 is now copied to directory named progs with the same name unit1

• Copy more than one file with a single command.


cp chap01 chap02 chap03 progs
chap01, chap02, chap03 files are copied to directory named progs.
• Copy all files beginning with chap
cp chap* progs

9.1 cp options:
Interactive copying (-i): the -i option warns the user before overwriting the destination file.
Ex: $ cp -i chap01 unit1
cp: overwrite unit1(yes/no)? y
A y at this prompt will overwrite the file.
Copying directory structure(-R) : the -R command behaves recursively to copy an entire directory
structure say progs to newprogs.
Ex say progs directory contains three files kernel, bash, korn. To copy all three files under progs to
newprogs directory
$ cp -R progs newprogs
10. rm : deleting files
The rm command deletes one or more files.
Ex 1: The following command deletes three files chap01, chap02, chap03.
$ rm chap01 chap02 chap03
Ex 2: to delete files named chap01 and chap02 under progs directory
$ rm progs/chap01 progs/chap02
Ex 3: to remove all file
$ rm*

10.1 rm options:
Interactive deletion (-i): the –i optin makes the command ask the user for confirmation before
removing each file.
$rm -i chap01 chap02 chap03
rm: remove chap01(yes/no)?y
rm: remove chap01(yes/no)?y
rm: remove chap01(yes/no)?y

Recursive deletion(-r or -R) deletes all subdirectories and files recursively. Rm wont normally

Padmaja.k, Asst Prof, Dept of Page 39


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

remove directories but when used with -r or -R option it will.


$ rm -r *
Forcing removal: rm prompts for removal, if a file is write protected. The -f option overrides this minor
protection and forces removal.
$ rm -rf * /*(deletes everything in the current directory and below)

11. mv: RENAMING FILES.


The mv command renames or moves files. It has two distinct functions:
a. It renames a file or directory
b. it moves a group of files to a different directory

To rename a file chap01 to man01


$ mv chap01 man01
mv replace the filename in the existing directory entry with the new name.
No additional space is consumed on disk during renaming.

To rename a directory:
$ mv pts perdir
pts directory is renamed as perdir

To move group of files to a directory


mv chap01 chap02 chap03 progs
to move three files chap01, chap02, chap03 to directory named progs

12. wc command: COUNTING LINES,WORDS,CHARACTERS


wc command takes one or more filenames as arguments and displays four columnar output.
First we will create a file named infile
$ cat > infile
I am the wc command
I count characters,words and lines
[ctrl+D]
$wc infile
2 10 55 infile
wc counts lines in first column ,words in second column,characters in third column and filename in
fourth column..
A line is any group of characters not containing a newline
A word is group of characters not containing a space tab or newline.
A character is the smallest unit of information and includes a space, tab and newline
wc options:
$ wc -l infile
2
$wc -w infile
10
$wc -c infile
55
• When two filenames are passed as wc argument

Padmaja.k, Asst Prof, Dept of Page 40


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

First line : number of lines, words and characters of chap01


Second line: number of lines, words and characters of chap02
Third line: Total number of lines, words and characters of both.
13. od Command: DISPLAYING DATA IN OCTAL.
$ cat odfile
White space includes a
The ^G character rings a bell

$ od -b odfile
The -b option displays the octal values for each character.
000000 127 150 151 164 145 040 163 160 141 143 145 040 151 156 143 154
000000 165 144 145 163 040 141 040 011 012 124 150 145 040 007 040 143
Each line displays 16 bytes of data in octal , preceded by the offset in the file of the first byte in the
line.

$od -bc odfile


The -b and -c option combined
Each line is now replaced with two.
The octal values are shown in first line and printable characters and escape sequences are shown in
second line
000000 127 150 151 164 145 040 163 160 141 143 145 040 151
W h i t e s p a c e i
156 143 154
n c l
000000 165 144 145 163 040 141 040 011 012 124 150 145 040
u d e s a \t \n T h e

007 040 143


007 c

The octal equivalent of characters are displayed ex for W- 127, i-151, \t (tab)-011, \n(newline)-012
^G(Bell character)- 007

BASIC FILE ATTRIBUTES


1. ls –l: LISTING FILE ATTRIBUTES
ls command is used to obtain a list of all filenames in the current directory. The output in UNIX lingo is
often referred to as the listing. Sometimes we combine this option with other options for displaying other
attributes, or ordering the list in a different sequence. ls look up the file’s inode to fetch its attributes. It
lists seven attributes of all files in the current directory and they are:
1.1 File type and Permissions
Padmaja.k, Asst Prof, Dept of Page 41
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

1.2 Links
1.3 Ownership
1.4 Group ownership
1.5 File size
1.6 Last Modification date and time
1.7 File name

1.1 The file type and its permissions: The first column shows the type and permissions associated with
each file.The first character in this column is mostly a – which indicates that the file is an ordinary one.
In unix, file system has three types of permissions- read, write and execute.

1.2 Links: The second column indicates the number of links associated with the file. This is actually the
number of filenames maintained by the system of that file.
1.3 Ownership: The third column shows the owner of files. The owner has full authority to tamper with
files content and permissions. Similarly, you can create, modify or remove files in a directory if you are
the owner of the directory.

1.4 Group ownership: The fourth column represents the group owner of the file. When opening a user
account, the system admin also assigns the user to some group. The concept of a group of users also
owning a file has acquired importance today as group members often need to work on the same file.

1.5 File size: The fifth column shows the size of the file in bytes. The important thing to remember here
is that it only a character count of the file and not a measure of the disk space that it occupies.

1.6 Last modification time: The sixth, seventh and eighth columns indicate the last modification time of
the file, which is stored to the nearest second. A file is said to be modified only if its content have changed
in any way.If the file is less than a year old since its last modification time, the year won’t be displayed.

1.7 Filename: The last column displays the filename arranged in ASCII collating sequence.
For example, $ ls –l
total 72
-rw-r--r-- 1 kumar metal 19514 may 10 13:45 chap01
-rw-r--r-- 1 kumar metal 4174 may 10 15:01 chap02
-rw-rw-rw- 1 kumar metal 84 feb 12 12:30 dept.lst
-rw-r--r-- 1 kumar metal 9156 mar 12 1999 genie.sh
drwxr-xr-x 2 kumar metal 512 may 09 10:31 helpdir
drwxr-xr-x 2 kumar metal 512 may 09 09:57 progs

2. LISTING DIRECTORY ATTRIBUTES (-d option)


• ls -d will not list all subdirectories in the current directory
For example,
$ls –ld helpdir progs
drwxr-xr-x 2 kumar metal 512 may 9 10:31 helpdir
drwxr-xr-x 2 kumar metal 512 may 9 09:57 progs

• Directories are easily identified in the listing by the first character of the first column, which
here shows a d.

Padmaja.k, Asst Prof, Dept of Page 42


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

• To see the attributes of a directory rather than the files contained in it, use ls –ld with the direc-
tory name.

3. FILE OWNERSHIP
• When you create a file, you become its owner and it shows up in the third column of the files
listing.
• Group name is seen in the fourth column; your group is the group owner of the file.
• Every owner is attached to a group owner. Several users may belong to a single group, but the
privileges of the group are set by the owner of the file and not by the group members.
• When the system administrator creates a user account, he has to assign these parameters to the
user:
The user-id (UID) – both its name and numeric representation
The group-id (GID) – both its name and numeric representation

4. FILE PERMISSIONS
• UNIX has a simple and well defined system of assigning permissions to files.
• Lets issue the ls –l command once again to view the permissions of a few lines .
$ls -l chap02 dept.lst dateval.sh
-rwxr-xr-- 1 kumar metal 25000 May 10 19:21 chap02
-rwxr-xr-x 1 kumar metal 890 Jan 10 23:17 dept.lst
-rw-rw-rw- 1 kumar metal 84 Feb 18 12:20 dateval.sh

Consider the first column.


- rwx r-x r—
Each group here represents the category and contain three slots representing the read, write and
execute permissions of the file.
r indicates the read permission; w indicates write permission; x indicates execute permission
- (hyphen) indicates the absence of the corresponding permission.
In the above example, the file permissions of chap02 file is
- rwx r-x r--
File owner/user group others
First group(rwx) has all the three permissions.
• The file is readable, writable and executable by the owner of the file, kumar.
• The third column shows the owner of the file.
• The first permissions group applies to kumar.
• You have to login with the name kumar for the privileges to apply to you.
Second group(r-x):
• has a hyphen in the middle slot, which indicates the absence of write permissions by the group
owner of the file.
• The group owner is metal and all users belonging to group metal has only read and execute per-
missions.

Third group(r--):
• has the write and execute bits absent.
• This set is applicable to others i,e those who are neither the owner nor group.
• This category is referred to as the world.

Padmaja.k, Asst Prof, Dept of Page 43


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

5. CHANGING FILE PERMISSIONS- chmod command.


A file or a directory is created with a default set of permissions, which can be determined by umask. Let
us assume that the file permission for the created file is -rw-r--r--. Using chmod command, we can change
the file permissions and allow the owner to execute his file. The command can be used in two ways:
5.1 In a relative manner by specifying the changes to the current permissions
5.2 In an absolute manner by specifying the final permissions

5.1 RELATIVE PERMISSIONS


chmod only changes the permissions specified in the command line and leaves the other permissions
unchanged.
Its syntax is:
chmod category operation permission filename(s)
chmod takes an expression as its argument which contains:
user category (user, group, others)
operation to be performed (assign or remove a permission)
type of permission (read, write, execute)

The below shows the abbreviations used by chmod command


Category operation permission
u - user + assign r - read
g – group - remove w - write
o - others = absolute x - execute
a - all (ugo)

Ex 1:
$ls –l xstart
-rw-r--r-- 1 kumar metal 1906 sep 23:38 xstart
Here user is having the only read and execute permission .

Using relative file permission need to add the execute permission to user
chmod category operation(+,-) permission filename.
$chmod u + x xstart
$chmod u+x xstart

$ ls –l xstart
-rwxr--r-- 1 kumar metal 1906 sep 23:38 xstart
After executing the chmod command, the command assigns (+) execute (x) permission to the user (u),
other permissions remain unchanged.

Ex 2: To remove execute permission from all and assign read permission to group and others
$chmod a-x, go+r xstart /*to remove execute permission from all(a)ie user, group, others
/*to assign read permission to group and others (go+r)

Ex 3: To assign write and execute permissions for others.


$chmod o+wx xstart

Padmaja.k, Asst Prof, Dept of Page 44


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

5.2 ABSOLUTE PERMISSIONS


A string of three octal digits is used as an expression. The permission can be represented by one octal
digit for each category. For each category, we add octal digits. If we represent the permissions of each
category by one octal digit, this is how the permission can be represented:
• Read permission – 4 (octal 100)
• Write permission – 2 (octal 010)
• Execute permission – 1 (octal 001)

Octal Permissions Significance


0 --- no permissions
1 --x execute only
2 -w- write only
3 -wx write and execute
4 r-- read only
5 r-x read and execute
6 rw- read and write
7 rwx read, write and execute

We have three categories and three permissions for each category, so three octal digits can describe a
file’s permissions completely. The most significant digit represents user and the least one represents
others. chmod can use this three-digit string as the expression.

Ex 1: To assign read,write permissions to all .Using relative permission, we have,


$chmod a+rw xstart

Using absolute permission, we have,


$chmod 666 xstart /* 6 for r-w
/* first digit 6 for user, second 6 for group and third 6 for others

Ex 2:
To assign read and write for user and remove write, execute permissions from group and others
• Here to assign rw- corresponds to digit 6
• Remove write , execute permissions is nothing but assigning only read option to group and oth-
ers
• Only read permission is r—corresponds to 4
$chmod 644 xstart

Ex 3:
To assign all permissions to the owner, read and write to group and only execute for others.
$chmod 761 xstart

Ex 4
To assign all permissions to all categories.
$chmod 777 xstart

5.3 The Security Implications


Let the default permission for the file xstart is
-rw-r—r--
Padmaja.k, Asst Prof, Dept of Page 45
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

$chmod u-rw, go-r xstart or


$chmod 000 xstart
After Executing above any one command the output will be removes the all permission from all
categories as shown below
----------

This is simply useless but still the user can delete this file
On the other hand,
chmod a+rwx xstart or
chmod 777 xstart
After Executing either of the one command it adds the all permission to all categories as shown
below
-rwxrwxrwx

The UNIX system by default, never allows this situation as you can never have a secure system. Hence,
directory permissions also play a very vital role here.

5.4 use chmod Recursively.(-R)


• It possible to make chmod descend directory hierarchy and apply the expression to every file
and sub directory it finds. This is done by using -R option
$chmod -R a+x shell_scripts

This makes all the files and subdirectories found in the shell_scripts directory, executable by all users.

6. DIRECTORY PERMISSIONS
• Directories also have their own permissions and the significance of these permissions differ
from those of ordinary files.
• The default permissions of a directory are,
rwxr-xr-x (755)
• A directory must never be writable by group and others

Ex1:
$mkdir c_progs ; ls –ld c_progs
drwxr-xr-x 2 kumar metal 512 may 9 09:57 c_progs
Here the c_progs directory is created (mkdir c_progs) and then the attributes of directory is listed out(ls
–ld c_progs)

If a directory has write permission for group and others also, be assured that every user can remove every
file in the directory. As a rule, you must not make directories universally writable unless you have definite
reasons to do so.

7. CHANGING FILE OWNERSHIP


There are two commands meant to change the ownership of a file or directory.
chown changing file owner and
chgrp changing group owner

Padmaja.k, Asst Prof, Dept of Page 46


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

7.1 chown : Changing file owner


• The syntax is
chown options owner [:group] file(s)
• For changing ownership requires super user permission. So let’s first change our status to that
of super user with the su command:
$su
Password: ******
#_
• After the password is successfully entered, su returns a # prompt, the prompt used by root. su
lets us acquire super user status if we know the root password.
• Consider the file note owned by kumar.To now renounce the ownership of the file note to Shar-
ma, use chown in the following way:
# ls -l note
-rwxr----x 1 kumar metal 347 may 10 20:30 note

#chown sharma note; ls -l note


-rwxr----x 1 sharma metal 347 may 10 20:30 note
Once ownership of the file has been given away to sharma, the user file permissions that previously
applied to Kumar now apply to sharma. Thus, Kumar can no longer edit note since there is no write
privilege for group and others. He cannot get back the ownership either. But he can copy the file to his
own directory, in which case he becomes the owner of the copy.

7.2 chgrp :Changing Group Owner


• This command changes the file’s group owner. No superuser permission is required.
$ ls –l dept.lst
-rw-r--r-- 1 kumar metal 139 jun 8 16:43 dept.lst
Here the group owner of dept.lst is metal

$chgrp dba dept.lst; ls –l dept.lst


-rw-r--r-- 1 kumar dba 139 jun 8 16:43 dept.lst

The group owner of the file dept.lst is changed from metal to dba by issuing the command
$chgrp dba dept.lst

The file attributes of dept.lst is listed by issuing the command


$ls –l dept.lst

• Using chown to change both file owner and group :


The syntax requires two arguments to be separated by :
chown sharma:dba dept.lst
Here the ownership of dept.lst is changed to sharma and group to dba

Padmaja.k, Asst Prof, Dept of Page 47


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

The if, while, for and case control statements.


we will learn following two statements that are used to control shell loops−
• The break statement
• The continue statement

The infinite Loop


All the loops have a limited life and they come out once the condition is false or true depending on
the loop.
A loop may continue forever if the required condition is not met. A loop that executes forever without
terminating executes for an infinite number of times. For this reason, such loops are called infinite
loops.
Example
Here is a simple example that uses the while loop to display the numbers zero to nine −
#!/bin/sh

a=10

until [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done

This loop continues forever because a is always greater than or equal to 10 and it is never less than
10.

The break Statement


The break statement is used to terminate the execution of the entire loop, after completing the
execution of all of the lines of code up to the break statement. It then steps down to the code following
the end of the loop.
Syntax
The following break statement is used to come out of a loop −
break
The break command can also be used to exit from a nested loop using this format −
break n
Here n specifies the nth enclosing loop to the exit from.
Example
Here is a simple example which shows that loop terminates as soon as a becomes 5 −
#!/bin/sh

Padmaja.k, Asst Prof, Dept of Page 48


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

a=0

while [ $a -lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done

Upon execution, you will receive the following result −


0
1
2
3
4
5
Here is a simple example of nested for loop. This script breaks out of both loops if var1 equals
2 and var2 equals 0 −
Live Demo
#!/bin/sh

for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo "$var1 $var2"
fi
done
done

Upon execution, you will receive the following result. In the inner loop, you have a break command
with the argument 2. This indicates that if a condition is met you should break out of outer loop and
ultimately from the inner loop as well.
1 0
1 5
The continue statement
The continue statement is similar to the break command, except that it causes the current iteration
of the loop to exit, rather than the entire loop.
This statement is useful when an error has occurred but you want to try to execute the next iteration
of the loop.
Padmaja.k, Asst Prof, Dept of Page 49
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

Syntax
continue
Like with the break statement, an integer argument can be given to the continue command to skip
commands from nested loops.
continue n
Here n specifies the nth enclosing loop to continue from.
Example
The following loop makes use of the continue statement which returns from the continue statement
and starts processing the next statement −
Live Demo
#!/bin/sh

NUMS="1 2 3 4 5 6 7"

for NUM in $NUMS


do
Q=`expr $NUM % 2`
if [ $Q -eq 0 ]
then
echo "Number is an even number!!"
continue
fi
echo "Found odd number"
done

Upon execution, you will receive the following result −


Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
we will examine the following types of loops available to shell programmers −

• The while loop


• The for loop
• The until loop
• The select loop
You will use different loops based on the situation. For example, the while loop executes the given
commands until the given condition remains true; the until loop executes until a given condition
becomes true.

Padmaja.k, Asst Prof, Dept of Page 50


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

Once you have good programming practice you will gain the expertise and thereby, start using
appropriate loop based on the situation. Here, while and for loops are available in most of the other
programming languages like C, C++ and PERL, etc.

Nesting Loops
All the loops support nesting concept which means you can put one loop inside another similar one
or different loops. This nesting can go up to unlimited number of times based on your requirement.
Here is an example of nesting while loop. The other loops can be nested based on the programming
requirement in a similar way −

Nesting while Loops


It is possible to use a while loop as part of the body of another while loop.
Syntax
while command1 ; # this is loop1, the outer loop
do
Statement(s) to be executed if command1 is true

while command2 ; # this is loop2, the inner loop


do
Statement(s) to be executed if command2 is true
done

Statement(s) to be executed if command1 is true


done
Example
Here is a simple example of loop nesting. Let's add another countdown loop inside the loop that you
used to count to nine −
#!/bin/sh

a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done

This will produce the following result. It is important to note how echo -n works here. Here -n option
lets echo avoid printing a new line character.
0
1 0
2 1 0
Padmaja.k, Asst Prof, Dept of Page 51
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0

CASE STATEMENTS
Syntax
The syntax is as follows:

case $variable-name in
pattern1)
command1
...
....
commandN
;;
pattern2)
command1
...
....
commandN
;;
patternN)
command1
...
....
commandN
;;
*)
esac

OR

case $variable-name in
pattern1|pattern2|pattern3)
command1
...
....
commandN
;;
pattern4|pattern5|pattern6)
command1
...
....
commandN
;;
pattern7|pattern8|patternN)
command1
...
Padmaja.k, Asst Prof, Dept of Page 52
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

....
commandN
;;
*)
esac

• The case statement allows you to easily check pattern (conditions) and then process a command-line if that
condition evaluates to true.
• In other words the $variable-name is compared against the patterns until a match is found.
• *) acts as default and it is executed if no match is found.
• The pattern can include wildcards.
• You must include ;; at the end of each commandN. The shell executes all the statements up to the two
semicolons that are next to each other.
• The esac is always required to indicate end of case statement.
Example
Create a shell script called rental.sh:

#!/bin/bash

# if no command line arg given


# set rental to Unknown
if [ -z $1 ]
then
rental="*** Unknown vehicle ***"
elif [ -n $1 ]
then
# otherwise make first arg as a rental
rental=$1
fi

# use case statement to make decision for rental


case $rental in
"car") echo "For $rental rental is Rs.20 per k/m.";;
"van") echo "For $rental rental is Rs.10 per k/m.";;
"jeep") echo "For $rental rental is Rs.5 per k/m.";;
"bicycle") echo "For $rental rental 20 paisa per k/m.";;
"enfield") echo "For $rental rental Rs.3 per k/m.";;
"thunderbird") echo "For $rental rental Rs.5 per k/m.";;
*) echo "Sorry, I can not get a $rental rental for you!";;
esac

Save and close the file. Run it as follows:

chmod +x rental.sh
./rental.sh
./rental.sh jeep
./rental.sh enfield
./rental.sh bike

Sample outputs:

Sorry, I can not get a *** Unknown vehicle *** rental for you!
Padmaja.k, Asst Prof, Dept of Page 53
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

For jeep rental is Rs.5 per k/m.


For enfield rental Rs.3 per k/m.
Sorry, I can not get a bike rental for you!

The case statement first checks $rental against each option for a match. If it matches "car", the echo command will
display rental for car. If it matches "van", the echo command will display rental for van and so on. If it matches
nothing i.e. * (default option), an appropriate warning message is printed.

Using Multiple Patterns


#!/bin/bash
NOW=$(date +"%a")
case $NOW in
Mon)
echo "Full backup";;
Tue|Wed|Thu|Fri)
echo "Partial backup";;
Sat|Sun)
echo "No backup";;
*) ;;
esac

The following shell script demonstrate the concept of command line parameters processing using the case
statement (casecmdargs.sh):

#!/bin/bash
OPT=$1 # option
FILE=$2 # filename

# test -e and -E command line args matching


case $OPT in
-e|-E)
echo "Editing $2 file..."
# make sure filename is passed else an error displayed
[ -z $FILE ] && { echo "File name missing"; exit 1; } || vi $FILE
;;
-c|-C)
echo "Displaying $2 file..."
[ -z $FILE ] && { echo "File name missing"; exit 1; } || cat $FILE
;;
-d|-D)
echo "Today is $(date)"
;;
*)
echo "Bad argument!"
echo "Usage: $0 -ecd filename"
echo " -e file : Edit file."
echo " -c file : Display file."
echo " -d : Display current date and time."
;;
esac

Run it as follows:

chmod +x casecmdargs.sh

Padmaja.k, Asst Prof, Dept of Page 54


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

./casecmdargs.sh
./casecmdargs.sh -e /tmp/file
./casecmdargs.sh -E /tmp/file
./casecmdargs.sh -e
./casecmdargs.sh -D

Creating a backup script


Create a backup script called allinonebackup.sh:

#!/bin/bash
# A shell script to backup mysql, webserver and files to tape
opt=$1
case $opt in
sql)
echo "Running mysql backup using mysqldump tool..."
;;
sync)
echo "Running backup using rsync tool..."
;;
tar)
echo "Running tape backup using tar tool..."
;;
*)
echo "Backup shell script utility"
echo "Usage: $0 {sql|sync|tar}"
echo " sql : Run mySQL backup utility."
echo " sync : Run web server backup utility."
echo " tar : Run tape backup utility." ;;
esac

Save and close the file. Run it as follows:

chmod +x allinonebackup.sh
# run sql backup
./allinonebackup.sh sql
# Dump file system using tape device
./allinonebackup.sh tar
# however, the following will fail as patterns are case sensitive
# you must use command line argument tar and not TAR, Tar, TaR etc.
./allinonebackup.sh TAR

SHIFT COMMAND

• The shift command in UNIX is used to move the command line arguments to one position left. The first
argument is lost when you use the shift command.
• Shifting command line arguments is useful when you perform a similar action to all arguments one-by-one,
without changing the variable name. The shift command throws away the left-most variable (argument
number 1) and reassigns values to the remaining variables.
• The value in $2 moves to $1, the value in $3 moves to $2, and so on.

Padmaja.k, Asst Prof, Dept of Page 55


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

EXAMPLE FOR SHIFT COMMAND IN UNIX:

EXECUTION RESULTS:

SET COMMAND

Syntax
The basic syntax:

set [options]
set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]

set command examples


Let us see some common examples of set command.
Turn debugging information on or off
Pass the -x option to show commands and their arguments as they are executed. Useful for debugging shell script:

#!/bin/bash
set -x # Turn on debug
....
...
...
set +x # Turn off debug
....
...

POSITIONAL PARAMETRES

Padmaja.k, Asst Prof, Dept of Page 56


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0
. Positional parameters are assigned from the shell's arguments when it is invoked, and may be
reassigned using the set builtin command.

Positional Parameters
When we last left our script, it looked something like this:

#!/bin/bash

# sysinfo_page - A script to produce a system information HTML


file

##### Constants

TITLE="System Information for $HOSTNAME"


RIGHT_NOW="$(date +"%x %r %Z")"
TIME_STAMP="Updated on $RIGHT_NOW by $USER"

##### Functions

system_info()
{
echo "<h2>System release info</h2>"
echo "<p>Function not yet implemented</p>"

} # end of system_info

show_uptime()
{
echo "<h2>System uptime</h2>"
echo "<pre>"
uptime
echo "</pre>"

} # end of show_uptime

drive_space()
{
echo "<h2>Filesystem space</h2>"
Padmaja.k, Asst Prof, Dept of Page 57
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

echo "<pre>"
df
echo "</pre>"

} # end of drive_space

home_space()
{
# Only the superuser can get this information

if [ "$(id -u)" = "0" ]; then


echo "<h2>Home directory space by user</h2>"
echo "<pre>"
echo "Bytes Directory"
du -s /home/* | sort -nr
echo "</pre>"
fi

} # end of home_space

##### Main

cat <<- _EOF_


<html>
<head>
<title>$TITLE</title>
</head>
<body>
<h1>$TITLE</h1>
<p>$TIME_STAMP</p>
$(system_info)
$(show_uptime)
$(drive_space)
$(home_space)
</body>
</html>
_EOF_

Padmaja.k, Asst Prof, Dept of Page 58


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

We have most things working, but there are several more features we can
add:

1. We should be able to specify the name of the output file on the


command line, as well as set a default output file name if no name is
specified.

2. Let's offer an interactive mode that will prompt for a file name and
warn the user if the file exists and prompt the user to overwrite it.

3. Naturally, we want to have a help option that will display a usage


message.

All of these features involve using command line options and arguments.
To handle options on the command line, we use a facility in the shell
called positional parameters. Positional parameters are a series of special
variables ($0 through $9) that contain the contents of the command line.

Let's imagine the following command line:

[me@linuxbox me]$ some_program word1 word2 word3

If some_program were a bash shell script, we could read each item on the
command line because the positional parameters contain the following:

• $0 would contain "some_program"


• $1 would contain "word1"
• $2 would contain "word2"
• $3 would contain "word3"

Here is a script we can use to try this out:

#!/bin/bash

echo "Positional Parameters"


echo '$0 = ' $0
echo '$1 = ' $1
echo '$2 = ' $2
echo '$3 = ' $3
Detecting Command Line Arguments
Padmaja.k, Asst Prof, Dept of Page 59
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

Often, we will want to check to see if we have comand line arguments on


which to act. There are a couple of ways to do this. First, we could simply
check to see if $1 contains anything like so:

#!/bin/bash

if [ "$1" != "" ]; then


echo "Positional parameter 1 contains something"
else
echo "Positional parameter 1 is empty"
fi

Second, the shell maintains a variable called $# that contains the number
of items on the command line in addition to the name of the command
($0).

#!/bin/bash

if [ $# -gt 0 ]; then
echo "Your command line contains $# arguments"
else
echo "Your command line contains no arguments"
fi
Command Line Options
As we discussed before, many programs, particularly ones from the GNU
Project, support both short and long command line options. For example,
to display a help message for many of these programs, we may use either
the "-h" option or the longer "--help" option. Long option names are
typically preceded by a double dash. We will adopt this convention for our
scripts.

Here is the code we will use to process our command line:

interactive=
filename=~/sysinfo_page.html

while [ "$1" != "" ]; do


case $1 in
-f | --file ) shift
filename="$1"
Padmaja.k, Asst Prof, Dept of Page 60
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

;;
-i | --interactive ) interactive=1
;;
-h | --help ) usage
exit
;;
* ) usage
exit 1
esac
shift
done

This code is a little tricky, so we need to explain it.

The first two lines are pretty easy. We set the variable interactive to be
empty. This will indicate that the interactive mode has not been requested.
Then we set the variable filename to contain a default file name. If
nothing else is specified on the command line, this file name will be used.

After these two variables are set, we have default settings, in case the user
does not specify any options.

Next, we construct a while loop that will cycle through all the items on the
command line and process each one with case. The case will detect each
possible option and process it accordingly.

Now the tricky part. How does that loop work? It relies on the magic
of shift.

shift is a shell builtin that operates on the positional parameters. Each


time we invoke shift, it "shifts" all the positional parameters down by
one. $2 becomes $1, $3 becomes $2, $4 becomes $3, and so on. Try this:

#!/bin/bash

echo "You start with $# positional parameters"

# Loop until all parameters are used up


while [ "$1" != "" ]; do
echo "Parameter 1 equals $1"
echo "You now have $# positional parameters"
Padmaja.k, Asst Prof, Dept of Page 61
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

# Shift all the parameters down by one


shift

done
Getting an Option's Argument
Our "-f" option requires a valid file name as an argument. We
use shift again to get the next item from the command line and assign it
to filename. Later we will have to check the content of filename to make
sure it is valid.

Integrating the Command Line Processor into the


Script
We will have to move a few things around and add a usage function to get
this new routine integrated into our script. We'll also add some test code to
verify that the command line processor is working correctly. Our script now
looks like this:

#!/bin/bash

# sysinfo_page - A script to produce a system information HTML


file

##### Constants

TITLE="System Information for $HOSTNAME"


RIGHT_NOW="$(date +"%x %r %Z")"
TIME_STAMP="Updated on $RIGHT_NOW by $USER"

##### Functions

system_info()
{
echo "<h2>System release info</h2>"
echo "<p>Function not yet implemented</p>"

} # end of system_info

Padmaja.k, Asst Prof, Dept of Page 62


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

show_uptime()
{
echo "<h2>System uptime</h2>"
echo "<pre>"
uptime
echo "</pre>"

} # end of show_uptime

drive_space()
{
echo "<h2>Filesystem space</h2>"
echo "<pre>"
df
echo "</pre>"

} # end of drive_space

home_space()
{
# Only the superuser can get this information

if [ "$(id -u)" = "0" ]; then


echo "<h2>Home directory space by user</h2>"
echo "<pre>"
echo "Bytes Directory"
du -s /home/* | sort -nr
echo "</pre>"
fi

} # end of home_space

write_page()
{
cat <<- _EOF_
<html>
<head>
<title>$TITLE</title>
Padmaja.k, Asst Prof, Dept of Page 63
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

</head>
<body>
<h1>$TITLE</h1>
<p>$TIME_STAMP</p>
$(system_info)
$(show_uptime)
$(drive_space)
$(home_space)
</body>
</html>
_EOF_

usage()
{
echo "usage: sysinfo_page [[[-f file ] [-i]] | [-h]]"
}

##### Main

interactive=
filename=~/sysinfo_page.html

while [ "$1" != "" ]; do


case $1 in
-f | --file ) shift
filename=$1
;;
-i | --interactive ) interactive=1
;;
-h | --help ) usage
exit
;;
* ) usage
exit 1
esac
shift
done

Padmaja.k, Asst Prof, Dept of Page 64


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

# Test code to verify command line processing

if [ "$interactive" = "1" ]; then


echo "interactive is on"
else
echo "interactive is off"
fi
echo "output file = $filename"

# Write page (comment out until testing is complete)

# write_page > $filename


Adding Interactive Mode
The interactive mode is implemented with the following code:

if [ "$interactive" = "1" ]; then

response=

read -p "Enter name of output file [$filename] > " response


if [ -n "$response" ]; then
filename="$response"
fi

if [ -f $filename ]; then
echo -n "Output file exists. Overwrite? (y/n) > "
read response
if [ "$response" != "y" ]; then
echo "Exiting program."
exit 1
fi
fi
fi

First, we check if the interactive mode is on, otherwise we don't have


anything to do. Next, we ask the user for the file name. Notice the way the
prompt is worded:

"Enter name of output file [$filename] > "

Padmaja.k, Asst Prof, Dept of Page 65


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

We display the current value of filename since, the way this routine is
coded, if the user just presses the enter key, the default value
of filename will be used. This is accomplished in the next two lines where
the value of response is checked. If response is not empty,
then filename is assigned the value of response. Otherwise, filename is
left unchanged, preserving its default value.

After we have the name of the output file, we check if it already exists. If it
does, we prompt the user. If the user response is not "y," we give up and
exit, otherwise we can proceed.

A here document is a special-purpose code block.

COMMAND <<InputComesFromHERE
...
...
...
InputComesFromHERE

A limit string delineates (frames) the command list. The special symbol << precedes the limit
string. This has the effect of redirecting the output of a command block into the stdin of the
program or command. It is similar to interactive-program < command-file, where command-
file contains

command #1
command #2
...

The here document equivalent looks like this:

interactive-program <<LimitString
command #1
command #2
...
LimitString

Choose a limit string sufficiently unusual that it will not occur anywhere in the command list and
confuse matters.

Note that here documents may sometimes be used to good effect with non-interactive utilities and
commands, such as, for example, wall.

Example 19-1. broadcast: Sends message to everyone logged in

Padmaja.k, Asst Prof, Dept of Page 66


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

#!/bin/bash

wall <<zzz23EndOfMessagezzz23
E-mail your noontime orders for pizza to the system administrator.
(Add an extra dollar for anchovy or mushroom topping.)
# Additional message text goes here.
# Note: 'wall' prints comment lines.
zzz23EndOfMessagezzz23

# Could have been done more efficiently by


# wall <message-file
# However, embedding the message template in a script
#+ is a quick-and-dirty one-off solution.

exit

Even such unlikely candidates as the vi text editor lend themselves to here documents.

TRAP COMMAND
When you press the Ctrl+C or Break key at your terminal during execution of a shell program,
normally that program is immediately terminated, and your command prompt returns. This may not
always be desirable. For instance, you may end up leaving a bunch of temporary files that won't get
cleaned up.
Trapping these signals is quite easy, and the trap command has the following syntax −
$ trap commands signals
Here command can be any valid Unix command, or even a user-defined function, and signal can be
a list of any number of signals you want to trap.
There are two common uses for trap in shell scripts −

• Clean up temporary files


• Ignore signals

Cleaning Up Temporary Files


As an example of the trap command, the following shows how you can remove some files and then
exit if someone tries to abort the program from the terminal −
$ trap "rm -f $WORKDIR/work1$$ $WORKDIR/dataout$$; exit" 2
From the point in the shell program that this trap is executed, the two
files work1$$ and dataout$$ will be automatically removed if signal number 2 is received by the
program.
Hence, if the user interrupts the execution of the program after this trap is executed, you can be
assured that these two files will be cleaned up. The exit command that follows the rm is necessary
because without it, the execution would continue in the program at the point that it left off when the
signal was received.
Signal number 1 is generated for hangup. Either someone intentionally hangs up the line or the line
gets accidentally disconnected.

Padmaja.k, Asst Prof, Dept of Page 67


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

You can modify the preceding trap to also remove the two specified files in this case by adding signal
number 1 to the list of signals −
$ trap "rm $WORKDIR/work1$$ $WORKDIR/dataout$$; exit" 1 2
Now these files will be removed if the line gets hung up or if the Ctrl+C key gets pressed.
The commands specified to trap must be enclosed in quotes, if they contain more than one command.
Also note that the shell scans the command line at the time that the trap command gets executed and
also when one of the listed signals is received.
Thus, in the preceding example, the value of WORKDIR and $$ will be substituted at the time that
the trap command is executed. If you wanted this substitution to occur at the time that either signal 1
or 2 was received, you can put the commands inside single quotes −
$ trap 'rm $WORKDIR/work1$$ $WORKDIR/dataout$$; exit' 1 2
Ignoring Signals
If the command listed for trap is null, the specified signal will be ignored when received. For example,
the command −
$ trap '' 2
This specifies that the interrupt signal is to be ignored. You might want to ignore certain signals when
performing an operation that you don't want to be interrupted. You can specify multiple signals to be
ignored as follows −
$ trap '' 1 2 3 15
Note that the first argument must be specified for a signal to be ignored and is not equivalent to writing
the following, which has a separate meaning of its own −
$ trap 2
If you ignore a signal, all subshells also ignore that signal. However, if you specify an action to be
taken on the receipt of a signal, all subshells will still take the default action on receipt of that signal.

Resetting Traps
After you've changed the default action to be taken on receipt of a signal, you can change it back
again with the trap if you simply omit the first argument; so −
$ trap 1 2
This resets the action to be taken on the receipt of signals 1 or 2 back to the default.
test - command
SYNOPSIS
test EXPRESSION
test
[ EXPRESSION ]
[]
[ OPTION

DESCRIPTION
Padmaja.k, Asst Prof, Dept of Page 68
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

Exit with the status determined by EXPRESSION.

Tag Description

--help display this help and exit

--version

output version information and exit

An omitted EXPRESSION defaults to false. Otherwise, EXPRESSION is true or false and sets exit
status. It is one of:

( EXPRESSION )

EXPRESSION is true

! EXPRESSION

EXPRESSION is false

EXPRESSION1 -a EXPRESSION2

both EXPRESSION1 and EXPRESSION2 are true

EXPRESSION1 -o EXPRESSION2

either EXPRESSION1 or EXPRESSION2 is true

-n STRING

the length of STRING is nonzero

STRING equivalent to -n STRING

-z STRING

the length of STRING is zero

STRING1 = STRING2

Padmaja.k, Asst Prof, Dept of Page 69


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

the strings are equal

STRING1 != STRING2

the strings are not equal

INTEGER1 -eq INTEGER2

INTEGER1 is equal to INTEGER2

INTEGER1 -ge INTEGER2

INTEGER1 is greater than or equal to INTEGER2

INTEGER1 -gt INTEGER2

INTEGER1 is greater than INTEGER2

INTEGER1 -le INTEGER2

INTEGER1 is less than or equal to INTEGER2

INTEGER1 -lt INTEGER2

INTEGER1 is less than INTEGER2

INTEGER1 -ne INTEGER2

INTEGER1 is not equal to INTEGER2

FILE1 -ef FILE2

FILE1 and FILE2 have the same device and inode numbers

FILE1 -nt FILE2

FILE1 is newer (modification date) than FILE2

FILE1 -ot FILE2

Padmaja.k, Asst Prof, Dept of Page 70


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

FILE1 is older than FILE2

-b FILE FILE exists and is block special

-c FILE FILE exists and is character special

-d FILE FILE exists and is a directory

-e FILE FILE exists

-f FILE FILE exists and is a regular file

-g FILE FILE exists and is set-group-ID

-G FILE FILE exists and is owned by the effective group ID

-h FILE FILE exists and is a symbolic link (same as -L)

-k FILE FILE exists and has its sticky bit set

-L FILE FILE exists and is a symbolic link (same as -h)

-O FILE FILE exists and is owned by the effective user ID

-p FILE FILE exists and is a named pipe

-r FILE FILE exists and read permission is granted

-s FILE FILE exists and has a size greater than zero

-S FILE FILE exists and is a socket

-t FD file descriptor FD is opened on a terminal

-u FILE FILE exists and its set-user-ID bit is set

-w FILE FILE exists and write permission is granted

-x FILE FILE exists and execute (or search) permission is granted

Except for -h and -L, all FILE-related tests dereference symbolic links. Beware that parentheses need to be
Padmaja.k, Asst Prof, Dept of Page 71
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

escaped (e.g., by backslashes) for shells. INTEGER may also be -l STRING, which evaluates to the length of
STRING.
NOTE: your shell may have its own version of test and/or [, which usually supersedes the version
described here. Please refer to your shell’s documentation for details about the options it supports.

Logical operators for conditional execution.


We will now discuss the following operators −

• Arithmetic Operators
• Relational Operators
• Boolean Operators
• String Operators
• File Test Operators
Bourne shell didn't originally have any mechanism to perform simple arithmetic operations but it uses
external programs, either awk or expr.
The following example shows how to add two numbers −
Live Demo
#!/bin/sh

val=`expr 2 + 2`
echo "Total value : $val"

The above script will generate the following result −


Total value : 4
The following points need to be considered while adding −
• There must be spaces between operators and expressions. For example, 2+2 is not correct; it
should be written as 2 + 2.
• The complete expression should be enclosed between ‘ ‘, called the backtick.

Arithmetic Operators
The following arithmetic operators are supported by Bourne Shell.
Assume variable a holds 10 and variable b holds 20 then −
Show Examples

Operator Description Example

+ (Addition) Adds values on either side of the operator `expr $a + $b` will give 30

- (Subtraction) Subtracts right hand operand from left hand `expr $a - $b` will give -10

Padmaja.k, Asst Prof, Dept of Page 72


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

operand

* (Multiplication) Multiplies values on either side of the operator `expr $a \* $b` will give
200

/ (Division) Divides left hand operand by right hand operand `expr $b / $a` will give 2

% (Modulus) Divides left hand operand by right hand operand `expr $b % $a` will give 0
and returns remainder

= (Assignment) a = $b would assign value


Assigns right operand in left operand
of b into a

== (Equality) Compares two numbers, if both are same then [ $a == $b ] would return
returns true. false.

!= (Not Equality) Compares two numbers, if both are different then [ $a != $b ] would return
returns true. true.

It is very important to understand that all the conditional expressions should be inside square braces
with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is incorrect.
All the arithmetical calculations are done using long integers.

Relational Operators
Bourne Shell supports the following relational operators that are specific to numeric values. These
operators do not work for string values unless their value is numeric.
For example, following operators will work to check a relation between 10 and 20 as well as in
between "10" and "20" but not in between "ten" and "twenty".
Assume variable a holds 10 and variable b holds 20 then −
Show Examples

Operator Description Example

-eq Checks if the value of two operands are equal or not; if yes, [ $a -eq $b ] is not true.
then the condition becomes true.

Padmaja.k, Asst Prof, Dept of Page 73


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

-ne Checks if the value of two operands are equal or not; if values
[ $a -ne $b ] is true.
are not equal, then the condition becomes true.

-gt Checks if the value of left operand is greater than the value of
[ $a -gt $b ] is not true.
right operand; if yes, then the condition becomes true.

-lt Checks if the value of left operand is less than the value of
[ $a -lt $b ] is true.
right operand; if yes, then the condition becomes true.

-ge Checks if the value of left operand is greater than or equal to


the value of right operand; if yes, then the condition becomes [ $a -ge $b ] is not true.
true.

-le Checks if the value of left operand is less than or equal to the
value of right operand; if yes, then the condition becomes [ $a -le $b ] is true.
true.

It is very important to understand that all the conditional expressions should be placed inside square
braces with spaces around them. For example, [ $a <= $b ] is correct whereas, [$a <= $b] is incorrect.

Boolean Operators
The following Boolean operators are supported by the Bourne Shell.
Assume variable a holds 10 and variable b holds 20 then −
Show Examples

Operator Description Example

! This is logical negation. This inverts a true condition


[ ! false ] is true.
into false and vice versa.

-o This is logical OR. If one of the operands is true, [ $a -lt 20 -o $b -gt 100 ] is true.
then the condition becomes true.

-a This is logical AND. If both the operands are true,


[ $a -lt 20 -a $b -gt 100 ] is false.
then the condition becomes true otherwise false.

String Operators
The following string operators are supported by Bourne Shell.

Padmaja.k, Asst Prof, Dept of Page 74


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

Assume variable a holds "abc" and variable b holds "efg" then −


Show Examples

Operator Description Example

= Checks if the value of two operands are equal or not; if yes, [ $a = $b ] is not true.
then the condition becomes true.

!= Checks if the value of two operands are equal or not; if [ $a != $b ] is true.


values are not equal then the condition becomes true.

-z Checks if the given string operand size is zero; if it is zero [ -z $a ] is not true.
length, then it returns true.

-n Checks if the given string operand size is non-zero; if it is [ -n $a ] is not false.


nonzero length, then it returns true.

str Checks if str is not the empty string; if it is empty, then it [ $a ] is not false.
returns false.

File Test Operators


We have a few operators that can be used to test various properties associated with a Unix file.
Assume a variable file holds an existing file name "test" the size of which is 100 bytes and
has read, write and execute permission on −
Show Examples

Operator Description Example

-b file Checks if file is a block special file; if yes, then the condition [ -b $file ] is false.
becomes true.

-c file Checks if file is a character special file; if yes, then the [ -c $file ] is false.
condition becomes true.

-d file Checks if file is a directory; if yes, then the condition [ -d $file ] is not true.
becomes true.

Padmaja.k, Asst Prof, Dept of Page 75


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

-f file Checks if file is an ordinary file as opposed to a directory or [ -f $file ] is true.


special file; if yes, then the condition becomes true.

-g file Checks if file has its set group ID (SGID) bit set; if yes, then [ -g $file ] is false.
the condition becomes true.

-k file Checks if file has its sticky bit set; if yes, then the condition [ -k $file ] is false.
becomes true.

-p file Checks if file is a named pipe; if yes, then the condition [ -p $file ] is false.
becomes true.

-t file Checks if file descriptor is open and associated with a [ -t $file ] is false.
terminal; if yes, then the condition becomes true.

-u file Checks if file has its Set User ID (SUID) bit set; if yes, then [ -u $file ] is false.
the condition becomes true.

-r file Checks if file is readable; if yes, then the condition becomes [ -r $file ] is true.
true.

-w file Checks if file is writable; if yes, then the condition becomes [ -w $file ] is true.
true.

-x file Checks if file is executable; if yes, then the condition [ -x $file ] is true.
becomes true.

-s file Checks if file has size greater than 0; if yes, then condition [ -s $file ] is true.
becomes true.

-e file Checks if file exists; is true even if file is a directory but [ -e $file ] is true.
exists.

Padmaja.k, Asst Prof, Dept of Page 76


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

Exit Status
• Every Linux command executed by the shell script or user, has an exit status.
• The exit status is an integer number.
• The Linux man pages stats the exit statuses of each command.
• 0 exit status means the command was successful without any errors.
• A non-zero (1-255 values) exit status means command was failure.
• You can use special shell variable called $? to get the exit status of the previously executed command. To
print $? variable use the echo command:

echo $?
date # run date command
echo $? # print exit status
foobar123 # not a valid command
echo $? # print exit status

How Do I See Exit Status Of The Command?


Type the following command:

date

To view exist status of date command, enter:

echo $?

Sample Output:

Try non-existence command

date1
echo $?
ls /eeteec
echo $?

Sample Output:

According to ls man page - exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.

How Do I Store Exit Status Of The Command In a Shell Variable?


Assign $? to a shell variable:

ls -l /tmp
status=$?
Padmaja.k, Asst Prof, Dept of Page 77
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

echo "ls command exit stats - $status"

Exit Status Shell Script Example


A simple shell script to locate username (finduser.sh)

#!/bin/bash
# set var
PASSWD_FILE=/etc/passwd

# get user name


read -p "Enter a user name : " username

# try to locate username in in /etc/passwd


grep "^$username" $PASSWD_FILE > /dev/null

# store exit status of grep


# if found grep will return 0 exit stauts
# if not found, grep will return a nonzero exit stauts
status=$?

if test $status -eq 0


then
echo "User '$username' found in $PASSWD_FILE file."
else
echo "User '$username' not found in $PASSWD_FILE file."
fi

Save and close the file. Run it as follows:

chmod +x finduser.sh
./finduser.sh

Sample Outputs:

Enter a user name : vivek


User 'vivek' found in /etc/passwd file.

Run it again:

chmod +x finduser.sh
./finduser.sh

Sample Outputs:

Enter a user name : tommy


User 'tommy' not found in /etc/passwd file.

You can combine the grep and if command in a single statement as follows:

if grep "^$username:" /etc/passwd >/dev/null

Padmaja.k, Asst Prof, Dept of Page 78


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

then
echo "User '$username' found in $PASSWD_FILE file."
else
echo "User '$username' not found in $PASSWD_FILE file."
fi

What is an exit code in the UNIX

An exit code, or sometimes known as a return code, is the code returned to a parent
process by an executable. On POSIX systems the standard exit code is 0 for success
and any number from 1 to 255 for anything else.

Exit codes can be interpreted by machine scripts to adapt in the event of successes of failures. If exit
codes are not set the exit code will be the exit code of the last run command.

How to get the exit code of a command


To get the exit code of a command type echo $? at the command prompt. In the following example a
file is printed to the terminal using the cat command.

cat file.txt
hello world
echo $?
0

The command was successful. The file exists and there are no errors in reading the file or writing it to
the terminal. The exit code is therefore 0.
In the following example the file does not exist.

cat doesnotexist.txt
cat: doesnotexist.txt: No such file or directory
echo $?
1

The exit code is 1 as the operation was not successful.


How to use exit codes in scripts
To use exit codes in scripts an if statement can be used to see if an operation was successful.

#!/bin/bash

cat file.txt

if [ $? -eq 0 ]
then
Padmaja.k, Asst Prof, Dept of Page 79
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

echo "The script ran ok"


exit 0
else
echo "The script failed" >&2
exit 1
fi

If the command was unsuccessful the exit code will be 0 and ‘The script ran ok’ will be printed to the
terminal.
How to set an exit code
To set an exit code in a script use exit 0 where 0 is the number you want to return. In the following
example a shell script exits with a 1. This file is saved as exit.sh.

#!/bin/bash

exit 1

Executing this script shows that the exit code is correctly set.

bash exit.sh
echo $?
1

What exit code should I use?


The Linux Documentation Project has a list of reserved codes that also offers advice on what code to
use for specific scenarios. These are the standard error codes in Linux or UNIX.
o 1 - Catchall for general errors
o 2 - Misuse of shell builtins (according to Bash documentation)
o 126 - Command invoked cannot execute
o 127 - “command not found”
o 128 - Invalid argument to exit
o 128+n - Fatal error signal “n”
o 130 - Script terminated by Control-C
o 255\* - Exit status out of range

How to suppress exit statuses


Sometimes there may be a requirement to suppress an exit status. It may be that a command is being
run within another script and that anything other than a 0 status is undesirable.
In the following example a file is printed to the terminal using cat. This file does not exist so will
cause an exit status of 1.
To suppress the error message any output to standard error is sent to /dev/null using 2>/dev/null.
If the cat command fails an OR operation can be used to provide a fallback - cat file.txt || exit 0.
In this case an exit code of 0 is returned even if there is an error.
Combining both the suppression of error output and the OR operation the following script returns a
status code of 0 with no output even though the file does not exist.
Padmaja.k, Asst Prof, Dept of Page 80
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

#!/bin/bash

cat 'doesnotexist.txt' 2>/dev/null || exit 0

Ordinary and environment variables


An important Unix concept is the environment, which is defined by environment variables. Some are
set by the system, others by you, yet others by the shell, or any program that loads another program.
A variable is a character string to which we assign a value. The value assigned could be a number,
text, filename, device, or any other type of data.
For example, first we set a variable TEST and then we access its value using the echo command −
$TEST="Unix Programming"
$echo $TEST

It produces the following result.


Unix Programming
Note that the environment variables are set without using the $ sign but while accessing them we use
the $ sign as prefix. These variables retain their values until we come out of the shell.
When you log in to the system, the shell undergoes a phase called initialization to set up the
environment. This is usually a two-step process that involves the shell reading the following files −

• /etc/profile
• profile
The process is as follows −
• The shell checks to see whether the file /etc/profile exists.
• If it exists, the shell reads it. Otherwise, this file is skipped. No error message is displayed.
• The shell checks to see whether the file .profile exists in your home directory. Your home
directory is the directory that you start out in after you log in.
• If it exists, the shell reads it; otherwise, the shell skips it. No error message is displayed.
As soon as both of these files have been read, the shell displays a prompt −
$
This is the prompt where you can enter commands in order to have them executed.
Note − The shell initialization process detailed here applies to all Bourne type shells, but some
additional files are used by bash and ksh.

The .profile File


The file /etc/profile is maintained by the system administrator of your Unix machine and contains
shell initialization information required by all users on a system.
The file .profile is under your control. You can add as much shell customization information as you
want to this file. The minimum set of information that you need to configure includes −
Padmaja.k, Asst Prof, Dept of Page 81
CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

• The type of terminal you are using.


• A list of directories in which to locate the commands.
• A list of variables affecting the look and feel of your terminal.
You can check your .profile available in your home directory. Open it using the vi editor and check
all the variables set for your environment.

Setting the Terminal Type


Usually, the type of terminal you are using is automatically configured by either
the login or getty programs. Sometimes, the auto configuration process guesses your terminal
incorrectly.
If your terminal is set incorrectly, the output of the commands might look strange, or you might not be
able to interact with the shell properly.
To make sure that this is not the case, most users set their terminal to the lowest common
denominator in the following way −
$TERM=vt100
$
Setting the PATH
When you type any command on the command prompt, the shell has to locate the command before
it can be executed.
The PATH variable specifies the locations in which the shell should look for commands. Usually the
Path variable is set as follows −
$PATH=/bin:/usr/bin
$
Here, each of the individual entries separated by the colon character (:) are directories. If you request
the shell to execute a command and it cannot find it in any of the directories given in the PATH
variable, a message similar to the following appears −
$hello
hello: not found
$
There are variables like PS1 and PS2 which are discussed in the next section.

PS1 and PS2 Variables


The characters that the shell displays as your command prompt are stored in the variable PS1. You
can change this variable to be anything you want. As soon as you change it, it'll be used by the shell
from that point on.
For example, if you issued the command −
$PS1='=>'
=>
=>
=>

Padmaja.k, Asst Prof, Dept of Page 82


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

Your prompt will become =>. To set the value of PS1 so that it shows the working directory, issue the
command −
=>PS1="[\u@\h \w]\$"
[root@ip-72-167-112-17 /var/www/tutorialspoint/unix]$
[root@ip-72-167-112-17 /var/www/tutorialspoint/unix]$
The result of this command is that the prompt displays the user's username, the machine's name
(hostname), and the working directory.
There are quite a few escape sequences that can be used as value arguments for PS1; try to limit
yourself to the most critical so that the prompt does not overwhelm you with information.

Sr.No. Escape Sequence & Description

1
\t
Current time, expressed as HH:MM:SS

2
\d
Current date, expressed as Weekday Month Date

3
\n
Newline

4
\s
Current shell environment

5
\W
Working directory

6
\w
Full path of the working directory

7
\u
Current user’s username

8
\h

Padmaja.k, Asst Prof, Dept of Page 83


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

Hostname of the current machine

9
\#
Command number of the current command. Increases when a new command is
entered

10
\$
If the effective UID is 0 (that is, if you are logged in as root), end the prompt with
the # character; otherwise, use the $ sign

You can make the change yourself every time you log in, or you can have the change made
automatically in PS1 by adding it to your .profile file.
When you issue a command that is incomplete, the shell will display a secondary prompt and wait for
you to complete the command and hit Enter again.
The default secondary prompt is > (the greater than sign), but can be changed by re-defining
the PS2 shell variable −
Following is the example which uses the default secondary prompt −
$ echo "this is a
> test"
this is a
test
$

The example given below re-defines PS2 with a customized prompt −


$ PS2="secondary prompt->"
$ echo "this is a
secondary prompt->test"
this is a
test
$
Environment Variables
Following is the partial list of important environment variables. These variables are set and accessed
as mentioned below −

Sr.No. Variable & Description

1
DISPLAY
Contains the identifier for the display that X11 programs should use by default.

Padmaja.k, Asst Prof, Dept of Page 84


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

2
HOME
Indicates the home directory of the current user: the default argument for the
cd built-in command.

3
IFS
Indicates the Internal Field Separator that is used by the parser for word splitting
after expansion.

4
LANG
LANG expands to the default system locale; LC_ALL can be used to override this.
For example, if its value is pt_BR, then the language is set to (Brazilian)
Portuguese and the locale to Brazil.

5
LD_LIBRARY_PATH
A Unix system with a dynamic linker, contains a colonseparated list of directories
that the dynamic linker should search for shared objects when building a process
image after exec, before searching in any other directories.

6
PATH
Indicates the search path for commands. It is a colon-separated list of directories
in which the shell looks for commands.

7
PWD
Indicates the current working directory as set by the cd command.

8
RANDOM
Generates a random integer between 0 and 32,767 each time it is referenced.

9
SHLVL
Increments by one each time an instance of bash is started. This variable is useful
for determining whether the built-in exit command ends the current session.

10
TERM
Refers to the display type.

Padmaja.k, Asst Prof, Dept of Page 85


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

11
TZ
Refers to Time zone. It can take values like GMT, AST, etc.

12
UID
Expands to the numeric user ID of the current user, initialized at the shell startup.

Following is the sample example showing few environment variables −


$ echo $HOME
/root
]$ echo $DISPLAY

$ echo $TERM
xterm
$ echo $PATH
/usr/local/bin:/bin:/usr/bin:/home/amrood/bin:/usr/local/bin
$

Make variable readonly

readonly var
readonly var=value
readonly p=/tmp/toi.txt
# error
p=/tmp/newvale

Make function readonly


• You need to use the -f option to make corresponding function readonly and syntax is:

readonly -f functionName

• For example, write a function called hello() at a shell prompt, enter:

function hello() { echo "Hello world"; }


# invoke it
hello

• Make it readonly:

readonly -f hello
# invoke it
hello

Padmaja.k, Asst Prof, Dept of Page 86


CSE, Mycem,Mysore
UNIX AND SHELL PROGRAMMING

• Now, try to update the hello(), enter:

function hello() { echo "Hello $1, let us be friends."; }

Sample outputs:

bash: hello: readonly function

Display all readonly variables


If no arguments are given, or if -p is given to the readonly buitin, a list of all readonly names is printed on screen:

readonly

OR

readonly -p

Sample outputs:

readonly
declare -ar BASH_VERSINFO='([0]="3" [1]="2" [2]="39" [3]="1" [4]="release" [5]="i486-
pc-linux-gnu")'
declare -ir EUID="1000"
declare -ir PPID="7628"
declare -r SHELLOPTS="braceexpand:emacs:hashall:histexpand:history:interactive-
comments:monitor"
declare -ir UID="1000"
declare -r pwdfile="/etc/passwd"

Display all readonly functions


Type the following command:

readonly -f

Sample outputs:

hello ()
{
echo "Hello world"
}
declare -fr hello

Padmaja.k, Asst Prof, Dept of Page 87


CSE, Mycem,Mysore

You might also like