0% found this document useful (0 votes)
11 views106 pages

Shells

Uploaded by

Himani Verma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views106 pages

Shells

Uploaded by

Himani Verma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 106

UNIX Shells

Lecturer: Prof. Andrzej (AJ) Bieszczad


Email: [email protected]
Phone: 818-677-4954

“UNIX for Programmers and Users”


Third Edition, Prentice-Hall, GRAHAM GLASS, KING ABLES

Slides partially adapted from Kumoh National University of Technology (Korea) and NYU
UNIX Shells

• A shell is a program that sits between you and the raw UNIX
operating system.

There are four shells that are commonly supported by UNIX vendors:
the Bourne shell(sh), the Korn shell(ksh), the C shell(csh) and Bourne
Again Shell (bash).

In the next segment, we will study Bash (Bourne Again Shell) that is
compatible with Bourne shell and borrows best features from the
other shells. Bash is becoming the most popular shell - it is the
default shell in Linux.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 2


UNIX Shells

We will introduce the following utilities and commands:

• Utilities

chsh kill ps
echo nohup sleep

• Shell Commands

echo kill umask


eval login wait
exec shift exit tee

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 3


UNIX Shells
RODUCTION

shell is a program that is an interface between a user and


he raw operating system.

makes basic facilities such as multitasking and piping easy


o use, and it adds useful file-specific features such as wild
and I/O redirection.

ere are four common shells in use:

· the Bourne shell


· the Korn shell
· the C shell
· the Bash shell (Bourne Again Shell)

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 4


UNIX Shells
ELL FUNCTIONALITY

This chapter describes the common core of functionality that


all four shells provide.

Here is a diagram that illustrates the relationship among t


four shells:

Korn shell Bourne Again Shell


C shell
Bourne shell
Common Common
core core

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 5


UNIX Shells
ELL FUNCTIONALITY

A hierarchy diagram is a useful way to illustrate the featur


shared by the four shells

Shell functions

Built-in Scripts Variables Redirection Wildcards Pipes Sequence Subshells Background Command
Commands Processing subsitution

Local Environment Conditional Unconditional

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 6


UNIX Shells
ELECTING A SHELL

hen you are provided with a UNIX account,


the system administrator chooses a shell for yo

o find out which shell was chosen for you, look at your prom

f you have a $ prompt, you’re probably in a Bash, Bourne or


Korn shell.

f you have a % prompt, you’re probably in a C shell.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 7


UNIX Shells
Utility : chsh

- chsh allows you to change your default login shell.


It prompts you for the full pathname of the new shell,
which is then used as your shell for subsequent logins.

- In order to use chsh, you must know the full pathnames of


the three shells. Here they are:

Shell Full pathname


Bourne /bin/sh
Bash /bin/bash
Korn /bin/ksh
C /bin/csh

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 8


UNIX Shells
ECTING A SHELL

the following example, we change the default login shell fro


Bourne shell to a Bash shell:

hsh ---> change the login shell from sh to bas


nging login shell for glass
shell : /bin/sh ---> pathname of old shell is displaye
shell: /bin/bash ---> enter full pathname of new shell.
D ---> terminate login shell.
in : glass ---> log back in again.
sword : ---> secret.
---> this time we are in a bash s

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 9


UNIX Shells
LECTING A SHELL

nother way to find out the full pathname of your login shell
to type the following:

echo $SHELL ---> display the name of current login shell.


bin/bash ---> full pathname of the Korn shell.
-

This example illustrated the echo shell command and a shell


variable called SHELL.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 10


UNIX Shells
ELL OPERATIONS

a shell is invoked, either automatically during a login or


ually from a keyboard or script, it follows a preset sequenc

It reads a special startup file, typically located in the us


home directory, that contains some initialization informat
Each shell’s startup sequence is different,
so we’ll leave the specific details for later.

It displays a prompt and waits for a user command.

If the user enters a Control-D character on a line of its ow


this command is interpreted by the shell as meaning “end o
input”, and it causes the shell to terminate;

otherwise, the shell executes the user’s command and


returns to step 2.
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 11
UNIX Shells
HELL OPERATIONS

ommands range from simple utility invocations like:

ls

complex-looking pipeline sequences like:

ps -ef | sort | ul -tdumb | lp

a command with a backslash(\) character, and the shell will


allow you to continue the command on the next line:

echo this is a very long shell command and needs to \


be extended with the line-continuation character. Note \
that a single command may be extended for several lines.
_

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 12


UNIX Shells
ECUTABLE FILES VERSUS BUILT-IN COMMANDS

ost UNIX commands invoke utility programs that are stored


in the directory hierarchy.

tilities are stored in files that have execute permission.

or example, when you type

ls

he shell locates the executable program called “ls”, which is


typically found in the “/bin” directory, and executes it.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 13


UNIX Shells
Displaying Information : echo

The built-in echo command displays its arguments to standard


output and works like this:

Shell Command: echo {arg}*

echo is a built-in shell command that displays all of its


arguments to standard output.
By default, it appends a new line to the output.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 14


UNIX Shells
Changing Directories : cd

The built-in cd command changes the current working director


of the shell to a new location.

METACHARACTERS

Some characters are processed specially by a shell and


are known as metacharacters.

All four shells share a core set of common metacharacters,


whose meanings are as follow:

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 15


UNIX Shells
TACHARACTERS

mbol Meaning

Output redirection; writes standard output to a f


Output redirection; appends standard output to a f
Input redirection; reads standard input from a fi
File-substitution wildcard;
matches zero or more characters.
File-substitution wildcard;
matches any single character.
File-substitution wildcard;
matches any character between the brackets.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 16


UNIX Shells

ymbol Meaning

mand` Command substitution; replaced by the output from


command.
Pipe symbol; sends the output of one process to the
input of another.
Used to sequence commands.
| Conditional execution;
executes a command if the previous one fails.
& Conditional execution;
executes a command if the previous one succeeds.
…) Groups commands.
Runs a command in the background.
All characters that follow up to a new line are ignored
by the shell and program(i.e., used for a comment)
Expands the value of a variable.
Prevents special interpretation of the next character.
<tok Input redirection; reads standard input from script up to tok.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 17


UNIX Shells
hen you enter a command,
the shell scans it for metacharacters and processes them specially

When all metacharacters have been processed,


the command is finally executed.

To turn off the special meaning of a metacharacter,


precede it by a backslash(\) character.

Here’s an example:

$ echo hi > file ---> store output of echo in “file”.


$ cat file ---> look at the contents of “file”.
hi
$ echo hi \> file ---> inhibit > metacharacter.
$ cat file ---> look at the file again.
hi > file ---> > is treated like other characters.
$ _

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 18


UNIX Shells
• Redirection

The shell redirection facility allows you to:

1) store the output of a process to a file ( output redirec


2) use the contents of a file as input to a process ( input

Output redirection

To redirect output, use either the “>” or “>>” metacharacters

The sequence

$ command > fileName

sends the standard output of command to the file with name fi

The shell creates the file with name fileName if it doesn’t a


or overwrites its previous contents if it does already exist.
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 19
UNIX Shells
f the file already exists but doesn’t have write permission,
an error occurs.

n the next example, we create a file called “alice.txt” by redirecti


he output of the cat utility.

ithout parameters, cat simply copies its standard input --- which,
in this case, is from the keyboard --- to its standard output.

cat > alice.txt ---> creates a text file.


n my dreams that fill the night,
see your eyes,
D ---> end of input.
cat alice.txt
n my dreams that fill the night, ---> look at its contents.
see your eyes,
_

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 20


UNIX Shells
he sequence
$ command >> fileName
pends the standard output of command to the file with name fileName.

e shell creates the file with name fileName if it doesn’t already ex


the following example, we appended some text to the existing ‘alice
ile:

cat >> alice.txt ---> append to the file.


d I fall into them,
ke Alice fell into Wonderland.
---> end of input.
cat alice.txt ---> look at the new contents.
my dreams that fill the night,
see your eyes,
d I fall into them,
ke Alice fell into Wonderland.
_

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 21


UNIX Shells
y default, both forms of output redirection leave the standard error
channel connected to the terminal.

owever, all shells have variations of output redirection that allow


redirect the standard error channel.

he Bash, C and Korn shells also provide protection against accidenta


overwriting of a file due to output redirection.

Bash:

et -o noclobber
cho text > test
cho text > test
h: test: cannot overwrite existing file
ho text >| test

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 22


UNIX Shells
put Redirection

put redirection is useful because it allows you to prepare a proces


nput beforehand and store it in a file for later use.

redirect input, use either the ‘<‘ or ‘<<‘ metacharacters.

e sequence

$ command < fileName

ecutes command using the contents of the file fileName


as its standard input.

the file doesn’t exist or doesn’t have read permission,an error oc

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 23


UNIX Shells
In the follow example,
we send the contents of “alice.txt” via the mail utility:

$ mail glass < alice.txt ---> send myself mail.


$ mail ---> look at my mail.
Mail version SMI 4.0 Sat Oct 13 20:32:29 PDT 1990 Type ? for help.
>N 1 [email protected] Mon Feb 2 13:29 17/550
& 1 ---> read message #1.
From: Graham Glass <[email protected]>
To: [email protected]
In my dreams that fill the night,
I see your eyes,
And I fall into them,
Like Alice fell into Wonderland
& q ---> quit mail.
$ _

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 24


UNIX Shells
hen the shell encounters a sequence of the form

$ command << word

t copies its standard input up to, but not including,


line starting with word into a buffer and then executes command
ng the contents of the buffer as its standard input.

hat allows shell programs( scripts ) to supply the standard input to


her commands as in-line text,

t << eof
e1
e2
e3
f
1
2
3

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 25


UNIX Shells
LENAME SUBSTITUTION( WILDCARDS )

l shells support a wildcard facility that allows you to select files


that satisfy a particular name pattern from the file system.

e wildcards and their meanings are as follows:

Wildcard Meaning

* Matches any string, including the empty string.

? Matches any single character.

[..] Matches any one of the characters between the brac


A range of characters may be specified by separat
a pair of characters by a hyphen.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 26


UNIX Shells
event the shell from processing the wildcards in a string
surrounding the string with single quotes(apostrophes) or double
otes.

backslash(/) character in a filename must be matched explicitly.

re are some examples of wildcards in action:

-FR ---> recursively list the current directory.


b.c cc.c dir1/ dir2/

:
e.e

:
g.c
*.c ---> list any text ending in “.c”.
b.c cc.c
?.c ---> list text for which one character is followed by “.c”
b.c
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 27
UNIX Shells

c]* ---> list any string beginning with “a” or “c”.


cc.c

-Za-z]* ---> list any string beginning with a letter.


b.c cc.c

r*/*.c ---> list all files ending in “.c” files in “dir*”


---> directories ( that is, in any directories begin
with “dir” ).
c dir2/g.c
*.c ---> list all files ending in “.c” in any subdirectory.
c dir2/g.c

/?.? ?.? ---> list all files with extensions in “2*” directories
and current directory.
b.c dir2/f.d dir2/g.c

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 28


UNIX Shells
PIPES

Shells allow you to use the standard output of one process


as the standard input of another process by connecting the proces
together using the pipe(|) metacharacter.

The sequence

$ command1 | command2

causes the standard output of command1 to “flow through” to


the standard input of command2.

Any number of commands may be connected by pipes.

A sequence of commands changed together in this way


is called a pipeline.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 29


UNIX Shells

ipelines support one of the basic UNIX philosophies, which is that


large problems can often be solved by a chain of smaller processes,
each performed by a relatively small, reusable utility.

he standard error channel is not piped through a standard pipeline,


although some shells support this capability.

n the next example, we pipe the output of the ls utility to the inp
of the wc utility in order to count the number of files in the curr
directory.

ls ---> list the current directory.


.c b.c cc.c dir1 dir2
ls | wc -w
5
_

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 30


UNIX Shells

head -4 /etc/passwd ---> look at the password file.


oot:eJ2S10rVe8mCg:0:1:Operator:/:/bin/csh
obody:*:65534:65534::/:
aemon:*:1:1::/:
ys:*:2:2::/:/bin/csh
cat /etc/passwd | awk -F: ‘{ print $1 }’ | sort
udit
in
aemon
lass
ngres
ews
obody
ync
ys
im
ucp
_

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 31


UNIX Shells
s an illustration of the pipeline that we just used:

ls Pipe awk Pipe sort Termin

he example, we pipe the contents of the “/etc/passwd” file


to the awk utility to extract the first field of each line.

output of awk is then piped to the sort utility,


hich sorts the lines alphabetically.

result is a sorted list of every user on the system.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 32


UNIX Shells
lity : tee -ia -{fileName}+

e tee utility copies its standard input to the specified files and t
standard output.
e -a option causes the input to be appended to the files rather
than overwriting them.
e -i option causes interrupts to be ignored.

the following example, we copy the output of who to a file called


who.capture” and also let it pass through to sort:

| tee who.capture | sort


ttyp6 May 3 17:54 ( waterloo.com )
ttyp0 May 3 18:49 ( bridge05.utdalla )
ttyp2 May 23 17:44 ( blackfoot.utdall )
ttyp4 May 23 17:44 ( blackfoot.utdall )
who.capture ---> look at the captured data.
ttyp0 May 3 18:49 ( bridge05.utdalla )
ttyp2 Apr 23 17:44 ( blackfoot.utdall )
ttyp4 Apr 23 17:44 ( blackfoot.utdall )
ttyp6 May 3 17:54 ( waterloo.com )

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 33


UNIX Shells
COMMAND SUBSTITUTION

command surrounded by grave accents (‘) - back quote - is executed,


nd its standard output is inserted in the command’s place in the ent
ommand line.

ny new lines in the output are replaced by spaces.

or example:

echo the date today is ‘date`


he date today is Mon Feb 2 00:41:55 CST 1998
_

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 34


UNIX Shells
iping the output of who to the wc utility,
it’s possible to count the number of users on the system:

---> look at the output of who.


ttyp0 Jan 22 15:31 ( blackfoot:0.0 )
ttyp3 Feb 3 00:41 ( bridge05.utdalla )
ttyp5 Jan 10 10:39 ( atlas.utdallas.e )

o there are ‘who | wc -l` users on the system


are 3 users on the system

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 35


UNIX Shells
The result of command substitution may also be used as part of
another command.

For example, vi allows you to specify a list of files to be


edited on the command line, which are then visited by the editor one
after the other.

$ vi ‘grep -l debug *.c`

TE: “grep -l” prints only the name of each input file from which output would
mally have been printed.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 36


UNIX Shells
QUENCES

you enter a series of simple commands or pipelines separated by


micolons, the shell will execute them in sequence, from left to rig

is facility is useful for type-ahead(and think-ahead) addicts who l


specify an entire sequence of actions at once.

re’s an example:

date; pwd; ls ---> execute three commands in sequence.


n Feb 2 00:11:10 CST 1998
ome/glass/wild
c b.c cc.c dir1 dir2
_

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 37


UNIX Shells
Each command in a sequence may be individually I/O redirected as we

$ date > date.txt; ls; pwd > pwd.txt


a.c b.c cc.c date.txt dir1
$ cat date.txt
Mon Feb 2 00:12:16 CST 1998
$ cat pwd.txt ---> look at output of pwd.
/home/glass
$ _

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 38


UNIX Shells
Conditional Sequences

- Every UNIX process terminates with an exit value.


By convention, an exit value of 0 means that the process completed
successfully, and a nonzero exit value indicates failure.

- All built-in shell commands return a value of 1 if they fail.


You may construct sequences that make use of this exit value:

1) If you specify a series of commands separated by “&&” tokens,


the next command is executed only if the previous command return
an exit code of 0.

2) If you specify a series of commands separated by “||” tokens,


the next command is executed only if the previous command return
a nonzero exit code.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 39


UNIX Shells
For example,
if the C compiler cc compiles a program without fatal errors,
it creates an executable program called “a.out” and returns an exi
code of 0;
otherwise, it returns a nonzero exit code.

$ cc myprog.c && ./a.out

The following conditional sequence compiles a program


called “myprog.c” and displays an error message if the compilation
fails:

$ cc myprog.c || echo compilation failed.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 40


UNIX Shells
PING COMMANDS
mands may be grouped by placing them between parentheses,
hich causes them to be executed by a child shell(subshell).

group of commands shares the same standard input,


ndard output, and standard error channels and may be redirected
piped as if it were a simple command.

e are some examples:


e; ls; pwd > out.txt ---> execute a sequence.
eb 2 00:33:12 CST 1998 ---> output from date.
b.c ---> output from ls.
out.txt ---> only pwd was redirected
e/glass
ate; ls; pwd ) > out.txt ---> group and then redirect.
out.txt ---> all output was redirec
Feb 2 00:33:28 CST 1998
b.c
/glass

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 41


UNIX Shells
Background Processing

If you follow a simple command, pipeline, sequence of pipelines,


or group of commands by the “&” metacharacter, a subshell is
created to execute the commands as a background process

The background process runs concurrently with the parent shell and
does not take control of the keyboard.

Background processing is therefore very useful for performing sever


tasks simultaneously, as long as the background tasks do not requir
input from the keyboard.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 42


UNIX Shells
round Processing

. -name a.c -print --->search for “a.c”


.c
e/tmp/a.c
. -name b.c -print &--->search in the background.
--->process ID number.
--->run “date” in the foreground.
.c --->output from background “find”.
2 18:10:42 CST 1998 --->output from date.
rse/tmp/b.c --->more output from background “find”
--->came after we got the shell p
---> but we don’t get another pro
y specify several background commands on a single line by separating
h command by an ampersand.

pwd & ---> create two background processes.


---> process ID of “date”.
---> process ID of “pwd”.
ass ---> output from “pwd”.
2 18:37:22 CST 1998 ---> output from “date”.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 43


UNIX Shells
• REDIRECTIONAL BACKGROUND PROCESSES

- Redirecting Ouput

To prevent the output from a background process from arriving


at your terminal, redirect its output to a file.

In the following example, we redirect the standard output the find


command to a file called “find.txt”.

As the command was executing, we see it grow using the ls command.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 44


UNIX Shells
RECTIONAL BACKGROUND PROCESSES

recting Ouput

d . -name a.c -print > find.txt &


---> process ID of “find”.
-l find.txt ---> look at “find.txt”.
--r-- 1 glass 0 Feb 3 18:11 find.txt
-l find.txt ---> watch it grow.
--r-- 1 glass 29 Feb 3 18:11 find.txt
find.txt ---> list “find.txt”.
d/a.c
erse/tmp/a.c

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 45


UNIX Shells
REDIRECTIONAL BACKGROUND PROCESSES

Another alternative is to mail the output of the background


process to yourself:

$ find . -name a.c -print | mail glass &


27193
$ cc program.c ---> do other useful work.
$ mail ---> read my mail.
ail version SMI 4.0 Sat Oct 13 20:32:29 PDT 1990 Type ? For help.
N 1 [email protected] Mon Feb 3 18:12 10/346
1
rom: Graham Glass <[email protected]>
o : [email protected]
/wild/a.c ---> the output from “find”.
/reverse/tmp/a.c
q
_

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 46


UNIX Shells
ecting Input

a background process attempts to read from a terminal,


erminal automatically sends it an error signal that causes it
rminate.

e following example, we run the chsh utility in the background.


mediately issues the “Login shell unchanged” message and
nates, never bothering to wait for any input.
h & ---> run “chsh” in backgr

ing NIS login shell for glass on csservr1.


shell : /bin/sh
hell : Login shell unchanged. ---> didn’t wait for the input.

u run the mail utility in the background,


ssues the message “No message!?!”:
l glass &

ssage !?! ---> didn’t wait for keyboard


Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 47
UNIX Shells
SHELL PROGRAMS: SCRIPTS

Any series of shell commands may be stored inside a regular text fil
for later execution.

A file that contains shell commands is called a script.

Before you can run a script, you must give it execute permission by
using the chmod utility.

to run it, you need only to type its name.

Scripts are useful for storing commonly used sequences of commands,


and they range in complexity from simple one-liners to fully blown
programs.

When a script is run, the system determines which shell the script
was written for and then executes the shell using the script as it
standard input.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 48


UNIX Shells
HELL PROGRAMS: SCRIPTS

he system decides which shell the script is written for by examinin


the first line of the script.

ere are the rules that it uses to make this decision:

1) If the first line of the script is just a pound sign(#),


then the script is interpreted by the shell from which you execut
this script as a command.

2) If the first line of the script is of the form #! path name,


then the executable program pathName is used to interpret the scr

3) If neither rule1 nor rule2 applies,


then the script is interpreted by a Bourne shell (sh).
Note: Bash on Linux, MacOS X is positioned as /bin/sh.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 49


UNIX Shells
HELL PROGRAMS: SCRIPTS

ere is an example that illustrates the construction and execution of


two scripts,

one for the Bash shell and the other for the Korn shell.

at > script.sh ---> create the bash script.


/bin/bash
his is a sample bash script.
o -n the date today is # in bash, -n omits new line
e # output today’s date.
---> end of input.
at > script.ksh ---> create the Korn-shell script.
bin/ksh
is is a sample Korn shell script.
o “the date today is \c” # in ksh, \c omits the new line
e # output today’s date.
---> end of input
hmod +x script.sh script.ksh ---> make the scripts executable.
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 50
UNIX Shells
L PROGRAMS: SCRIPTS

-lF script.csh script.ksh ---> look at the attributes


---> scripts.
xr-x 1 glass 138 Feb 1 19:46 script.csh*
xr-x 1 glass 142 Feb 1 19:47 script.ksh*
pt.csh ---> execute the C-shell script.
te today is Sun Feb 1 19:50:00 CST 2004
pt.ksh ---> execute the Korn-shell script.
te today is Sun Feb 1 19:50:05 CST 2004

“.sh” and “.ksh” extensions of the scripts are used only for clarity
ripts don’t even require an extension.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 51


UNIX Shells
BSHELLS

en you log into a UNIX system, you execute an initial login


shell.

is initial shell executes any simple commands that you enter

rrent(parent) shell creates a new(child) shell to perform


some tasks:

When a grouped command,


such as ( ls; pwd; date ), is executed, the parent shell cr
a child shell to execute the grouped commands.

If the command in not executed in the background,


the parent shell sleeps until the child shell termina

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 52


UNIX Shells
When a script is executed,
the parent shell creates a child shell to execute the comman
in the script.

If the script is not executed in the background,


the parent shell sleeps until the child shell terminates.

When a background job is executed,


The parent shell creates a child shell to execute the backgr
commands.

The parent shell continues to run concurrently with the chil


shell.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 53


UNIX Shells
hild shell is called a subshell.

ust like any other UNIX process,


a subshell has its own current working directory;

thus cd commands executed in a subshell do not affect


the working directory of the parent shell:

wd ---> display my login shell’s current directo


me/glass
cd /; pwd ) ---> the subshell moves and executes pwd.
---> output comes from the subshell.
wd ---> my login shell never moved.
me/glass

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 54


UNIX Shells
ell contains two data areas:
ironment space and a local-variable space.

shell inherits a copy of its parent’s environment space


clean local-variable space:

rent shell

Child shell
ironment
Environment Copied from pa

Local
Local Clean, in

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 55


UNIX Shells
ARIABLES

shell supports two kinds of variables:


local and environment variables.

oth kinds of variables hold data in a string format.

he child shell gets a copy of its parent shell’s environment


variables, but not its local variables.

nvironment variables are therefore used for transmitting


useful information between parent shells and their children

very shell has a set of predefined environment variables tha


are usually initialized by the startup files.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 56


UNIX Shells
ARIABLES

ere is a list of the predefined environment variables that ar


common to all shells:

Name Meaning

$HOME the full pathname of your home directory

$PATH a list of directories to search for comman

$MAIL the full pathname of your mailbox

$USER your username

$SHELL the full pathname of your login shell

$TERM the type of your terminal


Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 57
UNIX Shells
ARIABLES

he syntax for assigning variables differs between shells,


but the way that you access the variables is the same:

If you precede the name of a variable with a $,


this token sequence is replaced by the shell with the value
the named variable.

To create a variable, simply assign it a value;


variable does not have to be declared.

he syntax for assigning a variable in the Bourne, Bash and K


hells is as follows:

variableName=value ---> place no spaces around the va


or
variableName=“ value ” ---> here, spacing doesn’t matter.
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 58
UNIX Shells
• VARIABLES

- In the following example,


we display the values of some common shell environment
variables:

$ echo HOME = $HOME, PATH=$PATH ---> list two variables.


HOME =/home/glass, PATH=/bin:/usr/bin:/usr/sbin
$ echo MAIL = $MAIL
MAIL=/var/mail/glass
$ echo USER = $USER, SHELL = $SHELL, TERM=$TERM
USER = glass, SHELL = /bin/sh, TERM=vt100
$ _

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 59


UNIX Shells
RIABLES

e next example illustrates the difference between local and


nvironment variables.

n the following, we assign values to two local variables and


hen make one of them an environment variable by using the
ourne shell export command.

ote that the value of the environment variable is copied


nto the child shell, but the value of the local variable is n

inally, we press Control-D to terminate the child shell and


estart the parent shell, and then display the original
ariables:

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 60


UNIX Shells

$ firstname=Graham ---> set a local variable


$ lastname=Glass ---> set another local variable
$ echo $firstname $lastname ---> display their values.
Graham Glass
$ export lastname ---> make “lastname” an
---> environment variable.
$ sh ---> start a child shell; the parent sleeps
$ echo $firstname $lastname ---> display values again
Glass
$ ^D ---> note that firstname was’t copied.
$ echo $firstname $lastname ---> they remain unchanged.
Graham Glass
$ _

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 61


UNIX Shells
veral common built-in variables that have special meanings:

Name Meaning

$$ The process ID of the shell.

$0 The name of the shell script( if applicable

$1..$9 $n refers to the nth command line argument


( if applicable ).

$* A list of all the command-line arguments.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 62


UNIX Shells
he first special variable is especially useful for creating
emporary filenames, and the rest are handy for accessing
ommand-line arguments in shell scripts.

ere’s an example of a script that illustrates all of the com


pecial variables:

cat script.sh ---> list the script.


cho the name of this script is $0
cho the first argument is $1
cho a list of all the arguments is $*
cho this script places the date into a temporary file
cho called $1.$$
ate > $1.$$ # redirect the output of date.
s $1.$$ # list the file.
m $1.$$ # remove the file.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 63


UNIX Shells
script.sh paul ringo george john ---> execute the scrip
e name of this script is script.sh
e first argument is paul
list of all the arguments is paul ringo george john
is script places the date into a temporary file
lled paul.24321
ul.24321
_

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 64


UNIX Shells
QUOTING

There are often times when you want to inhibit the shell’s
wildcard-replacement, variable-substitution, and/or command-
substitution mechanisms.

The shell’s quoting system allows you to do just that.

Here’s the way that it works:

1) Single quotes(‘) inhibit wildcard replacement,


variable substitution, and command substitution.

2) Double quotes(“) inhibit wildcard replacement only.

3) When quotes are nested, it’s only the outer quotes that ha
any effect.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 65


UNIX Shells
QUOTING

The following example illustrates the difference between the


two different kinds of quotes:

$ echo 3 * 4 = 12 ---> remember, * is a wildcard.


3 a.c b b.c c.c 4 = 12
$ echo “3 * 4 = 12” ---> double quotes inhibit wildcards.
3 * 4 = 12
$ echo ‘3 * 4 = 12’ ---> single quotes inhibit wildcards.
3 * 4 = 12
$ name=Graham

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 66


UNIX Shells
By using single quotes(apostrophes) around the text,
we inhibit all wildcarding and variable and command
substitutions:

echo ‘my name is $name - date is `date`’


y name is $name - date is ‘date’
_

By using double quotes around the text, we inhibit wildcardin


but allow variable and command substitutions:

echo “my name is $name - date is `date`”


y name is Graham - date is Mon Feb 2 23:14:56 CST 1998
-

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 67


UNIX Shells
HERE DOCUMENTS

Scripts that use “<<“ are sometimes called here documents.

Here’s an example of a here document.

cat here.sh ---> look at an example of a “here” document.


il $1 << ENDOFTEXT
ar $1,
ease see me regarding some exciting news!
$USER
DOFTEXT
ho mail sent to $1
here.sh glass ---> send mail to myself using the script.
il sent to glass

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 68


UNIX Shells
mail
l version SMI 4.0 Sat Oct 13 20:32:29 PDT 1990 Type ? for
1 [email protected] Mon Feb 2 13:34 12/384
---> read message #1.
m: Graham Glass <[email protected]>
[email protected]

r glass,
ase see me regarding some exciting news!
ass
---> quit out of mail.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 69


UNIX Shells
B CONTROL

nvenient multitasking is one of UNIX’s best features,


o it’s important to be able to obtain a listing of your curre
rocesses and to control their behavior.

here are two utilities and one built-in command that allow
ou to do so:

ps, which generates a list of processes and their attribute


including their names, process ID numbers,
controlling terminals and owner.

kill, which allows you to terminate a process based on its


ID number.

wait, which allows a shell to wait for one of its child proc
to terminate.
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 70
UNIX Shells
rocess Status: ps

he ps utility allows you to monitor the status of processes


orks as follows:

tility : ps -efl

generates a listing of process-status information.

default, the output is limited to processes created by your


rrent shell.

e -e option instructs ps to include all running processes.


e -f option causes ps to generate a full listing.
e -l option generates a long listing.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 71


UNIX Shells
, we use of the sleep utility to delay a simple echo
ement and place the command in the background, then
xecute the ps utility to obtain a list of the shell’s
ciated processes.

h “sh” process is a Bourne-shell process;


of them is the login shell,
the other one is the subshell created to execute
command group.

ep 10; echo done ) & ---> delayed echo in background.


---> the process ID number.

TTY TIME CMD


pts/3 0:00 -sh ---> the long shell.
pts/3 0:00 -sh ---> the subshell.
pts/3 0:00 sleep 10 ---> the sleep.
pts/3 0:00 ps ---> the ps command itself!
---> the output from the background proc

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 72


UNIX Shells
r the record, here’s a description of the sleep utility:

ility : sleep seconds

e sleep utility sleeps for the specified number of seconds


d then terminates.

e meaning of the common column headings of ps output are


follows:

olumn Meaning
the state of the process
D the effective user ID of the process
D the ID of the process
ID the ID of the parent process
the percentage of CPU time that the process used
the last minute

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 73


UNIX Shells

umn Meaning

the priority of the process


the size of the process’ data and stack, in kilob
ME the time the process was created, or the date,
if the process was created before the current
the controlling terminal
E the amount of CPU time used so far(MM:SS)
the name of the command

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 74


UNIX Shells
rocess Status: ps

he S field encodes the stat of the process as follows:

letter Meaning

O running on a processor
R runable
S sleeping
T suspended
Z zombie process

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 75


UNIX Shells
ess Status: ps

’s an example of some user-oriented output from ps:

sleep 10; echo done ) &


2
-f ---> request user-oriented output.
UID PID PPID C STIME TTY TIME C
glass 731 728 0 21:48:46 pts/5 0:01 -
glass 831 830 1 22:27:06 pts/5 0:00 s
glass 830 731 0 22:27:06 pts/5 0:00 -
ne ---> output from previous command

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 76


UNIX Shells
The Bash, Bourne and Korn shells automatically terminate
background processes when you log out,
whereas the C shell allows them to continue.

If you’re using a Bash, Bourne or Korn shell and you want to


make a background process immune to this effect,
use the nohup utility to protect it.

Utility : nohup command

The nohup utility execute command and makes it immune to


the hangup(HUP) and terminate(TERM) signals.

The standard output and error channels of command are


automatically redirected to a file called “nohup.out,” and
the process’ priority value is increased by 5,
thereby reducing its priority.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 77


UNIX Shells
is utility is ideal for ensuring that background processes
re not terminated when your login shell is exited.

you execute a command using nohup, logout, and then log


ck in again, you won’t see the command listed in the output
a regular ps.

include a list of all of the current processes without contr


rminals in a ps output, use the -x option.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 78


UNIX Shells
ere’s an example of this effect:

nohup sleep 10000 & ---> nohup a background process


406
nding output to ‘nohup.out’ ---> message from “nohup”.
ps ---> look at process
D TT STAT TIME COMMAND
399 p3 S 0:00 -sh(sh)
406 p3 S N 0:00 sleep 10000
407 p3 R 0:00 ps
D ---> logout.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 79


UNIX Shells
stem V Release 4.0
lass ---> log back in.
: ---> secret.
---> the background proces
---> listed.

TT STAT TIME COMMAND


3 S 0:00 -sh(sh)
3 R 0:00 ps

x ---> the background process is listed.


TT STAT TIME COMMAND
? IN 0:00 sleep 10000
p3 S 0:00 -sh ( sh )
p3 R 0:00 ps -x

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 80


UNIX Shells
• Signaling Processes:kill

- If you wish to terminate a process before it


completes,
use the kill command.

The Bash, Korn and C shells contain a built-in command


called
kill, whereas the Bourne shell invoke the standard
utility instead.

Both versions of kill supports the following


functionality:

Utility/Shell Command : kill [-signalId] {pid}+


kill -l

kill sends the signal with code signalId to the list


of numbered
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 81
UNIX Shells
y default, kill sends a TERM signal ( number 15 ),
which causes the receiving processes to terminate.

o obtain a list of the legal signal names, use the -l option.

o send a signal to a process,


you must either own it or be a super-user.

rocesses may protect themselves from all signals except for


he KILL signal( number 9 ).

herefore, to ensure a kill, send signal number 9.

he kill utility ( as opposed to the shell built-in


ommands ) allows you to specify 0 as the pid,
hich causes all of the processes associated with the shell
o be terminated.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 82


UNIX Shells
In the following example,
we create a background process and then kill it.

To confirm the termination, we obtain a ps listing:

$ ( sleep 10; echo done ) & ---> create background process


27390 ---> process ID number.
$ kill 27390 ---> kill the process.
$ ps ---> it’s gone!
PID TT STAT TIME COMMAND
27355 p3 S 0:00 -sh(sh)
27394 p3 R 0:00 ps
$ _

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 83


UNIX Shells
use of the -l option and a named signal.

e signal names are listed in numerical order,


arting with signal #1.

ll -l ---> list the signal names.


UP 2) SIGINT 3) SIGQUIT 4) SIGILL
AP 6) SIGABRT 7) SIGEMT 8) SIGFPE
LL 10) SIGBUS 11) SIGSEGV 12) SIGSYS
IPE 14) SIGALRM 15) SIGTERM 16) SIGUSR1
SR2 18) SIGCHLD 19) SIGPWR 20) SIGVTALRM
ROF 22) SIGIO 23) SIGWINCH 24) SIGSTOP
STP 26) SIGCONT 27) SIGTTIN 28) SIGTTOU
RG 30) SIGLOST 32) SIGDIL 33) SIGXCPU
FSZ 35) SIGCANCEL 37) SIGRTMIN 38) SIGRTMIN+1
TMIN+2 40) SIGRTMIN+3 41) SIGRTMAX-3 42) SIGRTMAX-2
TMAX-1 44) SIGRTMAX

leep 10; echo done) &


0 ---> process ID number.
ll -KILL 27490 ---> kill the process with signal #9.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 84


UNIX Shells
ly, here’s an example of the kill utility’s ability to kill
rocesses associated with the current shell:

p 30 & sleep 30 & sleep 30 & ---> create three processes.

0 ---> kill them all.


Terminated
Terminated
Terminated

1 means ALL processes belonging to the user


(ABSOLUTE ALL if used by the super user)

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 85


UNIX Shells
ting For Child Processes: wait

shell may wait for one or more of its child processes


terminate by executing the built-in wait command,
ich works as follows:

ell Command: wait[ pid ]

it causes the shell to suspend until the child process with


e specified process ID number terminates.

no arguments are supplied, the shell waits for all of its c


ocesses.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 86


UNIX Shells
n the following example, the shell waited until both backgro
hild processes had terminated before continuing:

( sleep 30; echo done 1 ) & ---> create a child proce


193
( sleep 30; echo done 2 ) & ---> create a child proce
195
echo done 3; wait; echo done 4 ---> wait for children.
ne 3
ne 1 ---> output from first child.
ne 2 ---> output from second child.
ne 4
_

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 87


UNIX Shells
FINDING A COMMAND: $PATH

When a shell processes a command,


it first checks to see whether it’s a built-in command;

if it is, the shell executes it directly.

echo is an example of a built-in shell command:

$ echo some commands are executed directly by the shell


some commands are executed directly by the shell
$ _

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 88


UNIX Shells
file doesn’t exist or isn’t an executable, an errors occurs

/ls ---> full pathname of the ls u


.csh script.ksh
/nsx ---> a nonexistent filename.
sx: not found
/passwd ---> the name of the password file
asswd: Permission denied ---> it’s not executable.

ADING STANDARD UTILITIES


r bin ---> make my own personal “bin” directory.
in ---> move into the new directory.
> ls ---> create a script called “ls”.
y ls
---> end of input.
d +x ls ---> make it executable.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 89


UNIX Shells
ERLOADING STANDARD UTILITIES

echo $PATH ---> look at the current PATH setting.


in:/usr/bin:/usr/sbin
echo $HOME ---> get pathname of my home directory.
ome/glass
PATH=/home/glass/bin:$PATH ---> update.
ls ---> call “ls”.
ls ---> my own version overrides “/bin/ls”.
_

te that only this shell and its child shells would be affect
the change to PATH; all other shells would be unaffected.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 90


UNIX Shells
ERMINATION AND EXIT CODES

very UNIX process terminates with an exit value.

y convention, an exit value of 0 means that the process


ompleted successful, and a nonzero exit value indicates failu

ll built-in commands return an exit value of 1 if they fail.

n the Bash, Bourne and Korn shells, the special shell variabl
? always contains the value of the previous command’s
xit code.

n the C shell, the $status variable holds the exit code.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 91


UNIX Shells
n the following example, the date utility succeeded, whereas
he cc and awk utilities failed:

$ date ---> date succeeds.


Mon Feb 2 22:13:38 CST 1998
$ echo $? ---> display its exit value.
0 ---> indicates success.
$ cc prog.c ---> compile a nonexistent program.
cpp: Unable to open source file ‘prog.c’.
$ echo $? ---> display its exit value.
1 ---> indicates failure.
$ awk ---> use awk illegally.
awk: Usage: awk [-Fc] [-f source | ‘cmds’] [files]
$ echo $? ---> display its exit value.
1 ---> indicates failure.
$ _

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 92


UNIX Shells
ny script that you write should always explicitly return an e
ode.

o terminate a script, use the built-in exit command,


hich works as follows:

hell Command: exit number

xit terminates the shell and returns the exit value number
to its parent process.

f number is omitted, the exit value of the previous command


s used.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 93


UNIX Shells
f a shell doesn’t include an explicit exit statement,
he exit value of the last command is returned by default.

he script in the following example returned an exit value of

cat script.sh ---> look at the script.


cho this script returns an exit code of 3
xit 3
script.sh ---> execute the script.
his script returns an exit code of 3
echo $? ---> look at the exit value.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 94


UNIX Shells
MMON CORE BUILT-IN COMMANDS

ere are a large number of built-in commands that are


upported by the four shells, of which only a few commands
re common to all three shells.

is section describes the most useful common core built-in


mmands.

hell Command: eval command

he eval shell command executes the output of a command as


regular shell command.
t is useful for processing the output of utilities that gener
hell commands.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 95


UNIX Shells
the following example, we execute the result of the echo
mand, which causes the variable x to be set:

echo x=5 ---> first execute an echo directl


5
eval ‘echo x=5` ---> execute the result of the ech
echo $x

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 96


UNIX Shells
Exec

Shell command: exec command

The exec shell command causes the shell’s image to be replac


with command in the process’ memory space.

If command is successfully executed, the shell that performe


the exec ceases to exist.

If this shell was a login shell, then the login session is


terminated when command terminates.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 97


UNIX Shells
following example, we exec the date command from
in shell, which causes the date utility to run and then the
rocess to terminate:

date ---> replace shell process by date process.


eb 1 18:55:01 CDT 1998 ---> output from date.
_ ---> login shell is terminated
---> and starts a new for the ne

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 98


UNIX Shells
hift

hell Command: shift

he shift shell command causes all of the positional paramete


2…$n to be renamed $1..$(n-1), and $1 to be lost.

t’s particularly handy in shell scripts when cycling through


series of command-line parameters.

f there are no positional arguments left to shift,


n error message is displayed.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 99


UNIX Shells
the following example,
shell script displays its arguments before and after a shift

cat shift.sh ---> list the script.


/bin/sh
ho first argument is $1, all args are $*
ift
ho first argument is $1, all args are $*
shift.sh a b c d ---> run with four arguments.
rst argument is a, all args are a b c d
rst argument is b, all args are b c d
shift.sh a
rst argument is a, all args are a
rst argument is , all args are
shift.sh
rst argument is , all args are
ift: No more words ---> error message.
_

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 100


UNIX Shells
ask
en a C program creates a file, it supplies the file’s origina
rmission settings as an octal parameter to the system
ll open().

r example, to create a file with read and write permission fo


e owner, group, and others, it would execute a system call
ke this:

fd = open( “myFile”, OCREAT | ORDWR, 0666 );

you try creating a file using the “>” character, you’ll prob
d up with a file that has a permission setting of 644 octal:

date > date.txt


ls -l date.txt
w-r--r-- 1 glass 29 May 3 18:56 date.txt
_
Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 101
UNIX Shells
NIX process contains a special quantity called a umask
which is used to restrict the permission settings that
ests when a file is created.

ult umask value of a shell is 022 octal.

bits of a umask value mask out the set bits of


ted permission setting.

revious example, the requested permission 666 was


ith 022 to produce the final permission 644:

r w x r w x r
nal 1 1 0 1 1 0 1 1
0 0 0 0 1 0 0 1 0
1 1 0 1 0 0 1 0

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 102


UNIX Shells
If a file already exists before it is redirected to,
the original file’s permission values are retained and
the umask value is ignored.

Shell Command: umask [octalValue]

The umask shell command sets the shell’s umask value


to the specified octal number or displays the current umask
value if the argument is omitted.

A shell’s umask value is retained until changed.

Child processes inherit their umask values from their


parent shells.

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 103


UNIX Shells
-In the following example, we change the umask value to 0 and
then create a new file to illustrate its effect:

$ umask ---> display current umask value.


22 ---> mask write permission of group/others.
$ umask 0 ---> set umask value to 0.
$ date > date2.txt ---> create a new file.
$ ls -l date2.txt
-rw-rw-rw- 1 glass 29 May 3 18:56 date2.txt
$ _

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 104


UNIX Shells
CHAPTER REVIEW

Checklist
- the common functionality of the three major shells
- the common shell metacharacters
- output and input redirection
- filename substitution
- pipes
- command substitution
- command sequences
- grouped commands
- the construction of scripts
- the difference between local and environment variables
- the two different kinds of quotes
- basic job control
- the mechanism that the shell uses to find commands
- several core built-in commands

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 105


UNIX Shells
QUIZ

1. Can you change your default shell?


2. How can you enter commands that are longer than one line?
3. What is the difference between a built-in command and
a utility?
4. How can you make a script executable?
5. What is the strange term that is sometimes given to filena
substitution?
6. Describe a common use for command substitution.

7. Describe the meaning of the terms parent shell, child shel


and subshell.
8. How do you think the kill command got its name?
9. Describe a way to override a standard utility.
. What is a good umask value and why?

Prof. Andrzej (AJ) Bieszczad Email: [email protected] Phone: 818-677-4954 106

You might also like