1 / 54

Chapter 13

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.

ciro
Download Presentation

Chapter 13

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 13 The Z shell and Advanced Shell Programming

  2. Topics • Background • Variables • The Builtins • Command Processing • Shell Programs • Z Shell Options

  3. 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

  4. 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

  5. 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

  6. 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

  7. 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

  8. Topics • Background • Variables • The Builtins • Command Processing • Shell Programs • Z Shell Options

  9. 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.

  10. 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.

  11. 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

  12. 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

  13. Variables linux1% numvar=65261 linux1% typeset –i 16 hexnum linux1% hexnum=$numvar linux1% echo $numvar $hexnum 65261 16#FEED

  14. 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.

  15. 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)

  16. 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!

  17. 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

  18. Keyword Variables • Three categories • Modifiable • Set and used by environment • Readonly • Set and used by environment • Special • Perform special functions

  19. Keyword Variables • Special variables • # - number of command line arguments • * - all command line arguments together • @ - all command line arguments separate • _ - previous commands last line argument

  20. 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

  21. 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

  22. 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

  23. 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.

  24. 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)

  25. 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

  26. 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%

  27. 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

  28. 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 …

  29. Array Variables by the byte …% OldArray=(this old man) …% NewArray=“$OldArray[*]” …% echo ${#NewArray} 12 …% echo $NewArray[4,-4] s old

  30. 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))

  31. 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!

  32. Math, Logic & Relational Operators • Math • Unary • +, -, ++, --, <<, >> • Binary • *, /, %, **, +, -

  33. Math, Logic & Relational Operators • Logic • Binary (bitwise comparison) • &, ^, | • Relational • <, >, <=, >=, ==, != • &&, ^^, ||

  34. Topics • Background • Variables • The Builtins • Command Processing • Shell Programs • Z Shell Options

  35. 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

  36. Basic Syntax for Structures • select varname in argumentsdo• • •done

  37. 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

  38. 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

  39. 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

  40. 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

  41. 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.

  42. 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

  43. 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<&-

  44. 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. Functions • Declared the same as in bash • function func_name{Commands} • func_name(){Commands}

  46. Functions • break – will terminate a function. • unfunction – will delete a function. • autoload – load when executed.

  47. Topics • Background • Variables • The Builtins • Command Processing • Shell Programs • Z Shell Options

  48. Command Processing • Basically follows the same process as bash. • Token splitting • History substitution • Alias substitution • Filename Expansion • Command substitution • Parameter expansion • Etc.

  49. 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

  50. 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

More Related