chapter 13
Download
Skip this Video
Download Presentation
Chapter 13

Loading in 2 Seconds...

play fullscreen
1 / 54

Chapter 13 - PowerPoint PPT Presentation


  • 160 Views
  • Uploaded on

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.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Chapter 13' - ciro


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
chapter 13
Chapter 13

The Z shell and Advanced Shell Programming

topics
Topics
  • Background
  • Variables
  • The Builtins
  • Command Processing
  • Shell Programs
  • Z Shell Options
z background iz dees
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
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 files1
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 files2
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 files3
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
topics1
Topics
  • Background
  • Variables
  • The Builtins
  • Command Processing
  • Shell Programs
  • Z Shell Options
variables
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.
variables1
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.
variables2
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
variables3
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

variables4
Variables

linux1% numvar=65261

linux1% typeset –i 16 hexnum

linux1% hexnum=$numvar

linux1% echo $numvar $hexnum

65261 16#FEED

variables5
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.
variables6
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)
variables7
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
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
Keyword Variables
  • Three categories
    • Modifiable
      • Set and used by environment
    • Readonly
      • Set and used by environment
    • Special
      • Perform special functions
keyword variables1
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 variables2
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 variables3
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
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 prompt1
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 prompt2
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
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 variables1
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
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 variables1
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
Array Variables by the byte

…% OldArray=(this old man)

…% NewArray=“$OldArray[*]”

…% echo ${#NewArray}

12

…% echo $NewArray[4,-4]

s old

arithmetic
These are the same…HoweverArithmetic
  • 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))
arithmetic1
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, Logic & Relational Operators
  • Math
    • Unary
      • +, -, ++, --, <<, >>
    • Binary
      • *, /, %, **, +, -
math logic relational operators1
Math, Logic & Relational Operators
  • Logic
    • Binary (bitwise comparison)
      • &, ^, |
  • Relational
    • <, >, <=, >=, ==, !=
    • &&, ^^, ||
topics2
Topics
  • Background
  • Variables
  • The Builtins
  • Command Processing
  • Shell Programs
  • Z Shell Options
the builtins
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
Basic Syntax for Structures
  • select varname in argumentsdo• • •done
getopts
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
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
getopts1
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
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 output1
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 output2
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
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
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
Functions
  • Declared the same as in bash
    • function func_name{Commands}
    • func_name(){Commands}
functions1
Functions
  • break – will terminate a function.
  • unfunction – will delete a function.
  • autoload – load when executed.
topics3
Topics
  • Background
  • Variables
  • The Builtins
  • Command Processing
  • Shell Programs
  • Z Shell Options
command processing
Command Processing
  • Basically follows the same process as bash.
    • Token splitting
    • History substitution
    • Alias substitution
    • Filename Expansion
    • Command substitution
    • Parameter expansion
    • Etc.
command processing1
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
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
i o redirection the coprocess1
I/O Redirection & the Coprocess

Parent shell

Co-process

Create coprocess

Beginparallelexecution

print…>&p

Read stdin

read…<&p

Write stdout

topics4
Topics
  • Background
  • Variables
  • The Builtins
  • Command Processing
  • Shell Programs
  • Z Shell Options
recursion
Recursion
  • Doing yourself
    • Recursion is the execution of the function within the function.
    • Dependency on the completion of the previous iteration.
makepath
makepath

Makepath()

{ if [[ ${#1} –eq 0 || -d “$1” ]] then return 0 fi if [[ “${1%/*}” = “$1” ]] then mkdir $1 return $? fi makepath ${1%/*} || return 1 mkdir $1 return $?

}

ad