Chapter 13
This presentation is the property of its rightful owner.
Sponsored Links
1 / 54

Chapter 13 PowerPoint PPT Presentation


  • 118 Views
  • Uploaded on
  • Presentation posted in: General

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.

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

    • $0Command

    • $1 … $9first 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…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))


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

  • 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 $?

}


  • Login