korn shell programming
TRANSCRIPT
-
8/3/2019 Korn Shell Programming
1/49
Unix Programming with Korn Shell26/02/2009
/ BFS3
VARADARAJU G MURTHY
195912
TCS Public
-
8/3/2019 Korn Shell Programming
2/49
Unix Programming with Korn Shell
Contents
Shell and its featuresKorn Shell Features
Files and Directories
Use of Special Characters and Quoting
Control Keys
VI Editor Commands and Operations
Korn Shell Scripting
Variables
Command SubstitutionAccepting and displaying data
Program Execution
Test Command, Operators
Expr and Conditional Execution
Program Constructs
Break, Continue, Exit and Comments
Command grouping, Here Document, Export command
Environment, AliasesShell Variables, System Variables, Environment variables
Debugging
Functions, Autoloading
Select statement
Operators String, Arithmetic, Relational
Arrays
Using typeset
I/O RedirectorsSteps in command line processing
Eval command and Signals
Security Features
Internal Use 2
-
8/3/2019 Korn Shell Programming
3/49
Unix Programming with Korn Shell
The shell
A program that interprets users requests to run programs.
Provides environment for user programs.
A command line interpreter that
- Reads user inputs.
- Executes commands
Shell Types in Unix
Bourne Shell.
Bourne Again Shell (bash).
C Shell (c-shell).
Korn Shell (k-shell).
TC Shell (tcsh)
Shell Features
Interactive and background processing.
Input/output redirection
Pipes.
Wild card matching.
Programmable.
- Shell Variables.
- Programming language constructs.
- Shell Scripts.
Internal Use 3
-
8/3/2019 Korn Shell Programming
4/49
-
8/3/2019 Korn Shell Programming
5/49
Unix Programming with Korn Shell
Files Regular files
Also called text files; these contain readable characters. Executable files
Also called programs; these are invoked as commands Directories
Also called folders, contains files & subdirectories
Directories
The working directory
Is the current directory, which is the directory you are "in" at any given time(o/p of pwd command) Tilde notation ( ~ )
A tilde refers to home directory Changing working directories
cd directory-name
cd
which changes to whatever directory you were in before the current one
Internal Use 5
-
8/3/2019 Korn Shell Programming
6/49
Unix Programming with Korn Shell
Wildcards
Wildcard 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
[a-zA-Z] All lower- and uppercase letters
[a-zA-Z0-9_-] All letters, all digits, underscore, and dash
Internal Use 6
-
8/3/2019 Korn Shell Programming
7/49
Unix Programming with Korn Shell
Special Characters and Quoting
Character Meaning
~ Home directory
# Comment
$ Variable expression
& Background job
* String wildcard
( Start subshell
) End subshell \ suppresses meaning of any metacharacter
| Pipe
[ 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
Internal Use 7
-
8/3/2019 Korn Shell Programming
8/49
-
8/3/2019 Korn Shell Programming
9/49
Unix Programming with Korn Shell
Vi Editor
Editing ModeEditing 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
Simple Control Mode Commands
Basic vi Control Mode Commands
Command Description
h Move left one character
l Move right one character
w Move right one word
b Move left one word
W Move to beginning of next non-blank wordB Move to beginning of preceding non-blank word
e Move to end of current word
E Move to end of current non-blank word
0 Move to beginning of line
^ Move to first non-blank character in line
$ Move to end of line
Internal Use 9
-
8/3/2019 Korn Shell Programming
10/49
Unix Programming with Korn Shell
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
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 backwardsdW 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.
Internal Use 10
-
8/3/2019 Korn Shell Programming
11/49
Unix Programming with Korn Shell
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
Character-finding Commands
Command Description
fx Move right to next occurrence of x
Fx Move left to previous occurrence of x
tx Move right to next occurrence of x , then back onespace
Tx Move left to previous occurrence of x , then forward onespace
; Redo last character-finding command
, Redo last character-finding command in oppositedirection
Internal Use 11
-
8/3/2019 Korn Shell Programming
12/49
Unix Programming with Korn Shell
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
be numbers 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 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 thatstring.
With two arguments to fc, the arguments specify the beginning and end of arange of commands
Internal Use 12
-
8/3/2019 Korn Shell Programming
13/49
Unix Programming with Korn Shell
Korn Shell Scripting
Shell Variables Positional Parameters. Special Parameters.
Named variables
Positional Parameters .
Acquire values from the position of arguments in command line.
- $1, $2, $3,..$9
- sh file1 10 20 30
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.
Named Variables
- User-defined variable that can be assigned a value.
- Used extensively in shell-scripts.
- Used for reading data, storing and displaying it.
Internal Use 13
-
8/3/2019 Korn Shell Programming
14/49
Unix Programming with Korn Shell
Command substitution
Command substitution allows you to use the standard output of a command as ifit were the value of a variable.
The syntax is:
varname=`command` (enclose in backquotes)
or
varname=$(UNIX command)
Ex:- x=`date` or x=$(date)
To get the contents of a file into a variable ,you can use
varname=$( < filename)
Accepting Data
read.
- Accepts input from the user.
- Syntax : read variable_name.
- Example : read sname
Display Data
echo
- Used to display a message or any data as required by the user.
- echo [Message, Variable]
Example:
echo "UNIX"
echo $sname
Internal Use 14
-
8/3/2019 Korn Shell Programming
15/49
Unix Programming with Korn Shell
Program Execution
sh Command to execute program in Unix. Syntax : sh Example : sh file1
Shell Script Execution A script , or file that contains shell commands, is a shell program There are two ways to run a script
1 By using . (dot) commandEx:-
# . Scriptname
1 By typing scriptname , if the current directory is part of commandsearch path
# scriptname . If dot isnt in your path then type
# . /scriptname
Internal Use 15
-
8/3/2019 Korn Shell Programming
16/49
-
8/3/2019 Korn Shell Programming
17/49
Unix Programming with Korn Shell
Logical Operators
Logical Operators used with test are:
! Negates the expression.
-a Binary and operator.
-o Binary or operator.
Shell Quotes-Meanings (single forward quotes)
'....' take .... Literally ` ` (single backward quotes)
`` to be interpreted by shell " " (double quotes)
"...." take .... literally after $.
Internal Use 17
-
8/3/2019 Korn Shell Programming
18/49
Unix Programming with Korn Shell
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.
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
Internal Use 18
-
8/3/2019 Korn Shell Programming
19/49
Unix Programming with Korn Shell
Program Constructs if for while
until case
if statement.
Syntax.
if control command
then
else
fi
for statement.
Syntax.
for variable-name in value1 value2 ....
do
Done
Internal Use 19
-
8/3/2019 Korn Shell Programming
20/49
-
8/3/2019 Korn Shell Programming
21/49
Unix Programming with Korn Shell
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.
Command Grouping ( )
Commands grouped in this brackets will always gets executed in a sub-shell
Ex:
# pwd
/root
# ( cd /xyz ; pwd )
/root/xyz
# pwd
/rootChange of a directory is not affected to parent shell
Command Grouping { }
Commands enclosed in this brackets gets executed in the current shell
Ex:
# pwd
/root
# { cd /xyz ; pwd ; }
/root/xyz
# pwd
/root/xyz
The change of directory is permanent
Internal Use 21
-
8/3/2019 Korn Shell Programming
22/49
Unix Programming with Korn Shell
Here Document
It provides automation
Ex:
# cat > file
-
8/3/2019 Korn Shell Programming
23/49
Unix Programming with Korn Shell
Customizing Your Environment
The most basic means of customization that the Korn shell provides are Aliases
Synonyms for commands or command strings that you can define forconvenience.
Options
Controls for various aspects of your environment, which you can turn on andoff.
Variables
Place-holders for information that tell the shell and other programs how tobehave under various circumstances. To customize the environment variousbuilt-in shell variables are available.
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
Internal Use 23
-
8/3/2019 Korn Shell Programming
24/49
Unix Programming with Korn Shell
Aliases Alias is a synonym for a command or command string Syntax:
o 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
type alias without any arguments, to get a list of all the aliases you havedefined as well as several that are built-in.
The command unalias name removes any alias definition for its argument
Internal Use 24
-
8/3/2019 Korn Shell Programming
25/49
Unix Programming with Korn Shell
Options
Options let you change the shell's behavior
A shell option is a setting that is either "on" or "off."
The basic commands that relate to options are set -o optionnames and
set +o optionnames
where optionnames is a list of option names separated by blanks
The - turns the named option on, while the + turns it off
Option Description
bgnice Run background jobs at lower priority (on by default)
emacs Enter emacs editing mode ignoreeof Don't allow use of [CTRL-D] to log off; require the exit command
markdirs When expanding filename wildcards, append a slash (/) to directories
noclobber Don't allow output redirection (>) to clobber an existing file
noglob Don't expand filename wildcards like * and ? (wildcard expansion is sometimes called globbing)
nounset Indicate an error when trying to use a variable that is undefined
trackall Turn on alias tracking vi Enter vi editing mode
To check the status of an option, type
set -o
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
Internal Use 25
-
8/3/2019 Korn Shell Programming
26/49
-
8/3/2019 Korn Shell Programming
27/49
-
8/3/2019 Korn Shell Programming
28/49
Unix Programming with Korn Shell
System Variables or Built-in Variables (Continued)
MAIL
- 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 10minutes)
MAILPATH
- List of filenames, separated by colons (:), to check for incoming mail
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
Environment Variables Environment Variables are known to all kinds of subprocesses Any variable can become an environment variable. First it must be defined as
usual; then it must be exported with the command
export varnames To find out environment variables and their values ,type
export
Internal Use 28
-
8/3/2019 Korn Shell Programming
29/49
Unix Programming with Korn Shell
The Environment File
Although environment variables will always be known to subprocesses, the shellmust define which other variables, options, aliases, etc., are to communicated tosubprocesses.
The way to do this is to put all such definitions in a special file called theenvironment 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 yourenvironment file.
2. Put a line in your .profile that tells the shell where your environment file is:
ENV=envfilename
3. For the changes to take effect, type either . .profile or login. In either case, yourenvironment file will be run when the shell encounters the ENV= statement.
Internal Use 29
-
8/3/2019 Korn Shell Programming
30/49
Unix Programming with Korn Shell
Debugging Shell Programs
Set Options:
set -o Option Command-line Option Action
noexec -n Don't run commands; check forsyntax errors only
verbose -v Echo commands before runningthem
xtrace -x Echo commands after command-line processing
The xtrace option is more powerful: it echoes command lines after they havebeen through parameter substitution, command substitution, and the other stepsof command-line processing
set -o xtrace
Korn Shell Debugger Kshdb is a korn shell debugger It has these features:
Specify points at which the program stops execution and enters the
debugger. These are called breakpoints . Execute only a bit of the program at a time, usually measured in source code
statements. This ability is often called stepping . Examine and possibly change the state of the program (e.g., values of
variables) in the middle of a run, i.e., when stopped at a breakpoint or afterstepping.
Do all of the above without having to change the source code.
The code for kshdb has several features . The most important is the basicprinciple on which it works: it turns a shell script into a debugger for itself, byprepending debugger functionality to it; then it runs the new script.
Internal Use 30
-
8/3/2019 Korn Shell Programming
31/49
Unix Programming with Korn Shell
kshdb Commands
Command Action
*bp N Set breakpoint at line N
*bp str Set breakpoint at next line containing str
*bp List breakpoints and break condition
*bc str Set break condition to str
*bc Clear break condition
*cb Clear all breakpoints
*g Start or resume execution
*s [N ] Step through N statements (default 1)*x Toggle execution tracing
*h, *? Print a help menu
*q Quit
Internal Use 31
-
8/3/2019 Korn Shell Programming
32/49
Unix Programming with Korn Shell
Functions A function is sort of a script-within a-script Functions improve the shell's programmability significantly To define a function, you can use either one of two forms:
function functname {
shell commands
}
or:
functname () {
shell commands }
to delete a function definition issue command
unset -f functname .
To find out what functions are defined in your login session
functions (works only in ksh)
or typeset -f (for other shells)
Autoloaded functions 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 shells 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
How does the shell know where to get the definition of an autoloadedfunction? It uses the built-in variable FPATH , which is a list of directories likePATH . The shell looks for a file called fname that contains the definition offunction fname in each of the directories in FPATH .
o FPATH=/dir1
o autoload scriptname or typeset -fu scriptname
In this case both functionname & scriptname should be same
Internal Use 32
-
8/3/2019 Korn Shell Programming
33/49
Unix Programming with Korn Shell
String Operators
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
Operator Substitution
${varname :-word } Ifvarname 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 isundefined.
${varname :=word} If varname exists and isn't null, return its value;otherwise set it to word and then return its value
Purpose: Setting a variable to a default value if it is undefined.
Example: ${count:=0} sets count to 0 if it is undefined.
${varname :? message } Ifvarname exists and isn't null, return its value;otherwise print varname : followed by message , andabort the current command or script. Omitting message produces the default message parameter null or notset.
Purpose: Catching errors that result from variables beingundefined.
Example: {count:?" undefined!" } prints "count:undefined!" and exits if count is undefined.
${varname :+word } Ifvarname exists and isn't null, return word ; otherwisereturn null.
Purpose: Testing for the existence of a variable.
Example: ${count:+1} returns 1 (which could mean"true") if count is defined.
Length Operator
$ {#varname} , returns the length of the value of the variable as a character string
Internal Use 33
-
8/3/2019 Korn Shell Programming
34/49
Unix Programming with Korn Shell
select
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 eachchoice
Prompts the user for a number Stores the selected choice in the variable name and the selected number in
the built-in variable REPLY
Executes the statements in the body Repeats the process forever
Command-line Options
positional parameters (variables called 1, 2, 3, etc.) that the shell uses to store thecommand-line arguments to a shell script or function when it runs
But 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
supply a numeric argument to shift, it will shift the arguments that many times over
for example, shift 3 has the effect:
1= $4 2= $5 ...
Internal Use 34
-
8/3/2019 Korn Shell Programming
35/49
Unix Programming with Korn Shell
Integer Variables and Arithmetic The shell interprets words surrounded by $(( and )) as arithmetic expressions.
Variables in arithmetic expressions do not need to be preceded by dollarsigns
Korn shell arithmetic expressions are equivalent to their counterparts in the Clanguage
Table shows the arithmetic operators that are supported. There is no need tobackslash-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
Operator Meaning
+ Plus
- Minus
* Times
/ Division (with truncation)
% Remainder
> Bit-shift right
& Bitwise and
| Bitwise or
~ Bitwise not
^ Bitwise exclusive or
Internal Use 35
-
8/3/2019 Korn Shell Programming
36/49
Unix Programming with Korn Shell
Relational Operators
Operator Meaning
< Less than
> Greater than
= 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
-
8/3/2019 Korn Shell Programming
37/49
Unix Programming with Korn Shell
Sample Integer Expression Assignments
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
-
8/3/2019 Korn Shell Programming
38/49
Unix Programming with Korn Shell
Arrays 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.
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
3) print $ { #aname[*] }
o/p:- 2
Internal Use 38
-
8/3/2019 Korn Shell Programming
39/49
Unix Programming with Korn Shell
typeset 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 -option 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 turnedon.
Local Variables in Functions
typeset without options has an important meaning: if a typeset statement is insidea function definition, then the variables involved all become local to that function
you just want to declare a variable local to a function, use typeset without anyoptions.
Ex:-
f1 () {
typeset x
x=35
echo x is $x
}
echo x is $x
Internal Use 39
-
8/3/2019 Korn Shell Programming
40/49
Unix Programming with Korn Shell
Typeset Type and Attribute Options
Option Operation
-i Represent the variable internally as an integer; improvesefficiency of arithmetic.
-r Make the variable read-only: forbid assignment to it anddisallow 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
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.-fu Defines given name(s) as autoloaded function(s).
Two of these have built-in aliases that are more mnemonic: functions is an alias fortypeset -f and autoload is an alias for typeset -fu.
Type typeset without any arguments, you will see a list of all currently-definedvariables
Internal Use 40
-
8/3/2019 Korn Shell Programming
41/49
Unix Programming with Korn Shell
I/O Redirectors
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
n< file Set file as file descriptor n
&- Close the standard output
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 and communicationlines. 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 standardoutput (file descriptor 1)
Internal Use 41
-
8/3/2019 Korn Shell Programming
42/49
Unix Programming with Korn Shell
print
print escape sequences
print accepts a number of options, as well as several escape sequences that startwith 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]
\\ Single backslash
Options to print
Option Function
-n Omit the final newline (same as the \c escape sequence)-r Raw; ignore the escape sequences listed above
-s Print to command history file
Ex:-
print -s PATH=$PATH
read
read command, allows you to read values into shell variables
Options to readOption Function
-p prompt it prompts u for value
-s Save input in command history file. Chapter 1.
-n nchars it accepts only nchars for a variable.
EX:- read -p "enter value for x " x
read -n 4 x
Internal Use 42
-
8/3/2019 Korn Shell Programming
43/49
Unix Programming with Korn Shell
Steps in Command-line Processing
Internal Use 43
-
8/3/2019 Korn Shell Programming
44/49
-
8/3/2019 Korn Shell Programming
45/49
Unix Programming with Korn Shell
Signals 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 dosomething
signal 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 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
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 processto which you want to send the signal.
Ex:-
$ kill %1
$ kill -QUIT %1
$ kill -KILL %1
$ kill -QUIT 2389
Internal Use 45
-
8/3/2019 Korn Shell Programming
46/49
Unix Programming with Korn Shell
Signals (Continued)
trap
Used to alter the effects of certain events that generate signals, which generallytends to halt a process.
Syntax
trap command signal list
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 thatwas 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
1) function settrap {
trap 'print \'You hit control-C!\' ' INT}
settrap
while true; do
sleep 60
done
2) function loop { 3) function loop {
trap 'print how r u ' INT while true ; do
while true ; do sleep 60
sleep 60 done
done }
} trap ' print you hit control-c ' INT
loop
print exiting
Internal Use 46
-
8/3/2019 Korn Shell Programming
47/49
Unix Programming with Korn Shell
DEBUGGING SHELL SCRIPTING BY USING FAKE SIGNALS
Example: EXIT
The EXIT trap, when set, will run its code when the function or script within which itwas set exits.
E xample:
function func {
print 'start of the function'
trap 'print /'exiting from the function/ ' EXIT
}
print 'start of the script'
trap 'print /'exiting from the script/ EXIT
func
Example: ERR
The fake signal ERR enables you to run code whenever a command in thesurrounding script or function exits with non-zero status.
A simple but effective use of this is to put the following code into a script you want todebug:
function errtrap {
es=$?
print "ERROR: Command exited with status $es.
}
trap errtrap ERR
Example: DEBUG
DEBUG, causes the trap code to be run after every statement in the surrounding
function or script.function dbgtrap {
print "badvar is $ badvar
}
trap dbgtrap DEBUG
..section of code in which problem occurs...
trap - DEBUG # turn off DEBUG trap
Internal Use 47
-
8/3/2019 Korn Shell Programming
48/49
Unix Programming with Korn Shell
Ignoring Signals
HUP (hangup), the signal the shell sends to all the background processes whenyou log out.
nohup is used to ignore HUP
Coroutines
When two (or more) processes are explicitly programmed to run simultaneouslyand 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
Create two subprocesses, which we'll call P1 and P2 (the fork system call).
Set up I/O between the processes so that P1's standard output feeds into P2'sstandard input ( pipe ).
Start /bin/ls in process P1 ( exec ).
Start /bin/more in process P2 ( exec ).Wait for both processes to finish ( wait ).
Subshells
whenever a shell script is executed , it invoke another copy of the shell that is asubprocess of the main, or parent , shell process
Subshell Inheritance
Characteristics subshells get, or inherit , from their parents are
The current directory
Environment variables
Standard input, output, and error plus any other open file descriptors
Any characteristics defined in the environment file
Signals that are ignored
The first three of these are inherited by all subprocesses, while the last is uniqueto subshells surround some shell code with parentheses (instead of curlybrackets), and that code will run in a subshell
Internal Use 48
-
8/3/2019 Korn Shell Programming
49/49
Unix Programming with Korn Shell
Security Features
Restricted Shell
The restricted shell is designed to put the user into an environment where hisor her ability to move around and write files is severely limited. It's usuallyused for "guest" accounts. You can make a user's login shell restricted byputting rksh or ksh -r in the user's /etc/passwd entry.
The specific constraints imposed by the restricted shell disallow the user fromdoing the following:
Changing working directories: cd is inoperative. If you try to use it, you will getthe error message "ksh: cd: restricted".
Redirecting output to a file: the redirectors >, >|, , and >> are not allowed. Assigning a new value to the environment variables SHELL, ENV, or PATH. Specifying any pathnames with slashes (/) in them. The shell will treat files
outside of the current directory as "not found." These restrictions go into effect after the user's .profile and environment files
are run. This means that the restricted shell user's entire environment is set up in
.profile . Since the user can't overwrite that file, this lets the system
administrator configure the environment as he or she sees fit.