Professional Documents
Culture Documents
Contents
1. Command Language
• I/O redirection and pipe
• Shell variables
• Pattern matching
• Control characters
2. The environment
3. Most usual commands
• Help
• Directory listing
• Creating a directory
• Changing directory
• Comparing files
• Access to files
• copying files and directories
• deleting files & directory
• moving files & directories
• Visualizing files
• linking files & directories
• Compiling & Linking
• Debugging a program
• Archive library
• Make
• Job control
• miscellaneous
• History & Command line editing
4. Creating KORNshell scripts
• The different shells
• Special shell variables
• special characters
• Evaluating shell variables
• The if statement
• The logical operators
• Math operators
• Controlling execution
• Debug mode
• Examples
• Example 1 : loops, cases ...
• Example 2 : switches
• Example 3
• Example 4
• Example 5
5. List of Usual commands
6. List of Administrator commands
1.Command Language
I/O redirection and pipe
% command running in foreground (interactive)
% command >file redirects stdout to file
% command 2>err_file redirects stderr to err_file
% command >file 2>&1 redirects both stdout and stderr on
file
% (command > f1) 2>f2 send stdout on f1, stderr on f2
% command >>file appends stdout to file
% command <file redirects stdin from file
% command << text Read standard input uo to line
identical
to text
% command1 | command2 redirects stdout from command1 into
stdin of
command2 via a pipe
Ex : du ~ | sort -nr | head
% command | tee f1 f2 ... The output of command is sent on
stdout and copied into f1, f2, ...
% command& running in background
% nohup command& running in background even after log
out
% set -o monitor to have a message when a background
job ends
stderr : to print on it in a script, use the option -u2 in
command print
Shell variables
# Warning : no blank before of after the = sign
# Integers :
n=100 ; x=&n
integer t
typeset -r roues=4 # definition of a CONSTANT (read
only)
typeset -i2 x # declares x as binary integer
typeset -i8 y # declares y as octal integer
typeset -i16 z # guess what ?
# Strings :
lettre="Q" ; mot="elephant"
phrase="Hello, word"
print "n=$n ; lettre=$lettre ; mot=$mot ;
phrase=$phrase"
typeset -r nom="JMB" # string constant
# Arrays : one dimensional arrays of integers or strings
# automatically dimensionned to 1024
animal[0]="dog" ; animal[1]="horse" ; animal[3]="donkey"
set -A flower tulip gardenia " " rose
print ${animal[*]}
print ${flower[@]}
print "cell#1 content : ${flower[1]}
Pattern matching
+------------------------
+------------------------------------------------+
| Wild card | matches
|
+------------------------
+------------------------------------------------+
| ? | any single char
|
| [char1char2... charN] | any single char from the specified
list |
| [!char1char2... charN] | any single char other than one from
the |
| | specified list
|
| [char1-charN] | any char between char1 and charN
inclusive |
| [!char1-charN] | any char other than between char1 and
charN |
| | inclusive
|
| * | any char or any group of char
(including none) |
| ?(pat1|pat2...|patN) | zero or one of the specified patterns
|
| @(pat1|pat2...|patN) | exactly one of the specified patterns
|
| *(pat1|pat2...|patN) | zero, one or more of the specified
patterns |
| +(pat1|pat2...|patN) | one or more of the specified patterns
|
| !(pat1|pat2...|patN) | any pattern except one of the specif.
patterns |
+------------------------
+------------------------------------------------+
Tilde Expansion :
~ your home directory (ls ~)
~frenkiel home directory of another user
~+ absolute pathname of the working directory
~- previous directory (cd ~-) ( or cd -)
Control characters
< ctrl_c> Cancel the currently running process (foreground)
< ctrl_z> Suspend the currently running process
then : > bg : to send it in background
or > fg : continue in foreground
or > kill -option : sends signals (such as
TERMINATE)
ex > kill -9 pid : to kill a background job
kill -l : to find out all the
signals
supported by your system.
< ctrl_d> End of file character
$ stty to see what are the KILL & <EOF> characters
2.The environment
+-----------------------------------------------
+-----------------------+
| environmental characteristic | child
inherit this ? |
+-----------------------------------------------
+-----------------------+
| parent's access rights to files, directories | yes
|
| the files that parent has opened | yes
|
| parent's ressource limits (type ulimit) | yes
|
| parent's response to signal | yes
|
| aliases defined by parent | NO (expect
opt -x) |
| functions defined by parent | if
exported (*) |
| variables defined by parent | if
exported (*) |
| KornShell variables (except IFS) | if
exported (*) |
| KornShell variable IFS | if NOT
exported |
| parent's option settings (type set -o) | no
|
+-----------------------------------------------
+-----------------------+
(*) Not needed if a 'set -o allexport' statement has told
the KornShell to
export all these variables and functions
To export a variable :
$ export LPDEST=pshpa
Dot Scripts : a script that runs in the parent's environment, so it is not a child of the caller. A
dot script inherits ALL of the caller's environment. To invoke a dot script, just preface the
name of the script with a dot and a space :
$ ficus.ksh # invoke this script as a regular script.
$ . ficus.fsh # invoke the same script as a dot script.
It is recommanded (but not mandatory) to write the local variable names in lower case letters
and those of global variables in upper case letters.
Sequence of KornShell start-up scripts : The KornShell supports 3 start-up scripts. The first
2 are login scripts; they are executed when you log in. A third one runs whenever you create
a KornShell or run a KornShell script.
- /etc/profile
- $HOME/.profile
Use this file to :
- set & export values of variables
- set options such as ignoreeof that you want to
apply to your
login shell only
- specify a script to execute when yu log out
Example :
set -o allexport # export all
variables
PATH=.:/bin:/usr/bin:$HOME/bin # define command
search path
CDPATH=.:$HOME:$HOME/games # define search
path for cd
FPATH=$HOME/mathlib:/usr/funcs # define path
for autoload
PS1='! $PWD> ' # define primary
prompt
PS2='Line continues here> ' # define
secondary prompt
HISTSIZE=100 # define size of
history file
ENV=$HOME/.kshrc # pathname of
environment script
TMOUT=0 # KornShell
won't be timed out
VISUAL=vi # make vi the
comm. line editor
set +o allexport # turn off
allexport feature
- script whose name is hold in the KornShell variable ENV
Use this file to :
- define aliases & functions that apply for
interactive use only
- set default options that you want to apply to all
ksh invocations
- set variables that you want to apply to the
current ksh invoc.
Example :
# The information in this region will be accessible
to the KornShell
# command line and scripts.
alias -x disk='du' # -x makes alias accessible
to scripts
case $- in
*i*) # Here you are NOT in a
script
alias copy='cp';;
esac
Changing directory
> cd pathname
> cd
> cd ~tristram
> cd - # return to the previous working
directory
Comparing files
> diff f1 f2 text files comparison
> sdiff f1 f2 idem in 2 columns
> diff dir1 dir2 directory comparison
> cmp f1 f2 for binary files
> file filename determine file type
> comm f1 f2 compare lines common to 2 sorted files
Access to files
user group others
r w x rwx rwx
4 2 1
> ls -l display access permission
> chmod 754 file change access (rwx r-x r--)
> chmod u+x file1 gives yourself permition to execute
file1
> chmod g+re file2 gives read and execute permissions for
group members
> chmod a+r *.pub gives read permition to everyone
> umask 002 (default permissions : inverse) removes
write permission
for other in this example
> groups username to find out which group 'username'
belongs to
> ls -gl list the group ownwership of the files
> chgrp group_name file/directory_name
change the group ownwership
Visualizing files
> cat file1 file2 ... print all files on stdout
> more file print 'file' on stdout, pausing at
each end of page
> pg file idem, with more options
> od file octal dump for a binary file
> tail file list the end of a file (last lines)
> tail -n file idem for the last n lines
> tail -f file idem, but read repeatedly in case
the file grows
> tail +n file read the fisrt n lines of 'file'
> head give first few lines
Job control
> nohup command run a command immune to hangups,
logouts,
and quits
> at, batch execute commands at a later time
(see 'man at')
> jobs [-lp] [job_name] Display informations about jobs
> kill -l Display signal numbers ans names
> kill [-signal] job... Send a signal to the specified
jobs
> wait [job...] Wait for the specified jobs to
terminate
(or for all child processes if
no argument)
> ps List executing processes
miscellaneous
> who [am i] lists names of users currently logged in
> rwho idem for all machines on the local
network
> w idem + what they are doing
> whoami your userid
> groups names of the groups you belong to
> hostname name of the host currently connected
> finger names of users, locally or remotly
logged in
> finger name information about this user
> finger name@cdfhp3
> mail electronic mail
> grep searching strings in files
> sleep sleep for a given amount of time (shell
scripts)
> sort sort items in a file
> touch change the modification time of a file
> tar compress all files in a directory (and
its
subdirectories) into one file
> type tells you where a command is located (or
what it is an
alias for)
> find pathname -name "name" -print
seach recursively from pathename for
"name". "name" can
contain wild chars.
> findw string
search recursively for filenames
containing 'string'
> file fich tries to guess the type of 'fich' (wild
chars allowed)
> passwd changing Pass Word
> sh -x command Debugging a shell script
> echo $SHELL Finding out which shell you are using
/.../sh Bourne shell
/.../csh C shell
/.../tcsh TC shell
/.../ksh Korn shell
/.../bash Bourne Again SHell
> df gives a list of available disk space
> du gives disk space used by the current
directory and all
its subdirectories
> time command execute 'command' and then, gives the
elapse time
> ruptime gives the status of all machines on the
local network
> telnet host for remote login
> rlogin host idem for machines running UNIX
> stty set terminal I/O options
(without args or with -a, list current
settings)
> tty, pty get the name of the terminal
> write user_name send a message (end by < ctrl_d --> to a
logged user
> msg y enable message reception
> msg n disable message recpt.
> mes status of mes. recept.
> wall idem write, but for all logged users.
> date display date and time on standard output
> ulimit set or display system ressource limits
> whence command find pathname corresponding to 'command'
> whence -v name gives the type of 'name' (built-in,
alias, files ...)
> tee [-a] file reads standard input, writes to standard
output and
file. Appends to 'file' if option -a
> wc file Counts lines, words and chars in 'file'
You can edit the command line with the 'vi' or 'emacs' editor :
Put the following line inside a KornShell login script :
FCEDIT=vi; export FCEDIT
$ set -o emacs
> fc [-e editor] [-nlr] [first [last]]
* display (-l) commands from history file
* Edit and re-execute previous commands (FCEDIT if no -
e).
'last' and 'first' can be numbers or strings
$ fc # edit a copy of last command
$ fc 271 # edit, then re-execute command
number 271
$ fc 270 272 # group command 270, 271 & 272,
edit, re-execute
special characters
The special chars of the Korn shell are :
$ \ # ? [ ] * + & | ( ) ; ` " '
- A pair of simple quotes '...' turns off the significance of
ALL enclosed chars
- A pair of double quotes "..." : idem except for $ ` " \
- A '\' shuts off the special meaning of the char immediately to
its right.
Thus, \$ is equivalent to '$'.
- In a script shell :
# : all text that follow it up the newline is a
comment
\ : if it is the last char on a line, signals a
continuation line
qui suit est la continuation de celle-ci
The if statement
The if statement uses the exit status of the given command
if test
then
commands (if condition is true)
else
commands (if condition is false)
fi
Test on numbers :
((number1 == number2))
((number1 != number2))
((number1 number2))
((number1 > number2))
((number1 = number2))
((number1 >= number2))
Warning : 5 different possible syntaxes (not absolutely
identical) :
if ((x == y))
if test $x -eq $y
if let "$x == $y"
if [ $x -eq $y ]
if [[ $x -eq $y ]]
cmd1 is executed and its exit status examined. Only if cmd1 succeeds is cmd2 executed. You
can use the || operator to execute a command and, if it fails, execute the next command in the
command list.
cmd1 || cmd2
Math operators
First, don't forget that you have to enclose the entire mathematical operation within a
DOUBLE pair of parentheses. A single pair has a completely different meaning to the Korn-
Shell.
+-----------+-----------+-------------------------+
| operator | operation | example |
+-----------+-----------+-------------------------+
| + | add. | ((y = 7 + 10)) |
| - | sub. | ((y = 7 - 10)) |
| * | mult. | ((y = 7 * 4)) |
| / | div. | ((y = 37 / 5)) |
| % | modulo | ((y = 37 + 5)) |
| | shift | ((y = 2#1011 2)) |
| >> | shift | ((y = 2#1011 >> 2)) |
| & | AND | ((y = 2#1011 & 2#1100)) |
| ^ | excl OR | ((y = 2#1011 ^ 2#1100)) |
| | | OR | ((y = 2#1011 | 2#1100)) |
+-----------+-----------+-------------------------+
Controlling execution
goto my_label
......
my_label:
-----
case value in
pattern1) command1 ; ... ; commandN;;
pattern2) command1 ; ... ; commandN;;
........
patternN) command1 ; ... ; commandN;;
esac
where : value value of a variable
pattern any constant, pattern or group of
pattern
command name of any program, shell script or
ksh statement
example 1 :
case $advice in
[Yy][Ee][Ss]) print "A yes answer";;
[Mm]*) print "M followed by anything";;
+([0-9)) print "Any integer...";;
"oui" | "bof") print "one or the other";;
*) print "Default";;
example 2 : Creating nice menus
PS3="Enter your choice :"
select menu_list in English francais
do
case $menu_list in
English) print "Thank you";;
francais) print "Merci";;
*) print "???"; break;;
esac
done
-----
while( logical expression)
do
....
done
while : # infinite loop
....
done
while read line # read until an EOF (or <crtl_d> )
do
....
done fname # redirect input within this while
loop
until( logical expression)
do
....
done <fin >fout # redirect both input and output
-----
for name in 1 2 3 4 # a list of elements
do
....
done
for obj in * # list of every object in the
current directory
do
....
done
for obj in * */* # $PWD and the next level below it
contain
do
....
done
-----
break; # to leave a loop (while, until,
for)
continue; # to skip part of one loop iteration
# nested loops are allowed in ksh
----
select ident in Un Deux # a list of identifiers
do
case $ident in
Un) ....... ;;
Deux) ..... ;;
*) print " Defaut" ;;
esac
done
Debug mode
> ksh -x script_name
ou, dans un 'shell script' :
set -x # start debug mode
set +x # stop debug mode
Examples
Example 1 : loops, cases ...
#!/bin/ksh
USAGE="usage : fmr [dir_name]" # how to invoke this
script
print "
+------------------------+
| Start fmr shell script |
+------------------------+
"
function fonc
{
echo "Loop over params, with shift function"
for i do
print "parameter $1" # print is equivalent to echo
shift
done # Beware that $# in now = 0 !!!
}
echo "Loop over all ($#) parameters : $*"
for i do
echo "parameter $i"
done
#----------------------
if (( $# > 0 )) # Is the first arg. a directory
name ?
then
dir_name=$1
else
print -n "Directory name:"
read dir_name
fi
print "You specified the following directory; $dir_name"
if [[ ! -d $dir_name ]]
then
print "Sorry, but $dir_name isn't the name of a
directory"
else
echo "-------- List of directory $dir_name
-----------------"
ls -l $dir_name
echo
"------------------------------------------------------"
fi
#----------------------
echo "switch on #params"
case $# in
0) echo "command with no parameter";;
1) echo "there is only one parameter : $1";;
2) echo "there are two parameters";;
[3,4]) echo "3 or 4 params";;
*) echo "more than 4 params";;
esac
#----------------------
fonc
echo "Parameters number (after function fonc) : $#"
#------- To read and execute a
command
echo "==> Enter a name"
while read com
do
case $com in
tristram) echo "gerard";;
guglielmi) echo "laurent";;
dolbeau) echo "Jean";;
poutot) echo "Daniel ou Claude ?";;
lutz | frenkiel) echo "Pierre";;
brunet) echo "You lost !!!"; exit ;;
*) echo "Unknown guy !!! ( $com )"; break ;;
esac
echo "==> another name, please"
done
#------ The test function :
echo "Enter a file name"
read name
if [ -r $name ]
then echo "This file is readable"
fi
if [ -w $name ]
then echo "This file is writable"
fi
if [ -x $name ]
then echo "This file is executable"
fi
#------
echo "--------------- Menu select ----------"
PS3="Enter your choice: "
select menu_list in English francais quit
do
case $menu_list in
English) print "Thank you";;
francais) print "Merci.";;
quit) break;;
*) print " ????";;
esac
done
print "So long!"
Example 2 : switches
#!/bin/ksh
USAGE="usage: gopt.ksh [+-d] [ +-q]" # + and - switches
while getopts :dq arguments # note the leading
colon
do
case $arguments in
d) compile=on;; # don't precede d
with a minus sign
+d) compile=off;;
q) verbose=on;;
+q) verbose=off;;
\?) print "$OPTARG is not a valid option"
print "$USAGE";;
esac
done
print "compile=$compile - verbose= $verbose"
Example 3
###############################################################
# This is a function named 'sqrt'
function sqrt # square the input argument
{
((s = $1 * $1 ))
}
# In fact, all KornShell variables are, by default, global
# (execpt when defined with typeset, integer or readonly)
# So, you don't have to use 'return $s'
###############################################################
# The shell script begins execution at the next line
print -n "Enter an integer : "
read an_integer
sqrt $an_integer
print "The square of $an_integer is $s"
Example 4
#!/bin/ksh
############ Using exec to do I/O on multiple files
############
USAGE="usage : ex4.ksh file1 file2"
if (($# != 2)) # this script needs 2
arguments
then
print "$USAGE"
exit 1
fi