Upload
maleem
View
255
Download
0
Embed Size (px)
Citation preview
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 1/113
Unix
Programming with the Shell.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 2/113
Shell Types in Unix
Bourne Shell.
Bourne Again Shell (bash).
C Shell (c-shell).
Korn Shell (k-shell).
TC Shell (tcsh)
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 3/113
The Shell.
A program that interprets user‟s requests to run programs.
Provides environment for user programs.
A command line interpreter that
– Reads user inputs.
– Executes commands.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 4/113
Shell Features.
Interactive and background processing.
Input/output redirection
Pipes.
Wild card matching.
Programmable.
– Shell Variables.
– Programming language constructs.
– Shell Scripts.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 5/113
Korn Shell Features
Job control
Aliases
Functions
Command history
Command-line editing ,
Integrated programming features
The functionality of several external UNIX commands, including test , expr , getopt ,
and echo , has been integrated into the shell itself, enabling common programming
tasks to be done more cleanly and without creating extra processes.
Control structures
Debugging primitives
Regular expressions
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 6/113
Korn Shell Features
Advanced I/O features
New options and variables
Increased speed
Security features
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 7/113
Figure 1.1: The shell is a layer around the UNIX operating system
What is a shell ?
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 8/113
Files
Regular files
Also called text files; these contain readable characters.
Executable files
Also called programs; these are invoked as commands
DirectoriesAlso called folders, contains files & subdirectories
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 9/113
Directories
The working directory
Is the current directory, which is the directory you are "in" at any given
time.
Tilde notation ( ~ )
A tilde refers to home directoryChanging working directories
1) cd directory-name
2) cd -
which changes to whatever directory you were in before the current one.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 10/113
Filenames and WildcardsWildcard Matches
? Any single character
* Any string of characters[set ] Any character in set
[!set ] Any character not in set
A set is a list of characters
Expression Matches
[abc] a, b, or c
[ .,;] Period, comma, or semicolon
[-_] Dash and underscore
[a-c] a, b, or c
[a-z] All lowercase letters
[!0-9] All non-digits
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 11/113
Expression Matches
[a-zA-Z] All lower- and uppercase letters
[a-zA-Z0-9_-] All letters, all digits, underscore, and dash
Filenames and Wildcards
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 12/113
Special Characters and Quoting
Table 1.6: Special Characters
Character Meaning
~ Home directory
# Comment
$ Variable expression
& Background job
* String wildcard
( Start subshell
) End subshell
\ Quote next character
| Pipe
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 13/113
Special Characters and Quoting
Character Meaning
[ Start character-set wildcard
] End character-set wildcard
{ Start code block
} End code block
; Shell command separator‘ Strong quote“ Weak quote
< Input redirect
> Output redirect
/ Pathname directory separator
? Single-character wildcard
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 14/113
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 15/113
Command-line Editing
Enabling Command-line Editing
There are two ways of entering either editing mode
Add following line in .profile file
1)VISUAL=$(whence emacs)
OrVISUAL=$(whence vi)
2)$ set -o emacs
or$ set -o vi
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 16/113
The History File
All of the Korn shell's command history facilities depend on a file that contains
commands as you type them in. This file is normally .sh_history in your home
directory, but you can call it whatever you like by setting the environment
variable HISTFILE
HISTSIZE
can be used to determine the maximum number of commands kept in the
history file. The default is 128 (i.e., the 128 most recent commands),
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 17/113
Vi Editing Mode
Editing Commands in vi Input Mode
Command Description
DEL Delete previous character
[CTRL-W] Erase previous word (i.e., erase until blank)
[CTRL-V] "Quote" the next character
ESC Enter control mode
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 18/113
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 19/113
Entering and Changing Text
Commands for Entering vi Input Mode
Command Description
i Text inserted before current character (insert)
a Text inserted after current character (append)
I Text inserted at beginning of line
A Text inserted at end of line
R Text overwrites existing text
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 20/113
Deletion Commands
Command Description
dh Delete one character backwards
dl Delete one character forwards
db Delete one word backwards
dw Delete one word forwards
dB Delete one non-blank word backwards
dW Delete one non-blank word forwards
d$ Delete to end of line
d0 Delete to beginning of line
U undoes all commands on the current line.
u undoes the last text modification command only
. redoes the last text modification command.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 21/113
Moving Around in the History File
Command Description
k or - Move backward one line
j or + Move forward one line
G Move to line given by repeat count
? string Search backward for string
/string Search forward for string
n Repeat search in same direction as previous
N Repeat search in opposite direction of previous
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 22/113
Character-finding Commands
Command Description
f x Move right to next occurrence of x
F x Move left to previous occurrence of x
t x Move right to next occurrence of x , then back one
spaceT x Move left to previous occurrence of x , then forward one
space
; Redo last character-finding command
, Redo last character-finding command in opposite
direction
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 23/113
The fc Command
fc (fix command) is a shell built-in command
It is used to edit one or more commands with editor, and to run old
commands with changes without having to type the entire command in again
The fc -l is to lists previous commands.
It takes arguments that refer to commands in the history file. Arguments can benumbers or alphanumeric strings
To see only commands 2 through 4, type fc -l 2 4
To see only one command type fc -l 5
To see commands between ls and cal in history ,type fc -l l c
To edit , fc command_no
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 24/113
The fc Command
With no arguments, fc loads the editor with the most recent command.
With a numeric argument, fc loads the editor with the command with that
number.
With a string argument, fc loads the most recent command starting with that
string.With two arguments to fc , the arguments specify the beginning and end of a
range of commands,
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 25/113
Shell Variables.
Positional Parameters.
Special Parameters.
Named variables
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 26/113
Positional Parameters.
Acquire values from the position of arguments in command line.
– $1, $2, $3,..$9
– sh file1 10 20 30
$1 $2 $3
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 27/113
Special Parameters.
Shell assigns the value for this parameter.
– $$ - PID number.
– $# - Number of Command Line Arguments.
– $0 – Command Name.
– $* - Displays all the command line arguments.
– $? – Exit Status.
– $- - Shell options
– $! - Process number of the last background command
– $@ - Same as $*, except when enclosed in double quotes.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 28/113
Named Variables.
User-defined variable that can be assigned a value.
Used extensively in shell-scripts.
Used for reading data, storing and displaying it.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 29/113
Accepting Data.
read.
– Accepts input from the user.
– Syntax : read variable_name.
– Example : read sname
VariableName
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 30/113
Display Data.
echo
– Used to display a message or any data as required by the user.
– echo [Message, Variable]
– Example:
echo “IBM.”
echo $ sname
VariableName
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 31/113
Program Execution.
sh
– Command to execute program in Unix.
– Syntax : sh <Shell Script Name>
– Example : sh file1
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 32/113
test command.
Used extensively for evaluating shell script conditions.
It evaluates the condition on its right and returns a true or false exit status.
The return value is used by the construct for further execution.
In place of writing test explicitly, the user could also use [ ].
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 33/113
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 34/113
test command (Contd).
Operators used with test for evaluating string data are:
str1 = str2 True if both equals
str1 != str2 True if not equals
-n str1 True if str1 is not a null string
-z str1 True if str1 is a null string
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 35/113
test command (Contd).
Operators used with test for evaluating file data are:
-f file1 True if file1 exists and is a regular file.
-d file1 True if file1 exists and is directory.
-s file1 True if file1 exists and has size greater than 0
-r file1 True if file1 exists and is readable.
-w file1 True if file1 exists and is writable.
-x file1 True if file1 exists and is executable.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 36/113
Logical Operators.
Logical Operators used with test are:
! Negates the expression.
-a Binary „and‟ operator.
-o Binary „or‟ operator.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 37/113
Shell Quotes-Meanings.
„ „ (single forward quotes)
– '....' take .... Literally
` ` (single backward quotes)
– `…` to be interpreted by shell
" " (double quotes) – "...." take .... literally after $.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 38/113
expr command.
Used for evaluating shell expressions.
Used for arithmetic and string operations.
– Example : expr 7 + 3
would give an output 10.
When used with variables, back quotes need to be used.
Operator has to be preceded and followed by a space.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 39/113
Conditional Execution.
&&
– The second command is executed only when first is successful.
– command1 && command2
||
– The second command is executed only when the first is unsuccessful.
– command1 || command2
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 40/113
Program Constructs
if
for
while
until
case
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 41/113
if statement.
Syntax.
i f control command
then
<commands>
e l se
<commands>
f i
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 42/113
for statement.
Syntax.
for variable-name in value1 v alue2 ... .
d o
< c o m m a n d s >
d o n e
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 43/113
while statement.
Syntax.
w h i l e c o n t ro l c o m m a n d
d o
< c o m m a n d s >
d o n e
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 44/113
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 45/113
case statement.
Syntax.
case value in
cho ic e1) com mands ; ;
cho ic e2) com mands ; ;
....
....
esac
The symbols ;; are used as option terminators.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 46/113
Useful Shell Scripting commands.
break
– To come out of a loop.
continue
– To jump to the start of loop.
exit – To prematurely terminate a program.
#
– To interpret the rest of line as comments.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 47/113
Trap command.
trap
– To alter the effects of certain events that generate signals, which generally tends to
halt a process.
– Syntax:
trap command signal list
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 48/113
export command.
export
– To make a variable a part of environment and also be accessible to the child shell.
Customizing Your Environment
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 49/113
Customizing Your Environment
The most basic means of customization that the Korn shell provides are
AliasesSynonyms for commands or command strings that you can define for
convenience.
OptionsControls for various aspects of your environment, which you can turn
on and off.
VariablesPlace-holders for information that tell the shell and other programs
how to behave under various circumstances. To customize the
environment various built-in shell variables are available.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 50/113
Customizing Your Environment
>To change the values of variables permanently , define it in .profile file.
The .profile File
This is a file of shell commands, also called a shell script, that the Korn shell
reads and runs whenever you log in to your system.
Various environment variables can be defined in this file
Alias can be defined in .profile file
Aliases
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 51/113
Aliases
Alias is a synonym for a command or command string
Syntax:
alias new =original
Ex:-
alias search=grep
alias cdnew=„cd /xyz/x1/x2‟
>Quotes are necessary if the string being aliased consists of more than one word
>it is possible to alias an alias, aliases are recursive
Ex:-
alias c=cdnew
Aliases
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 52/113
Aliasestype alias without any arguments, to get a list of all the aliases you have defined as well
as several that are built-in.
The command unalias name removes any alias definition for its argument
Tracked Aliases
Tracked alias can shorten the time it takes the shell to invoke commands
After turning ON this option , for all subsequent alias definitions, the shellwill internally substitute the full pathname of each command for which an
alias is defined.Can also define individual tracked aliases with alias -t
command ,
alias -t command =command
To list all tracked aliases , type alias -t .
A tracked alias cuts down the number of steps the shell has to take to find the
command when you want to run it
T k d Ali
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 53/113
Tracked Aliases
Ex:- alias v=vi , where vi executable is in /usr/bin/vim
$ v file1
In this example it replaces v with /usr/bin/vim ,as if u had defined
the alias as:
alias v=/usr/bin/vim
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 54/113
O i
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 55/113
Opt ions
Opt ion Descr ip t ion
n o u n s e t Indicate an error when trying to use a variable that is
undefined
t rackal l Turn on alias tracking[6]
v i Enter vi editing mode
To check the status of an option, type
set -o
t d
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 56/113
set command.
set command
– Used for display all the environment variables.
– Shows the current values of system variables.
– Also allows conversion of arguments into positional parameters.
– Syntax : set
Shell Variables
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 57/113
Shell variables can specify everything from your prompt string to how often the
shell checks for new mailbuilt-in variables have names in all capital letters
The syntax for defining variables is
varname =value
if the value is more than one word, it must be surrounded by
quotes
To delete a variable type the command
unset varname
P i t C d
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 58/113
Print Command
To check value of a variable print built-in command can be used
Print c ommand is strongly recommended over echo because its options are
the same on all UNIX systems, whereas echo 's options differ between BSD-
derived and System V-derived UNIX versions.
Ex:- print “$x”
System Variables or Built-in Variables
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 59/113
yPATH
– Search path referred by Unix for any command.
– echo $PATH
HOME
– Indicates the home directory for the user.
– echo $HOME
HISTFILE
- Name of history file, on which the editing modes operate.
EDITOR
– Pathname of your favorite text editor; the suffix ( macs or v i ) determines which editing
mode to use
VISUAL
– Similar to EDITOR; used if EDITOR is not set or vice versa.
– Pathname of your favorite text editor; the suffix ( macs or vi ) determines which editing mode to
use.
System Variables (Contd)
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 60/113
System Variables (Contd).
FCEDIT
– Pathname of editor to use with the fc command.
PS1
– Used for displaying & changing the primary prompt.
– echo $PS1
PS2
– Used for changing the secondary prompt.
– Name of file to check for incoming mail (i.e., your mail file)
MAILCHECK
– How often, in seconds, to check for new mail (default 600 seconds, or 10 minutes)
MAILPATH
– List of filenames, separated by colons ( :), to check for incoming mail
System Variables (Contd)
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 61/113
System Variables (Contd).
SHELL
– Pathname of the shell you are running
PWD
– Current directory
ENV
– Name of file to run as environment file when shell is invoked
FPATH
– Search path for autoloaded functions.
HISTSIZE
– Number of lines kept in history file
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 62/113
The Environment File
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 63/113
Although environment variables will always be known to subprocesses,
the shell must define which other variables, options, aliases, etc., areto communicated to subprocesses.
The way to do this is to put all such definitions in a special file called
the environment file instead of your .profile .
1. Decide which definitions in your .profile you want to propagate to
subprocesses. Remove them from .profile and put them in a file you
will designate as your environment file.
2. Put a line in your .profile that tells the shell where your environment file
is:
ENV=envfilename
The Environment File
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 64/113
3 . For the changes to take effect, type either . .profile or
login. In either case, your environment file will be run when
the shell encounters the ENV= statement.
Shell Scripts and Functions
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 65/113
A script , or file that contains shell commands, is a shell program
There are two ways to run a script
1 By using . (dot) command
Ex:-
• Scriptname
2 By typing scriptname , if the current directory is part of command search
path . If dot isn‟t in your path then type
. /scriptname
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 66/113
Functions
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 67/113
Functions
to delete a function definition issue command
unset -f functname .
To find out what functions are defined in your login session
functions
Autoloaded functions
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 68/113
function definitions can be placed in your .profile or environment file.
This is fine for a small number of functions .As it increases it takes lot
of logging in time
Korn shell‟s autoload feature is used to overcome this problem
put the command autoload fname in your .profile or environment file,
instead of the function's definition, then the shell won't read in the
definition of fname until it's actually called. autoload can take more
than one argument.
FPATH
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 69/113
FPATH
How does the shell know where to get the definition of an autoloaded function?
It uses the built-in variable FPATH , which is a list of directories like PATH . Theshell looks for a file called fname that contains the definition of function fname
in each of the directories in FPATH .
String Operators
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 70/113
string operators let you do the following:
Ensure that variables exist (i.e., are defined and have non-null values)
Set default values for variables
Catch errors that result from variables not being set
Remove portions of variables' values that match patterns
Syntax of String Operators
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 71/113
Operator Substitution
${varname :-word } If varname exists and isn't null, return its value; otherwise
return word .Purpose Returning a default value if the variable is undefined.
Example : ${count:-0} evaluates to 0 if count is undefined.
${varname :=word} If varname exists and isn't null, return its value; otherwise set it to word
and then return its valuePurpose : Setting a variable to a default value if it is undefined.
Example : ${count:=0} sets count to 0 if it is undefined.
${varname :?message } If varname exists and isn't null, return its value; otherwise print
varname : followed by message , and abort the current command orscript. Omitting message produces the default message parameter null
or not set .
Purpose : Catching errors that result from variables being undefined.
Example : {count :?" undefined! " } prints "count: undefined!" and exits if count
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 72/113
${varname :+word } If varname exists and isn't null, return word ; otherwise
return null.Purpose : Testing for the existence of a variable.
Example : ${count:+1} returns 1 (which could mean "true") if
count is defined.
Pattern-matching Operators
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 73/113
Operator & Meaning
${variable # pattern }
If the pattern matches the beginning of the variable's value, delete the shortest part that
matches and return the rest.
${variable ## pattern }
If the pattern matches the beginning of the variable's value, delete the longest part thatmatches and return the rest.
${variable % pattern }
If the pattern matches the end of the variable's value, delete the shortest part that
matches and return the rest.
${variable %% pattern }
If the pattern matches the end of the variable's value, delete the longest part that
matches and return the rest.
Length Operator
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 74/113
${#varname } , returns the length of the value of the variable as a character
string
select
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 75/113
select allows you to generate simple menus easily
Syntax:-
select name [in list ]
do
statements that can use $name...
done what select does:
Generates a menu of each item in list , formatted with numbers for each choice
Prompts the user for a number
Stores the selected choice in the variable name and the selected number in the built-invariable REPLY
Executes the statements in the body
Repeats the process forever
Command-line Options
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 76/113
positional parameters (variables called 1, 2, 3, etc.) that the shell uses to store
the command-line arguments to a shell script or function when it runsBut consider when options are involved.
command [-options ] args
So the value of positional parameter $1 becomes options ,followed by $2 ,$3
$1 will not get first value of args ,which results in error.
Shift command can be used to shift variable position.
shift
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 77/113
supply a numeric argument to shift , it will shift the arguments that many times
overfor example, shift 3 has the effect:
• 1= $4 2= $5 ...
Integer Variables and Arithmetic
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 78/113
The shell interprets words surrounded by $(( and )) as arithmetic expressions.
Variables in arithmetic expressions do not need to be preceded by dollar signsKorn shell arithmetic expressions are equivalent to their counterparts in the C
language
Table shows the arithmetic operators that are supported. There is no need to
backslash-escape them, because they are within the $((...)) syntax.
The assignment forms of these operators are also permitted.
For example, $((x += 2)) adds 2 to x and stores the result back in x.
: Arithmetic Operators
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 79/113
p
Operator Meaning
+ Plus
- Minus
* Times
/ Division (with truncation)
% Remainder<< Bit-shift left
>> Bit-shift right
& Bitwise and
| Bitwise or~ Bitwise not
^ Bitwise exclusive or
Relational Operators
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 80/113
p
Operator Meaning
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal
== Equal!= Not equal
&& Logical and
|| Logical or
Value 1 is for true and 0 for false
Ex:- $((3 > 2)) has the value 1
$(( (3 > 2) || (4 <= 1) )) also has the value 1
Arithmetic Variables and Assignment
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 81/113
The ((...)) construct can also be used to define integer variables and assign
values to them. The statement:
(( intvar =expression ))
The shell provides a better equivalent: the built-in command let.
let intvar =expression there must not be any space on either side of the equal sign ( =).
Sample Integer Expression Assignments
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 82/113
p g p g
Assignment Value
let x= $x
1+4 5
'1 + 4 ‘ 5
'(2+3) * 5 ‘ 25
'2 + 3 * 5 ‘ 17'17 / 3 ‘ 5
'17 % 3 ‘ 2
'1<<4 ‘ 16
'48>>3 ‘ 6'17 & 3 ‘ 1
'17 | 3 ‘ 19
'17 ^ 3 ‘ 18
Arrays
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 83/113
The two types of variables: character strings and integers. The third type of variable the
Korn shell supports is an array .
An array is like a list of things
There are two ways to assign values to elements of an array.
The first is
nicknames[2]=shell nicknames[3]=program
The second way to assign values to an array is with a variant of the set statement,
set -A aname val1 val2 val3 ...
creates the array aname (if it doesn't already exist) and assigns
val1 to aname[0] , val2 to aname[1] , etc.
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 84/113
To extract a value from an array, use the syntax
${aname [ i ]}.
Ex:-
1) ${nicknames[2]} has the value “shell”
2) print "${nicknames[ *]}",
O/p :- shell program
typeset
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 85/113
the kinds of values that variables can hold is the typeset command.
typeset is used to specify the type of a variable (integer, string, etc.);
the basic syntax is:
typeset -o varname [=value ]
Options can be combined; multiple varname s can be used. If you leave out
varname , the shell prints a list of variables for which the given option is turned
on.
:
Local Variables in Functions
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 86/113
typeset without options has an important meaning: if a typeset statement is
inside a function definition, then the variables involved all become local to thatfunction
you just want to declare a variable local to a function, use typeset without any
options.
String Formatting Options
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 87/113
Typeset String Formatting Options
Option Operation
-Ln Left-justify. Remove leading blanks; if n is given, fill with blanks
or truncate on right to length n .
-Rn Right-justify. Remove trailing blanks; if n is given, fill with blanks
or truncate on left to length n .
-Zn Same as above, except add leading 0's instead of blanks if
needed.
-l Convert letters to lowercase.
-u Convert letters to uppercase.
typeset String Formatting Options
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 88/113
Ex:-
alpha=" aBcDeFgHiJkLmNoPqRsTuVwXyZ "
Statement Value of v
typeset -L v=$alpha "aBcDeFgHiJkLmNoPqRsTuVwXyZ “
typeset -L10 v=$alpha "aBcDeFgHiJ“
typeset -R v=$alpha " aBcDeFgHiJkLmNoPqRsTuVwXyZ“
typeset -R16 v=$alpha "kLmNoPqRsTuVwXyZ“
typeset -l v=$alpha " abcdefghijklmnopqrstuvwxyz“
typeset -uR5 v=$alpha "VWXYZ“
typeset -Z8 v="123.50“ "00123.50"
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 89/113
A typeset -u undoes a typeset -l , and vice versa.
A typeset -R undoes a typeset -L , and vice versa.
typeset -Z has no effect if typeset -L has been used.
to turn off typeset options type typeset + o , where o is the option you turned
on before
Typeset Type and Attribute Options
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 90/113
Option Operation
-in Represent the variable internally as an integer; improvesefficiency of arithmetic. If n is given, it is the base used for
output.
-r Make the variable read-only: forbid assignment to it and disallow
it from being unset .
-x Export; same as export command.
-f Refer to function names only
Ex:-
typeset -r PATH
typeset -i x=5 .
Typeset Function Options
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 91/113
The -f option has various suboptions, all of which relate to functions
Option Operation
-f With no arguments, prints all function definitions.
-f fname Prints the definition of function fname .
+f Prints all function names.
-ft Turns on trace mode for named function(s).
+ft Turns off trace mode for named function(s).
-fu Defines given name(s) as autoloaded function(s).
Two of these have built-in aliases that are more mnemonic: functions isan alias for typeset -f and autoload is an alias for typeset -fu .Type typeset without any arguments, you will see a list of all currently-
defined variables
I/O Redirectors
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 92/113
Redirector Function
> file Direct standard output to file
< file Take standard input from file cmd1 | cmd2 Pipe; take standard output of cmd1 as standard input to
cmd2 >> file Direct standard output to file ; append to file if it already
exists>| file Force standard output to file even if noclobber set
<> file Use file as both standard input and standard output
n> file Direct file descriptor n to file
I/O Redirector
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 93/113
Redirec tor Funct ion
n< file Set file as file descriptor n
>&n Duplicate standard output to file descriptor n
<&n Duplicate standard input from file descriptor n
<&- Close the standard input
>&- Close the standard output
|& Background process with I/O from parent shell
>&p Direct background process' standard output to the parent shell's
standard output
<&p Direct parent shell's standard input to background process'
standard input
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 94/113
The redirector <> is mainly meant for use with device files (in the /dev
directory), i.e., files that correspond to hardware devices such as terminals andcommunication lines. Low-level systems programmers can use it to test device
drivers
2>&1 says, "send standard error (file descriptor 2) to the same place as
standard output (file descriptor 1)
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 95/113
print escape sequences
print accepts a number of options, as well as several escape sequences that start with a
backslash
Sequence Character printed
\a ALERT or [CTRL-G]
\b BACKSPACE or [CTRL-H]
\c Omit final NEWLINE
\f FORMFEED or [CTRL-L]
\n NEWLINE (not at end of command) or [CTRL-J]
\r RETURN (ENTER) or [CTRL-M] \t TAB or [CTRL-I]
\v VERTICAL TAB or [CTRL-K]
\0n ASCII character with octal (base-8) value n , where n is 1 to 3 digits
\\ Single backslash
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 96/113
The \0 n sequence is more device-dependent and can be used for complex I/O, such as
cursor control and special graphics characters.
Options to print
Option Function
-n Omit the final newline (same as the \c escape sequence)
-r Raw; ignore the escape sequences listed above
-p Print on pipe to coroutine
-s Print to command history file
-u n Print to file descriptor n
Ex:-
print -s PATH=$PATH
read
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 97/113
read command, allows you to read values into shell variables
Options to readOption Function
-r Raw; do not use \\ as line continuation character
-s Save input in command history file. Chapter 1 .
-u n Read from file descriptor n .
EX:-
read -r preserves any other escape sequences the input might contain. For
example, if the file fred contains this line:
A line with a\n escape sequence
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 98/113
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 99/113
Steps in Command-line Processing
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 100/113
1. Splits the command into tokens that are separated by the fixed set of
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 101/113
metacharacters : SPACE, TAB, NEWLINE, ;, (, ), <, >, | , and &. Types of tokens
include words , keywords , I/O redirectors, and semicolons.
2. Checks the first token of each command to see if it is a keyword with no quotes
or backslashes
3. Checks the first word of each command against the list of aliases .
4. Substitutes the user's home directory ( $HOME ) for tilde if it is at the beginningof a word. Substitutes user 's home directory for ~user .
5. Performs parameter (variable) substitution for any expression that starts with a
dollar sign ( $).
6. Does command substitution for any expression of the form $(string ).
7. Evaluates arithmetic expressions of the form $((string )).
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 102/113
8 Performs filename generation , a.k.a. wildcard expansion , for any occurrences of
*, ? , and [/] pairs9 Uses the first word as a command by looking up its source according to the
rest of the list in Chapter 4 , i.e., as a built-in command
10 Runs the command after setting up I/O redirection and other such things.
11 Takes the parts of the line that resulted from parameter, command, and
arithmetic substitution and splits them into words again
eval
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 103/113
Quoting skip steps in command-line processing.
The eval command, lets you go through the process again. Performingcommand-line processing twice.
Ex:-
listpage="ls | more"
$listpage
Instead of producing a paginated file listing, the shell will treat | and more
as arguments to ls
eval listpage
Signals
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 104/113
A signal is a message that one process sends to another when some abnormal
event takes place or when it wants the other process to do somethingsignal is another way of processes to communicate with each other.
To get list of all the signals on your system
kill -l
Control-key Signals
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 105/113
CTRL-C, to send the INT ( "interrupt") signal to the current job
[CTRL-Z] sends TSTP ( for "terminal stop").send the current job a QUIT signal by typing CTRL-\ (control-backslash)
KILL signal
To find out what your control-key settings are
stty -a
To customize the control keys used to send signals , use options of the
stty command
For example, to set INT key to [CTRL-X] , use:
stty intr ^X
kill
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 106/113
kill is used to send a signal to any process you created-not just the
currently running job
kill takes as argument the process ID, job number, or command name of the
process to which you want to send the signal.
Ex:-
$ kill %1
kill -QUIT %1
$ kill -KILL %1
$ kill -QUIT 2389
trap
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 107/113
Syntax
trap cmd sig1 sig2 ... when any of sig1 , sig2 , etc., are received, run cmd , then resume execution.
After cmd finishes, the script resumes execution just after the command that
was interrupted.
The sig s can be specified by name or by number
Ex:-
trap 'print \'You hit control-C!\' ' INT
trap 'print \'You hit control-C!\' ' INT TERM
Traps and Functions
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 108/113
function settrap {
trap 'print \'You hit control-C!\' ' INT}
settrap
while true; do
sleep 60
done
Ignoring Signals
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 109/113
HUP (hangup), the signal the shell sends to all the background processes
when you log out.nohup is used to ignore HUP
CoroutinesWhen two (or more) processes are explicitly programmed to run
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 110/113
( ) p p y p g
simultaneously and possibly communicate with each other, we call them
coroutines .a pipeline is an example of coroutines
Ex:-
ls | more
the shell tells UNIX to do the following things
1. Create two subprocesses, which we'll call P1 and P2 (the fork system call).
2. Set up I/O between the processes so that P1's standard output feeds into P2's
standard input ( pipe ).
3. Start /bin/ls in process P1 ( exec ).
4. Start /bin/more in process P2 ( exec ).
5. Wait for both processes to finish ( wait ).
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 111/113
Summary
8/11/2019 (2) Original Korn Shell Script
http://slidepdf.com/reader/full/2-original-korn-shell-script 112/113
Types of Shells
Shell VariablesProgram Constructs
System Variables.