540 likes | 733 Views
Chapter 13. The Z shell and Advanced Shell Programming. Topics. Background Variables The Builtins Command Processing Shell Programs Z Shell Options. Z Background iz dees. Developed from the Korn Shell found primarily on System V UNIX systems.
E N D
Chapter 13 The Z shell and Advanced Shell Programming
Topics • Background • Variables • The Builtins • Command Processing • Shell Programs • Z Shell Options
Z Background iz dees • Developed 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
Startup Files • The Four System startup files set systemwide global defaults • /etc/zshenv – Always executes first & only once when zsh starts. • /etc/zprofile – runs at login startup • Not executed if –f option is used • Used to modify environment to mimic bash or ksh
Startup Files • /etc/zshrc – sets interactive defaults • Not executed if –f option is used • Executed only when stdin and stdout are connected. • /etc/zlogin – sets login defaults • Used to modify environment to mimic C or tcsh
Startup Files • The Four user startup files override systemwide defaults • .zshenv – overrides /etc/zshenv variables • Not executed if –f option is used • 2nd file to execute when zsh starts. • .zprofile – overrides /etc/profile variables • Not executed if –f option is used • Used to modify environment to mimic bash or ksh
Startup Files • .zshrc – overrides /etc/zshrc variables • Not executed if –f option is used • Executed only when stdin and stdout are connected. • .zlogin – overrides /etc/zlogin variables • Used to modify environment to mimic C or tcsh
Topics • Background • Variables • The Builtins • Command Processing • Shell Programs • Z Shell Options
Variables • Declared 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.
Variables • Command line argument reference • $0 Command • $1 … $9 first nine arguments • ${10 … } for all other arguments • Deleting variables • unset – will remove variable values and attributes.
Variables • Variable Attributes • Use the typeset built-in to set attributes • -l set variable to lowercase • -uset variable to uppercase • -iset variable to integer • -xexport variable • By default all variables are strings • Arithmetic functions against strings causes • Conversion to integer • Manipulation • Conversion back to string
Variables • Variable 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
Variables linux1% numvar=65261 linux1% typeset –i 16 hexnum linux1% hexnum=$numvar linux1% echo $numvar $hexnum 65261 16#FEED
Variables • Variable 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.
Variables • Variable Attributes - Formatting • Causes the variables to be justified and padded with spaces to a width of number • typeset -Lnumber(justify left pad right) • typeset -Rnumber(justify right pad left) • Causes the variables to be justified right and padded with zeroes to a width of number • typeset -Znumber(justify left pad right)
Variables • Variable Attributes - readonly • Marks variables as unchangeable . • typeset -ror readonly • Values must be set before marking. • Attributes can be viewed by • typeset variable name DOES NOT WORK ANYMORE!
Variable Locality • By default all variables are global • Recognized throughout the current shell and all sub-shells. • Local variables • Defined and recognized only within a function. • typeset name
Keyword Variables • Three categories • Modifiable • Set and used by environment • Readonly • Set and used by environment • Special • Perform special functions
Keyword Variables • Special variables • # - number of command line arguments • * - all command line arguments together • @ - all command line arguments separate • _ - previous commands last line argument
Keyword Variables • Environment 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
Keyword Variables • Environment variables • PS4 – Trace ID • Used by the debugging facility • Set by set -x • RANDOM – each reference sets to 0-32767 • SECONDS – # of sec’s since shell started • TMOUT – # of sec’s until logout
Controlling the Prompt • Default 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
Controlling the Prompt • Not 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.
Controlling the Prompt • PS1=`%(?/True:/False:)` • Test Characters • w – if day of week = n (0 – Sunday) • d – if day of month = n • D – if month = n (0 – January) • ? – last exit status was 0 • Text can include additional %(x.true-text.False-text)
Expanding Shell Variables • Variables 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
Expanding Shell Variables linux1% 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%
Array Variables • z shell supports single dimensional arrays • varname=(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
Array Variables • Non-integer subscripts • $varname [@] – creates a duplicate array each element is exactly the same • NewArray=“$OldArray[@]” • $varname [*] – splits array into characters • NewArray=“$OldArray[*]” Does not work …
Array Variables by the byte …% OldArray=(this old man) …% NewArray=“$OldArray[*]” …% echo ${#NewArray} 12 …% echo $NewArray[4,-4] s old
These are the same…However Arithmetic • let – 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))
Arithmetic • let – builtin with arrays • …% days_in_month=(31 28 31 30 …) • …% echo $((days_in_month[2]))0 This refers to the variabledays_in_month[2] • …% echo $(($days_in_month[2]))28 This refers to the arraydays_in_month[2] Not anymore!
Math, Logic & Relational Operators • Math • Unary • +, -, ++, --, <<, >> • Binary • *, /, %, **, +, -
Math, Logic & Relational Operators • Logic • Binary (bitwise comparison) • &, ^, | • Relational • <, >, <=, >=, ==, != • &&, ^^, ||
Topics • Background • Variables • The Builtins • Command Processing • Shell Programs • Z Shell Options
The Builtins • Control Structures • if…then • for…in • while • case • until • repeat • Select Like bash Use either test (expression) Or [[expression]] Like bash Like bash
Basic Syntax for Structures • select varname in argumentsdo• • •done
getopts • Get 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
getopts in use • Problem: 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
getopts SKIPBLANKS= TMPDIR=\tmp CASE=lower while getopts bt:u arg do case $arg in b) SKIPBLANKS=TRUE ;; t) if [[ -d “$OPTARG” ]] then TMPDIR=$OPTARG else print “$0: -t takes directory argument.” >&2 exit 1 fi;; u) CASE=upper ;; esac
Input and Output • read [-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
Input and Output • read [-qEA] [-un] [varname…] • -un use the specified filestream for input. • Read will prompt the user for input using the following format • read varname\?”Enter something” • Read sets exit status 0 if successful & set a 1 at eof.
Input and Output • print [-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
File Descriptors • Additional files can be opened for use by using the “exec” builtin • exec 3> outputfile • exec 6< inputfile • File descriptors can be duplicated using redirection operators • a<&v • Files can be closed • exec 3<&-
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<&- }
Functions • Declared the same as in bash • function func_name{Commands} • func_name(){Commands}
Functions • break – will terminate a function. • unfunction – will delete a function. • autoload – load when executed.
Topics • Background • Variables • The Builtins • Command Processing • Shell Programs • Z Shell Options
Command Processing • Basically follows the same process as bash. • Token splitting • History substitution • Alias substitution • Filename Expansion • Command substitution • Parameter expansion • Etc.
Command Processing • Process 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
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