Module 2

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

MODULE 2

Chapter -1: File Attributes and Permissions


2.1.1 The ls command with options

The ls command is to obtain a list of all file names in the current directory.

ls with options:

Option Description
-x Multicolumnar Output
-F Marks executables with *, directories with / and symbolic link
with @
-a Shows all filenames beginning with a dot including . and ..
-R Recursive list
-r Sorts filenames in reverse order(ASCII collating sequence by
default)
-l Long listing in ASCII collating sequence seven attributes of a
file.
-d dirname Lists only dirname if dirname is a directory.
-t Sort filenames by last modification time.
-lt Sorts listing by last modification time.
-u Sorts filenames by last access time.
-lu Sorts by ASCII collating sequence but listing shows last access
time.
-lut As above but sorted by last access time.
-i Displays inode number.

ls look up the file‘s inode to fetch its attributes. It lists seven attributes of all files in the current
directory and they:
1. File type & Permission:
The first column shows the type and permissions associated with each file.
The first character in this column is mostly a -, which indicates that file is an
ordinary one.
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.
3. Ownership:
When you create a file, you automatically become its owner. The third column
shows kumar is the owner of all of these files. The owner has full authority to
tamper with a files contents and permissions—a privilege not available with
others except the root user.
4. Group Ownership:
The fourth column represents the group owner of the file. Every user is attached
to a group owner. Every member of that group can access the file depending
on the permission assigned.
5. File size:
File size in bytes is displayed. It is the number of character in the file rather
than the actual size occupied on disk.

6. Last modification time:


Last modification time is the next field. If you change only the permissions or
ownership of the file, the modification time remains unchanged. If at least one
character is added or removed from the file then this field will be updated.
7. File name:
The last column displays the filenames arranged in ASCII collating
sequence.

Example:

$ ls -l
total 72
-rw-r--r-- 1 kumar metal 19514 may 10 13:45 chap01
-rw-r--r-- 2 kumar metal 19555 may 10 15:45 chap02

$ ls -ld // lists only names of directories and not the files.


drwxr-xr-x 2 kumar metal 512 may 09 12:55 helpdir
drwxr-xr-x 3 kumar metal 512 may 09 11:05 progs

2.1.2 Changing File Permissions


• A file or a directory is created with a default set of permissions.
• Using chmod command, we can change the file permissions.
• This command can be used in 2 ways:
1. Relative mode
• This command can be used to add or delete permission for specific type of
user(owner, group or others)
• This command can be used to
• Change only permissions specified in the command line
• Leave the other permissions unchanged.
Syntax:
Chmod category operation permission filename
This command takes 4 arguments:
1) Category can be
u->user(owner)
g->group
o->others
a->all
2) Operation can be
+->assign
- -> remove
= ->absolute
3) Permission can be
r->read
w->write
x->execute
4) Filename whose permission has to be changed
Example:
-rw-r—r-- 1 kumar metal 1906 sep 23:38 xstart
$chmod u+x xstart
-rwxr—r-- 1 kumar metal 1906 sep 23:38 xstart
This command also accepts multiple file names.
Ex: chmode u+x note1 note2 note3

2. Absolute mode
• This command is used to add/delete permission for all type of users(owner,
group or others)
• This command is also used to change all permissions in the command line.
• Syntax:
• Chmod octal_value filename
• This command takes 2 arguments:
1. Octal_value contains 3 octal digits to represent 3 types of users(owner,
group or others)
a. First digit is for the user
b. Second digit is for the group
c. Third digit is for others
• Each digit represents a permission as shown below:
4(100) – read only
2(010) – write only
1(001) – execute only
6(110) – read and write only

2. Filename whose permission has to be changed.

Example: octal value of 644 (110 100 100) means


User can read and write only
Group can read only
Others can read only
• 777 signify all permissions for all categories, but still we can prevent a file from
being deleted.
• 000 signifies absence of all permissions for all categories, but still we can delete
a file.
• It is the directory permissions that determine whether a file can be deleted or not.
• Only owner can change the file permissions. User cannot change
other user‘s file‘s permissions.
• But the system administrator can do anything.

2.1.3 Recursively changing file permissions


• Chmod command is used to change recursively permission of all the files and subdirectories
found in the current directory.
• Example:
Chmod -R a + x c_progs // current directory c_progs
• Here, all files and subdirectories are made executable for all users in current directory
c_progs.

2.1.4 Directory Permissions


The default permission of a directory are: rwxr-xr-x (775)
1) Read directory permission grants the ability to view a file.
2) Write directory permission grants the ability to add, change or remove file from the
directory.
3) Execute directory permission grants the ability to list (ls) the directory content or search for
files in the directory.
Example:
$mkdir c_progs
$ls -ld c_progs
Drwxr-xr-x 2 kumar metal 512 may 9 09:57 c_progs
A directory must never be writable by group and others.
Chapter -2: The Shells Interpretive Cycle
The following activities are typically performed by the shell in its interpretive cycle:
✓ The shell issues the prompt and waits for you to enter a command.
✓ After a command is entered, the shell scans the command line for meta characters
and expands abbreviations (like the * in rm *) to recreate a simplified command line.
✓ It then passes on the command line to the kernel for execution.
✓ The shell waits for the command to complete and normally can’t do
any work while the command is running.
✓ After the command execution is complete, the prompt reappears and the shell
returns to its waiting role to start the next cycle. You are free to enter another
command.

2.1Wild Cards
The meta characters that are used to construct the generalized pattern for matching
filenames belong to a category called wild-cards. The following table lists them:

Wild Card Matches


* Any number of characters including none.
? A single character.
[ijk] A single character – either an i, j or k.
[x-z] A single character that is within the ASCII range of characters x and z.
[!ijk] A single character that is not an i, j or k (Not in C shell).
[!x-z] A single character that is not within the ASCII range of the characters x
and z (Not in C Shell).
{pat1,pat2...} Pat1, pat2, etc. (Not in Bourne shell).

Metacharacters * and ?
To list all files that begin with chap, use, $ls chap*
To list all files whose filenames are six character long and start with chap, use, $ls
chap??
Ex:
$ ls chap? // to list all 5 characters filenames beginning with “chap”
Chapx, chapy, chapz
$ ls chap?? // to list 6 characters filenames beginning with “chap”
Chap01, chap02, chap03
Character class
It comprises of a set of characters enclosed by the rectangular brackets’[‘ and ‘]’.
It matches a single character in the class.
Example:
Character class Match
[ijk] A single character either an I, j ork
[X-Z] A single character that is within the ASCII
range of the characters X and Z
Chap0[124] Chap01, chap02, chap04
[!ijk] A single character that is not n I, j or k
[!X-Z] A single character that is not within the
ASCII range of the characters x and z

This can be combined with any string or another wild-card expression.


Ex:
$ls chap0[124] // matches chap01, chap02, chap04 and lists if found
$ls chap[x-z] //matches chapx, chapy, and chapz and lists if found
Negating the character class(!)
Not operator(!) is used to negate the character class.
Ex:
$ls [!a-zA-Z]* // to match all filenames tht don’t begin with an alphabetical character.

2.2.2Removing the special meanings of wild cards(Escaping and Quoting)


➢Escaping means providing a “\” before the wildcard to remove its special meaning.
➢Example:
➢$ rm chap\* // to remove file named chap*, “\” is used to suppress special meaning of *
➢$ cat chap0\[1-3\] // to list the contents of the filenamed :chap0[1-3]
➢$ echo \\ /// outputs \
➢Quoting means enclosing the wild card within quotes to remove its special meaning.
➢When a command argument is enclosed in quotes, the meanings of all enclosed special characters are
turned off.
➢ Example:
➢ $ rm ‘chap*’, etc…
2.2.3Redirection: Three Standard Files
The shell associates three standard files with the terminal:
1. Two for display and
2. One for keyboard
When a user logs in, the shell makes available three standard files
i)Standard input: The file representing input which is connected to the keyboard. It represents 3 input
sources:
The keyboard, the default source
A file using redirection with the symbol “<” symbol.
Another program using a pipeline.
By default, the shell directs standard input from the keyboard.
Ex: $wc
Hell
World
<ctrl+d> // end of input
2 2 10 //output
The redirect input symbol (<) instructs the shell to redirect a command’s input to come from the specified file
instead of from the keyboard
Ex:
$ cat sample.txt
Hello
World
$ wc < sample.txt
2 2 10 //output

ii)Standard output: The file representing output which is representing the display.
It represents 3 possible destinations:
a) The terminal, the default destination.
b) A file using the redirection symbols > and >>
c) As input to another program using a pipeline
By default, the shell directs standard output from a command to the screen.
Ex:
$cat sample.txt
Hello
World
$ wc sample.txt
2 2 10
The redirect output symbol (>) instructs the shell to redirect the output of a command to the specified file
instead of to a screen.
Ex:
$ wc sample.txt > temp.txt
$ cat temp.txt
2 2 10 // output of wc stored in temp.txt.
“>>” can be used to append to a existing file.
iii)Standard error: The file representing error messages that come from the command or shell. This file is
also connected to the display.
By default, the shell directs standard error from a command to the scree.
Ex: cat empty.txt
Cat: cannot open empty.txt
The redirect output instructs the shell to redirect the error message of a command to the specified file instead
of to the screen.
Ex: cat empty.txt >> errorfile.txt
$ cat errorfile.txt
Cat: cannot open empty text. // error message stored in errorfile.txt

iv)Filters: Using both standard Input and Standard Output


Unix commands are grouped into four categories
a) Directory-oriented commands like mkdir, rmdir and cd and other basic file handling commands like cp,
mv and rm don’t read standard input but they write to standard output.
b) Commands like ls, pwd, who, etc. don’t read standard input but they write to standard output.
c) Commands like lp read standard input but don’t write to standard output.
d) Commands like cat, wc, cmp etc. use both standard input and standard output.
e) Ex:
$ cat calc.txt
(4*2)+2
$ bc < calc.txt > result.txt
10
f) Here, this command performs arithmetic calculations that are specified as expressions in input file
“calc.txt” and redirect the output to a file “result.txt”.
g) Running two or more commands have following disadvantages:
o The process is slow. The second command cant act unless the first has complete its job.
o Requires an intermediate file that has to be removed after the first command has completed its run.
o When handling large files, temporary files can build up early and eat up disk space in no time.

2.2.1 Connecting commands: PIPE


➢ PIPE is another from of redirection.
➢ With piping, the output of the command can be used as input (piped) to a subsequent command.
➢ Syntax:
➢ $ command1 | command 2
➢ Here, output from command 1 is piped into input for command 2.
➢ The symbol ‘|’ denotes a pipe.
➢ Ex:
➢ $ ls -l | lp // pipe is used to send the output of ls to the lp to print a hardcopy of the listing of the
current directory.
➢ Pipeline can be used with two or more commands. User the user should know the behavioral
properties of each commands to place them there.
Ex: $ ls -l | wc-l | lp // to print a count of files in current directory.

2.2.2 Basic and Extended Regular Expressions:


o Like the shell's wild-cards which matches similar filenames with a single expression,
grep uses an expression of a different type to match a group of similar patterns. Unlike
shell's wild-cards, grep uses following set of meta- characters to design an expression
that matches different patterns.
o If an expression uses any of these meta-characters, it is termed as Regular Expression
(RE).

o Regular expression can be classified as

• BRE(Basic Regular Expression)


• ERE(Extended Regular Expression)
• Grep supports BRE by default and ERE with the -E option.
• Character set of BRE is listed below:
Metacharacters/ Match
Character class
* Zero or more occurrences of the previous character.
g* Nothing or g, gg, ggg, gggg, etc.
.(Dot) A single character.
.* Nothing or any number of characters.
[pqr] A single character p, q or r
[c1-c2] A single character within ASCII range shown by c1
and c2
[0-9] A digit between 0 and 9
[^pqr] A single character which is not a p, q or r
[^a-zA-z] A non-alphabetic character
^pat Pattern pat at beginning of line
pat$ Pattern pat at end of line
^bash$ A bash as the only word in line
^$ Lines containing nothing

2.2.2.1 Character class:


• It comprises of characters enclosed by [ and ].
• It matches a single character in the class.
• When we use range, make sure that the character on the left of the hyphen has a lower ASCII
value that that of the one on the right.
• Caret(^) is used to negate the character class.
Ex:
Character class Match
[pqr] A single character p, q or r
[x-z] A single character between characters x
to z.

^[pqr] A sinle character which is not p, q or r

Example:
$ grep -i “[Mm][Hh]” demo_file // matches all the words such as MH mH Mh mh

2.2.2.2 Asterisk(*):
The asterisk(*) refers to the immediately preceding character.
It indicates zero or more occurrences of the previous character.
G* -> nothing or g, gg, ggg, etc.
Lg* -> l or lg, lgg, lggg, etc.
Example:
$ grep “isaa*c” demo_file // matches isac Isaac or isaaac
2.2.2.3 Dot(.):
• A dot matches single character.
• Example:
$ grep “2…” demo_file // matches all 4 character words beginning with 2
• Regular expression “.*” -> signifies any number of characters or none
• Ex:
$ grep prog.c.* demo_file // matches all c and cpp extension filenames

2.2.2.4 Specifying Pattern Location (^ and $):


Following two metacharacters can match a pattern at the beginning or end of a line.
^ Pattern → pattern at beginning of life
Pattern$ → pattern at end of the line.
Anchoring a pattern is often necessary when it can occur in more than one place in a line, and we are
interested in its occurrence only at a particular location.
Example:
Grep “^2” empt.lst // selects line starting with 2
Grep “7..$” emp.lst //selects lines where salary between number number between 7000
to 7999

2.2.3 Extended Regular Expression:


• ERE is used to match dissimilar patterns with a single expression.
• This uses some additional characters as listed below:

Metacharacter/character Match
class
Ch+ One or more occurrences of character ch
Ch? Zero or one occurrence of character ch
Exp1|exp2 Exp1 or exp2
(x1|x2)x3 X1x3 or x2x3

• If current version of grep doesn’t support ERE, then use egrep but without the -E option.
• -E option treats pattern as ERE.
• Example:
$ grep -E “isaa*c” demp_file // matches isac Isaac
$ grep -E ‘vijaykumar | jayakumar’ demo_file //matches multiple patterns
$ grep -E ‘(vijay | jaya) kumar’ demo_file // matches multiple patterns.

2.2.4 grep:
• g/re/p means “globally search for a regular expression and print all lines containing it”.
• This command is used to search a file(s) for lines that have a certain pattern.
• This command scans for the pattern in a file
Syntax:
Grep pattern filename(s)

Example:
Grep “MH” student.lst // display lines containg “MH” from the file student.lst
▪ Patterns with and without quotes is possible.
▪ Quote is mandatory when pattern involves more than one word.
▪ Example:
Grep “My Document” student.lst // display lines containing “My Document” from student.lst.
▪ This command can be used with multiple filenames, where it displays the filenames along with the
output.
▪ Example:
Grep “MH” student.lst vtu.lst rank.lst
2.2.4.1 grep options:
Linux supports below listed options.

Option Significance
-i Ignores case for matching.
-v Doesn't display lines matching expression
-n Displays line numbers along with lines
-c Displays count of number of occurrences
-l Displays list of filenames only.
-e exp Matches multiple patterns
-f Takes patterns from file, one per line
filename
-E Treats patterns as an ERE
-F Matches multiple fixed strings

To understand the working of different options, let us consider we have following information in the file
student.lst

$ cat student.lst
4 | MH | 10 | IS | 111
4 | MH | 11 | CS | 401
4 | GW | 11 | CS | 402
4 | VV | 11 | CS | 403

Ignore case:
-I (ignore) option is used to search all lines containing a pattern regardless ofd uppercase and lowercase
distinction.
Example:
$ grep -I “MH” demo_file // matches all the words such as MH mH Mh mh
4 | MH | 10 | 111

4 | MH | 11 | 401
Deleting Lines:
-v option is used to print all lines that do not contain the specified pattern in a file.
Ex:
Grep -v ‘MH’ student.lst
4 | GW | 11 | CS | 402
4 | VV 11 | CS | 403
Displaying Line Number:
-n(line number is used to display line numbers containing the pattern.
Example:
Grep -n ‘MH’ STUDENT.LST
1
2
Counting Lines Containing the Pattern:
-c(line count) option is used to count number of lines containing the pattern.
Example:
Grep -c ‘MH’ student.lst
2

Displaying filenames:
-l(list filename) option is used to list out the files containing the pattern.
Example:
Grep -l ‘MH’ *.lst
Matching Multiple Pattern:
-e option is used to match multiple pattern in a file.
Example:
Grep -e ‘MH’ -e ‘VV’ student.lst
Taking Pattern from File:
-f option is used to place all matched pattern in a separate file, one pattern per line.
Chapter- 3: Shell Programming
3.1 Introduction
1. A shell is a program that acts as the interface between user & the linux system,
allowing user to enter commands for the operating system to execute. A linux shell is
both a command interpreter and a programming language.
2. Shells may be used interactively or non-interactively, in interactive mode, they
accept input typed from the keyboard. When executing non- interactively, shells
execute commands read from a file.
3. The most commonly used shells are SH(Bourne Shell) CSH(C Shell) and
KSH(Korn Shell). KSH is based on SH & so is BASH(Bourne again shell).
TCSH(Extended C Shell) is based on CSH.

3.2 Ordinary and Environment Variables


Shell variables are of two types:
1. Environment variable 2. Ordinary variable
3.2.1 Environment variables:
• They are used to provide information to the programs you use.
• These variables control the behavior of the system.
• They determine the environment in which the user works.
• If environment variables are not set properly, the users may not be able to use some
• commands.
• Environment variables are called so because they are available in the user’s total
• environment.
• Some variables are set by the system, others by the users and others by the shell
• programs.
• “env” command is used to display environment variables.
a. Example:
$ env
HOME = home/kumar
IFS = ‘’
LOGNAME = Kumar
MAIL = /var/mail/kumar
MAILCHECK = 60
PATH = /bin:/usr/bin
PS1 = ‘$’
PS2 = ‘>’
SHELL = /usr/bin/bash
TERM = tty1
1) HOME
i. It indicates the home variable of the current user.
ii. This variable is set for the user by the system admin in /etc/passwd.
2) IFS
i. This variable contains a string of characters that are used as word separator in the command
line.
ii. It normally consists of the space, tab and newline characters.
3) LOGNAME
i. This variable shows the user name.
4) MAIL
i. This variable specifies the path to user’s mailbox.
5) MAILCHECK
i. This variable determines how often the shell checks for the file for the arrival of new mail.
6) PATH
i. This variable specifies the locations in which the shell should look for commands.
ii. Usually, the path variable is set as follows:
$PATH = /bin:/usr/bin
7) PS1 and PS2
The shell has 2 prompts:
1. The primary prompt ‘$’ is the one the user normally sees on the monitor. It
is stored in PS1.
a. The user can change the primary prompt as follows:
$ PS1 = “c >”
C > // similar to windows

2. The secondary prompt is stored in PS2.

8) SHELL
• It specifies the current shell being used by the users.
• Different types of shells are Bourne shell, C-shell and Korn shell
• This variable is set for the user by the system admin in /etc/passwd.
9) TERM
a. This indicates the terminal type that is used.
b. Every terminal has certain characteristics that are defined in a separate control file in the
terminfo directory.
c. If TERM is not set correctly, vi will not work and display will be faulty.

3.2.2 Ordinary Variables


• A variable is a character string to which the user assigns a value.
• The value can be a number, text,, filename, device or any other type of data.
• Syntax:
Value = variable // variable definition
• The value of the variables are stored in ASCII format.
• In command line, all words that are preceded by a $ are identified and evaluated as
variables.
• The variable can be removed with unset and protected from reassignment by readonly
Where both are shell internal commands.
• The variables exist only for a short time during the execution of a shell script.
• The variables are local to the users shell environment.
• 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.
Uses of Local Variables:
1) Setting pathnames
If a pathname is used several times in a script, we assign it to a variable and use itr as an argument
to any command.
2) Using command substitution
We can assign the result of execution of a command to a variable. The command to be executed
must be enclosed in backquotes.
3) Concatenating variables and strings
Two variables can be concatenated to form a new variable.
Example:
$ base = foo; ext=.c
$ file = $base$ext
$echo $file // prints foo

3.2.3 The . profile


• A profile file is a startup file of an UNIX user.
• This file gets executed as soon as the user logs in.
• 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
i.e; the user can
▪ assign suitable values to the environment variables.
▪ Add and modify statements in the profile file.
• This file can be any one of the two:
▪ 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

3.3 read and readonly commands: Making Scripts Interactive

The read statement is the shell’s internal tool for making scripts interactive (i.e. taking input fromthe
user). It is used with one or more variables.

Inputs supplied with the standard input are read into these variables. For instance, the use of
statement like read name, causes the script to pause at that point to take input from the keyboard.
Whatever is entered by youwill be stored in the variable name.

Example: A shell script that uses read to take a search string and filename from the terminal.

#! /bin/sh

# emp1.sh: Interactive version, uses read to accept two


echo “Enter the pattern to be searched: # No newline

\c”read pname
# use echo –e in
bash
echo “Enter the file to be used:

\c”read fname

echo “Searching for pattern $pname from the file

Running of the above script by specifying the inputs when the script pauses twice:

$ emp1.s
Enter the pattern to be searched :
directorEnter the file to be used:
emp.lst
Searching for pattern director from the file emp.lst

9876 Jai Sharma Director Productions

356 Rohit Director Sales

Selected records shown above.


The readonly command is used to make variables and functions readonly, i.e. you cannot
changethe value of the variables.
Command Line Arguments

Shell scripts also accept arguments from the command line. Therefore, they can be run
noninteractively and be used with redirection and pipelines.
The arguments are assigned to special shell variables. Represented by $1, $2, etc; similar
to Ccommand arguments argv[0], argv[1], etc.
The following table lists the different shell parameters.

Shell parameter
Significance
$1, $2… Positional parameters representing command line arguments

$# No. of arguments specified in command line


$0 Name of the executed command
$* Complete set of positional parameters as a single string
“$ @” Each quoted string treated as separate argument
$? Exit status of last command
$$ Pid of the current shell
$! PID of the last background job.

3.5 Exit and Exit status of a command

To terminate a program exit is used. Nonzero value indicates an error condition.


Example:
$ cat foo
Cat: can’t open foo
Returns nonzero exit status. The shell variable $? Stores this status.
Example 2:
grep director emp.lst >
/dev/null:echo $?0

Exit status is used to devise program logic that braches into different paths depending on
success or failure of a command.
3.6 Logical Operators for Conditional Execution
The shell provides two operators that aloe conditional execution, the && and ||.
Usage:
cmd1 && cmd2
cmd1 || cmd2
&& delimits two commands. cmd 2 executed only when cmd1 succeeds.
Example 1:
$ grep ‘director’ emp.lst && echo “pattern found
Output:

9876 Jai Sharma Director Productions


2356 Rohit Director Sales

Pattern found
Example 2:
$ grep ‘clerk’ emp.lst || echo “Pattern Not Found”
Output: Pattern Not Found
Example 3:
$ grep “$1” $2 || exit2
Echo “Pattern found and job over”
3.6.1 String Comparison:
Test command is also used for testing strings.
Test can be used to compare strings with the following set of comparison operators as listed
below.

Test True if
s1=s2 String s1=s2
s1!=s2 String s1 is not equal to s2
-n stg String stg is not a null string
-z stg String stg is a null string
stg String stg is assigned and not null
s1= =s2 String s1=s2

String test used by test


Example:

#!/bin/sh
#emp1.sh checks user input for null values finally turns emp.sh developed
previously#
if [ $# -eq 0 ] ; then
echo “Enter the string to be searched
:\c”read pname
if [ -z “$pname” ] ; then
echo “You have not entered th e string”; exit
1fi
echo “Enter the filename to be used
:\c”read flname
if [ ! –n “$flname” ] ; then
echo “ You have not entered the flname” ; exit
2fi
emp.sh “$pname”
“$flname”else
emp.sh
$*fi

Output1:
$emp1.sh
Enter the string to be searched :[Enter]
You have not entered the string
Output2:
$emp1.sh
Enter the string to be searched :root
Enter the filename to be searched :/etc/passwd
Root:x:0:1:Super-user:/:/usr/bin/bash
When we run the script with arguments emp1.sh bypasses all the above activities and calls emp.shto
perform all validation checks

$ emp1.sh jai

You didn’t enter two arguments

$ emp1.sh jai emp,lst

9878|jai sharma|director|sales|12/03/56|70000
$emp1.sh “jai sharma” emp.lst You didn’t

enter two arguments

Because $* treats jai and sharma are separate arguments. And $# makes a wrong argument count.
Solution is replace $* with “$@” (with quote” and then run the script.

3.6.2 File Tests:

Test is used to test various file attributes like its type(file, directory or symbolic links)or its
permission( read, write, Execute, SUID, ETC)

Example:

$ ls -l emp.lst

-rw-rw-rw- 1 Kumar group 870 jun 8 15:52 emp.lst

$ [-f emp.lst]; echo $ ---→ ordinary file

$ [-xemp.lst]; echo $? --→ Not an executable

$ [! -w emp.lst] || echo “False that file not writable”

False that file is not writable

Example: filetest.sh

#! /bin/usr

If[! -e $1]: then

Echo “File does not exist”

Elif [! -r S1]; then

Echo “File not readable”

Elif[! -w $ 1]; then

Echo “File not writable”

Else

Echo “File is both readable and writable”


Fi

Output:

$ filetest.sh emp3.lst

File does not exist

$ filetest.sh emp.lst

File is both readable and writable

The following table depicts file-related tests with test:

Test True if

-f file File exists and is a regular file

-r file File exists and readable

-w file File exists and is writable

-x file File exists and is executable

-d file File exists and a directory

-s file File exists and has a size greater than 0

-e file File exists (Korn and Bash shell_

-u file File exists and has SUID bit set

-k file File exists and has sticky bit set

-L file File exists and is a symbolic link(korn and bash only)

F1 -nt f2 File f1 is newer than f2

F1 -ot f2 File f1 is older than f2

F1 -ef f2 File f1 is linked to f2

3.7 The IF condition

The if statement makes two way decisions based on the result of a condition. The following
forms of IF are available in the shell:
if command is If command is If command is
successful then successful then successful then
execute commands execute commands execute
else fi commands elif
execute commands command is
fi successful then
execute commands
else
execute commands
fi
Form 1 Form 2 Form 3

Example:

#!/bin/sh
# shell script to illustrate

If conditional if grep ‘director’ emp.lst


then
echo “Pattern found in file”
else
echo “Pattern not in found”
fi

3.8 While: Looping


To carry out a set of instructions repeatedly, shell offers three features namely, while until and for.
Syntax:
While condition is true
Do
Commands
Done
The commands enclosed by do and done are executed repeatedly as long as condition is true.
Example:

#! /bin/usr
Ans =y
While[“$ans “=” “y”]
Do
Echo “Enter the code and description: \c” > /dev/tty
Read code description
Echo “$code $description” > newlist
Echo “Enter any more [Y/N]”
Read any
Case $any in
Y * | y* ) answer = y;;
N * | n* ) answer = n;;
*) answer = y;;
Esac
done

Input:
Enter the code and description : 03 analgestics
Enter any more [Y/N] :y
Enter the code and description : 04 antibiotics
Enter any more [Y/N] : [Enter]
Enter the code and description : 05 OTC drugs
Enter any more [Y/N] : n

Output:
$ cat newlist
03 | analgestics
04 | antibiotics
05 | OTC Drugs

3.9 for: Looping with a list


for is also a repetitive structure.
Syntax:

For variable in list


Do
Commands
done
List here comprises a series of character strings. Each string is assigned to variable specified.
Example:

For file in ch1 ch2


Do
Cp $file ${file}.bak
Echo $file copied to $file.bak
done

Output:
Ch1 copied to ch1.bak
Ch2 copied to ch2.bak
3.9.1 Sources of list:
List from variables: Series of variables are evaluated by the shell before executing the loop.
Example:
$ for var in $PATH $HOME; do echo “$var”; done
Output:
/bin:/usr?bin;?home?local?bin;
/home/user1
List from command substitution: Command substitution is used for creating a list. This is used when
the list is large.
Example:
$ for var in ‘cat clist’
List from wildcards: Here, the shell interprets the wildcards as filenames.
Example: $ for in *.htm*.html; do
Sed ‘s/strong/STRONG/g
s/img src/ING SRC/’ $file $$
mv $$ file
done.
List form positional parameters:
Example: emp.sh

#! /bin/sh
For pattern in “$@”; do
Grep “$pattern” emp.lst || echo “pattern $pattern not found”
Done
Output:
$emp.sh 9876 “Rohit”
9876 Jai Sharma Director Productions
3.10 The case conditional
The case statement is the second conditional offered by the shell. It doesn’t have a parallel
either inC (Switch is similar) or perl.
The statement matches an expression for more than one alternative, and uses a compact
construct topermit multiway branching.
case also handles string tests, but in a more efficient manner than if.
Syntax:

Case expression in
Pattern 1) commands1 ;;
Pattern 2) commands2 ;;
Pattern 3) commands3 ;;

esac

Case first matches expression with pattern1. if the match succeeds, then it executes
commands1,which may be one or more commands.
If the match fails, then pattern2 is matched and so forth.
Each command list is terminated with a pair of semicolon and the entire construct is closed
withesac (reverse of case).

#! /bin/sh
#
Echo “ Menu\n
1. List of files\n 2. Processes of user\n 3. Today’s date
4. Users of system\n 5. Quit\n Enter your option: \c”
Read choice
Case “$choice” in
1) Ls -l;
2) Ps -f;
3) Date;;
4) Who;;
5) Exit;;
*) echo “Invalid option”
esac

Output:
$ menu.sh
Menu
1. List of files
2. Processes of user
3. Today’s date
4. Users of systemest a user response for both y and Y(or
5. Quit
Enter your option: 3
Mon oct 8 08:02:45 IST 2007
Matching multiple patterns:
Case can also specify the same action for more than one pattern. For instance to test a user response for both
y and Y (or n and N).
Example:
Echo “Do you wish to continue? [y/n]: \c”
Read ans
Case “$ans” in
Y | y);;
N | n) exit ;;
Esac
Wild cards: case uses them:
Case has a string-matching feature that uses wild-cards
It uses the filename matching metacharacters *, ? and character class( to match only strings and not files in
the current directory).
Example:
Case “$ans” in
[Yy] [eE]* );; // matches YES, Yes, yes,yEs, etc…
[Nn] [oO]) exit;; // matches no, NO, No, nO

3.11 Set and Shift:


3.11.1 set

➢ The set statement assigns positional parameters $1, $2 and so on, to its arguments. This is used
forpicking up individual fields from the output of a program.

o Example 1: $ set 9876 2345 6213


➢ This assigns the value 9876 to the positional parameters $1, 2345 to $2 and 6213 to $3. It also
setsthe other parameters $# and $*.
Example 1: $ set ‘date’
$ echo $*
Mon oct 8 08:02:45 IST 2007
Example 2: $echo “The date today is $2 $3, $6”
The date today is oct 8, 2007
3.11.2 Shift: Shifting Arguments Left

➢ Shift transfers the contents of positional parameters to its immediate lower numbered one.
➢ This is done as many times as the statement is called. When called once, $2 becomes $1,
$3becomes S2 and so on.

Example:

$echo “$@” // $@ and $* are interchangeable

Mon oct 8 08:02:45 IST 2007

$echo $1 $2 $3

Mon Oct 8

$ shift

$echo $1 $2 $3

Mon Oct 8 08:02:45

$ shift 2 // shifts 2 places

$echo $1 $2 $3

08:02:45 IST 2007

3.11.3 Set -- : Helps command substitution


Inorder for the set to interpret - and null output produced by UNIX commands the – option is
used .If not used – in the output is treated as an option and set will interpret it wrongly.
In case of null, all variables are displayed instead of null.
Example:
$ set ‘ls -l student.lst’
-rwxr=xr--: bad option
Solution:
$set – ‘ls -l student.lst’
-rwxr-xr—2 kumar froup 163 jul 13 21:36 student.lst
3.12 here( < < ) document
• The shell uses the << symbol to read data from the same file containing the script.
This is referred to as a here document, signifying that the data is here rather than
in aspirate file.
• Any command using standard input can also take input from a here document.
• Syntax:
o Command << delimiter
o Document
o Delimiter
Example:
$ mailx kumar << MARK
Explore
Dream
Discover
MARK
• The string MARK is delimiter.
• 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 data inserted by command.
• The word MARK itself doesn’t show up.

Using here document with interactive programs:


A shell script can be made to work non-interactively by supplying inputs through here document.
For example:
$ wc -l < < END
Decide
Commit
Succeed
END
3 // outputs number of lines = 3
3.13 trap
• Normally, the shell scripts terminate whenever the interrupt key is pressed.
• It is not a good programming practice because a lot of temporary files will be stored on disk.
• The trap statement lets you do the things you want to do when a script receives a signal.
• The trap statement is normally placed at the beginning of the shell script and uses two lists:
• Syntax: trap command_list signal_list
• The signal list contains the signal nam.
• The command list contains the commands to be executed when the signals are received by the
script.
• Two common uses of trap are:
1. Clean up temporary files.
• The user can remove some files and then exit if someone tries to abort the script
from the terminal.
• Example:
$trap ‘rm temp.txt ; exit’ SIGINT
• Here, a file temp.txt will be automatically removed if a signal SIGINT is received
by the script.
2. Ignore 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.

You might also like