1 © 2001 john urrutia. all rights reserved. chapter 13 the z shell and advanced shell programming
TRANSCRIPT
2© 2001 John Urrutia. All rights reserved.
TopicsBackground
Variables
The Builtins
Command Processing
Shell Programs
Z Shell Options
3© 2001 John Urrutia. All rights reserved.
Z Background iz deesDeveloped from the Korn Shell found
primarily on System V UNIX systems.
Combines many features of bash, tcsh, and ksh
Extensive help (man zshall or man zsh)
Strong script programming features
4© 2001 John Urrutia. All rights reserved.
Startup FilesThe Four System startup files set
systemwide global defaults/etc/zshenv – Always executes first &
only once when zsh starts.
/etc/zprofile – runs at login startupNot executed if –f option is usedUsed to modify environment to mimic bash or
ksh
5© 2001 John Urrutia. All rights reserved.
Startup Files/etc/zshrc – sets interactive defaults
Not executed if –f option is usedExecuted only when stdin and stdout are
connected.
/etc/zlogin – sets login defaultsUsed to modify environment to mimic C or
tcsh
6© 2001 John Urrutia. All rights reserved.
Startup FilesThe Four user startup files override
systemwide defaults.zshenv – overrides /etc/zshenv variables
Not executed if –f option is used2nd file to execute when zsh starts.
.zprofile – overrides /etc/profile variablesNot executed if –f option is usedUsed to modify environment to mimic bash or
ksh
7© 2001 John Urrutia. All rights reserved.
Startup Files.zshrc – overrides /etc/zshrc variables
Not executed if –f option is usedExecuted only when stdin and stdout are
connected.
.zlogin – overrides /etc/zlogin variablesUsed to modify environment to mimic C or
tcsh
8© 2001 John Urrutia. All rights reserved.
TopicsBackground
Variables
The Builtins
Command Processing
Shell Programs
Z Shell Options
9© 2001 John Urrutia. All rights reserved.
VariablesDeclared as in bash – no whitespace
Variablename=Value
If whitespace is needed it must be enclosed in quotation marks
Referenced by preceding $${…} are required if variable is followed
by a letter, digit or underscore.
10© 2001 John Urrutia. All rights reserved.
VariablesCommand line argument reference
$0 Command
$1 … $9 first nine arguments
${10 … } for all other arguments
Deleting variablesunset – will remove variable values and
attributes.
11© 2001 John Urrutia. All rights reserved.
VariablesVariable Attributes
Use the typeset built-in to set attributes-l set variable to lowercase-u set variable to uppercase-i set variable to integer-x export variable
By default all variables are stringsArithmetic functions against strings causes
Conversion to integer Manipulation Conversion back to string
12© 2001 John Urrutia. All rights reserved.
VariablesVariable Attributes
typeset -i or integer designate numerics
integers by default are considered to be base 10 numbers but can be set to any other base.typeset -i 2 BINARY
Sets the base to 2
13© 2001 John Urrutia. All rights reserved.
Variableslinux1% numvar=65261
linux1% typeset –i 16 hexnum
linux1% hexnum=$numvar
linux1% echo $numvar $hexnum
65261 16#FEED
14© 2001 John Urrutia. All rights reserved.
VariablesVariable Attributes
typeset -x or exportCauses the variables to be copied and made available to any child processes
When applied to a function all sub-shells can execute the function.
15© 2001 John Urrutia. All rights reserved.
VariablesVariable Attributes - Formatting
Causes the variables to be justified and padded with spaces to a width of number typeset -L number (justify left pad right)typeset -R number (justify right pad left)
Causes the variables to be justified right and padded with zeroes to a width of number typeset -Z number (justify left pad right)
16© 2001 John Urrutia. All rights reserved.
VariablesVariable Attributes - readonly
Marks variables as unchangeable .typeset -r or readonly
Values must be set before marking.
Attributes can be viewed bytypeset variable nameDOES NOT WORK ANYMORE!
17© 2001 John Urrutia. All rights reserved.
Variable LocalityBy default all variables are global
Recognized throughout the current shell and all sub-shells.
Local variablesDefined and recognized only within a
function.typeset name
18© 2001 John Urrutia. All rights reserved.
Keyword VariablesThree categories
ModifiableSet and used by environment
ReadonlySet and used by environment
SpecialPerform special functions
19© 2001 John Urrutia. All rights reserved.
Keyword VariablesSpecial variables
# - number of command line arguments
* - all command line arguments together
@ - all command line arguments separate
_ - previous commands last line argument
20© 2001 John Urrutia. All rights reserved.
Keyword VariablesEnvironment variables
LINENO – Line number of script where referenced
PPID – PID of parent proccess
LINES – lines on display (default 24) COLUMNS– columns on display (default 80) PS3 – bash equivalent
21© 2001 John Urrutia. All rights reserved.
Keyword VariablesEnvironment variables
PS4 – Trace IDUsed by the debugging facilitySet by set -x
RANDOM – each reference sets to 0-32767
SECONDS– # of sec’s since shell started
TMOUT – # of sec’s until logout
22© 2001 John Urrutia. All rights reserved.
Controlling the PromptDefault for zsh - $HOSTNAME%
Common options for PS1%~ – Pathname of working directory
%. – Working directory tail ( no pathname)
%m or M – hostname - with DOMAIN
%n – $USERNAME variable
%W – date in format mm/dd/yy
23© 2001 John Urrutia. All rights reserved.
Controlling the PromptNot so Common option for PS1
%n (x . true-text . False-text )n – represents the number to comapre to.
(zero by default)
. – represents a separation character (or /)
x – represents the test character.true-text - text to display if test is true.false-text - text to display if test is false.
24© 2001 John Urrutia. All rights reserved.
Controlling the PromptPS1=`%(?/True:/False:)`
Test Charactersw – if day of week = n (0 – Sunday)d – if day of month = nD – if month = n (0 – January)? – last exit status was 0
Text can include additional %(x .true-text.False-text )
25© 2001 John Urrutia. All rights reserved.
Expanding Shell VariablesVariables can be expanded using
prefix and suffix control characters# - Remove minimal matching prefixes
## - Remove maximal matching prefixes
% - Remove minimal matching suffixes
%% - Remove maximal matching suffixes
26© 2001 John Urrutia. All rights reserved.
Expanding Shell Variableslinux1% somefile=/home/usr/name.c
linux1% echo ${somefile#/*/}
usr/name.c
linux1% echo ${somefile##/*/}
name.c
linux1% echo ${somefile%/*}
/home/usr
linux1% echo ${somefile%%/*}
linux1%
27© 2001 John Urrutia. All rights reserved.
Array Variablesz shell supports single dimensional
arraysvarname=(value1 value2 value3 …)
Entire array is referenced by $varname
Array element(s) is/are referenced by
$varname [n ] – one element
$varname [n,x ] – range of elements
28© 2001 John Urrutia. All rights reserved.
Array Variables Non-integer subscripts
$varname [@] – creates a duplicate array each element is exactly the sameNewArray=“$OldArray[@]”
$varname [*] – splits array into charactersNewArray=“$OldArray[*]”
Does not work …
29© 2001 John Urrutia. All rights reserved.
Array Variables by the byte
…% OldArray=(this old man)
…% NewArray=“$OldArray[*]”
…% echo ${#NewArray}
12
…% echo $NewArray[4,-4]
s old
30© 2001 John Urrutia. All rights reserved.
Arithmeticlet – builtin
…% let “NewVar=OldVar*10+NewVar”No spaces, must be quoted to prevent shell
expansion.You can assign multiple variables on a line
…% ((NewVar=OldVar*10+NewVar))Shortcut method – NO QUOTES NEEDED
…% echo $((2*NewVar))
…% echo $((2*$NewVar))
These are the same…
However
31© 2001 John Urrutia. All rights reserved.
Arithmeticlet – builtin with arrays
…% days_in_month=(31 28 31 30 …)
…% echo $((days_in_month[2]))0 This refers to the variable days_in_month[2]
This refers to the array days_in_month[2]…% echo $(($days_in_month[2]))
28
Not anymore!
32© 2001 John Urrutia. All rights reserved.
Math, Logic & Relational Operators
MathUnary
+, -, ++, --, <<, >>
Binary*, /, %, **, +, -
33© 2001 John Urrutia. All rights reserved.
Math, Logic & Relational Operators
LogicBinary (bitwise comparison)
&, ^, |
Relational<, >, <=, >=, ==, !=
&&, ^^, ||
34© 2001 John Urrutia. All rights reserved.
TopicsBackground
Variables
The Builtins
Command Processing
Shell Programs
Z Shell Options
35© 2001 John Urrutia. All rights reserved.
The BuiltinsControl Structures
if…then
for…in
while
case
until
repeat
Select
Like bash
Like bash
Like bash
Use either
test (expression)
Or
[[expression]]
36© 2001 John Urrutia. All rights reserved.
Basic Syntax for Structuresselect varname in arguments
do•••
done
37© 2001 John Urrutia. All rights reserved.
getoptsGet Options
Sets the valid list of option characters
If option takes an argument it is stored in OPTARG
The : indicates the option requires an argument
while getopts :bt:u arg
38© 2001 John Urrutia. All rights reserved.
getopts in useProblem: Write a script that can take
3 options.-b ignore whitespace at start of line
-u translate all output to uppercase
-t [arg] use the directory provided
39© 2001 John Urrutia. All rights reserved.
getoptsSKIPBLANKS=TMPDIR=\tmpCASE=lowerwhile getopts bt:u argdocase $arg in b) SKIPBLANKS=TRUE ;; t) if [[ -d “$OPTARG” ]]
thenTMPDIR=$OPTARG
elseprint “$0: -t takes directory argument.” >&2exit 1
fi;; u) CASE=upper ;;esac
40© 2001 John Urrutia. All rights reserved.
Input and Outputread [-qEA] [-un] [varname…]
Reads input from the filestream and places it into one or more variables
-q query reads 1 char. if ‘y’ or ‘Y’ set variable to ‘y’ otherwise set it to ‘n’
-E echoes the typed words after the return key
-A breaks input into words based on IFS
41© 2001 John Urrutia. All rights reserved.
Input and Outputread [-qEA] [-un] [varname…]
-un use the specified filestream forinput.
Read will prompt the user for input using the following formatread varname\?”Enter something”
Read sets exit status 0 if successful & set a 1 at eof.
42© 2001 John Urrutia. All rights reserved.
Input and Outputprint [-ncoO] [-un] [string to
print…]-n supress newlines
-c display output in columns
-o sort arguments ascending (-O decending)
The string to print can contain escape characters for formatting
43© 2001 John Urrutia. All rights reserved.
File DescriptorsAdditional files can be opened for use by
using the “exec” builtinexec 3> outputfile
exec 6< inputfile
File descriptors can be duplicated using redirection operatorsa <& v
Files can be closed exec 3<&-
44© 2001 John Urrutia. All rights reserved.
What does this function do?mycp(){ case $# in 0) exec 3<&0 4<&1 ;; 1) exec 3< $1 4<&1 ;; 2) exec 3< $1 4> $2 ;; *) print “Usage: mycp [source [dest]]”
exit 1;; esac cat <&3 >&4 exec 3<&- 4<&-}
45© 2001 John Urrutia. All rights reserved.
FunctionsDeclared the same as in bash
function func_name{Commands}
func_name(){Commands}
46© 2001 John Urrutia. All rights reserved.
Functionsbreak – will terminate a function.
unfunction – will delete a function.
autoload – load when executed.
47© 2001 John Urrutia. All rights reserved.
TopicsBackground
Variables
The Builtins
Command Processing
Shell Programs
Z Shell Options
48© 2001 John Urrutia. All rights reserved.
Command ProcessingBasically follows the same process as
bash.Token splitting
History substitution
Alias substitution
Filename Expansion
Command substitution
Parameter expansion
Etc.
49© 2001 John Urrutia. All rights reserved.
Command ProcessingProcess Substitution
Substitutes filenames with processes
<(command ) - output of command is directed to a named pipe (FIFO) which is substituted for the input file
>(command ) - output is directed to a named pipe (FIFO) which is substituted for standard input to command
50© 2001 John Urrutia. All rights reserved.
I/O Redirection & the Coprocess
Allows the creation of a parallel process that runs in the background and communicates directly with the parent shell.
Connected with a 2-way pipe<&p – read the standard output
>&p – write to standard input
51© 2001 John Urrutia. All rights reserved.
I/O Redirection & the Coprocess
Create coprocess
Beginparallel
execution
Parent shell
print…>&p
read…<&p
Read stdin
Write stdout
Co-process
52© 2001 John Urrutia. All rights reserved.
TopicsBackground
Variables
The Builtins
Command Processing
Shell Programs
Z Shell Options
53© 2001 John Urrutia. All rights reserved.
RecursionDoing yourself
Recursion is the execution of the function within the function.
Dependency on the completion of the previous iteration.