# Parts of the zsh Shell - Shell Scripting

This section walks you through the basics of the zsh shell, showing the built-in commands that are available (or can be added by installing modules), as well as the command line parameters and environment variables used by the zsh shell.

Shell options

Most shells use command line parameters to define the behavior of the shell. The zsh shell uses a few command line parameters to define the operation of the shell, but mostly it uses options to customize the behavior of the shell.You can set shell options either on the command line, or within the shell itself using the set command.

Table below lists the command line parameters available for the zsh shell.

The zsh Shell Command Line Parameters

While this may seem like a small set of command line parameters, the -o parameter is somewhat misleading. It allows you to set shell options that define features within the shell. By far the zsh shell is the most customizable shell available. There are lots of features that you can alter for your shell environment. The different options fit into several general categories:

• Changing directories: Options that control how the cd and dirs commands handle directory changes
• Completion: Options that control command completion features
• Expansion and globbing: Options that control file expansion in commands
• History: Options that control command history recall
• Initialization: Options that control how the shell handles variables and startup files when started
• Input/Output: Options that control command handling
• Job Control: Options that dictate how the shell handles and starts jobs
• Prompting: Options that define how the shell works with command line prompts
• Scripts and Functions: Options that control how the shell processes shell scripts and defines shell functions
• Shell Emulation: Options that allow you to set the behavior of the zsh shell to mimic the behavior of other shell types
• Shell State: Options that define what type of shell to start
• zle: Options for controlling the zsh line editor (zle) feature
• Option Aliases: Special options that can be used as aliases for other option names

With this many different categories of shell options, you can imagine just how many actual options the zsh shell supports. The following sections show a sampling of the different zsh shell options available for you to use when customizing your zsh shell environment.

Shell state

There are six different zsh shell options that define the type of shell to start:

• interactive (-i): Provides a command line interface prompt for entering built-in commands and program names.
• login (-l): The default zsh shell type, processes the zsh shell startup files, and provides a command line interface prompt.
• privileged (-p): The default if the effective user ID (UID) of the user is not the same as the real UID (the user has become the root user). This option disables the user startup files.
• restricted (-r): Restricts the user to a specified directory structure in the shell.
• shin stdin (-s): Commands are read from STDIN.
• single command (-t): Executes a single command from STDIN and exits.
• The shell states define whether or not the shell starts with a command line interface prompt, and what access the user has within the shell.

Shell emulation

The shell emulation options allow you to customize the zsh shell to perform similar to the csh orksh shells. These options are:

• bsd echo: Make the echo statement compatible with the C shell echo command.
• csh junkie history: Using the history command without a specifier references the previous command.
• csh junkie loops: Allow while and for loops to use end like the C shell instead of do and done.
• csh junkie quotes: Change the rules of using single and double quotation marks to match the C shell.
• csh nullcmd: Don’t use the values of the NULLCMD and READNULLCMD variables when executing redirections with no commands.
• ksh arrays: Use Korn-style arrays, starting numeric arrays at 0, and require braces to reference array elements.
• ksh option print: Emulate the Korn shell method of printing options.
• ksh typeset: Alter the way that the typeset command arguments are processed.
• posix builtins: Use the builtin command to execute built-in commands.
• sh file expansion: Perform filename expansion before any other expansion.
• sh nullcmd: Don’t use the NULLCMD and READNULLCMD variables when performing redirections.
• sh option letters: Interpret single letter shell command line options similar to the Korn shell.
• sh word split: Perform field splitting on unquoted parameter expansions.
• traps async: While waiting for a program to exit, handle signals and run traps immediately.

By having multiple options you can pick and choose which csh or ksh shell feature you need to emulate in your zsh shell, instead of having to emulate the entire shell.

Initialization

There are a few options for handling the shell startup features:

• all export: All parameters and variables are exported to child shell processes automatically.
• global export: Parameters exported to the environment will not be made local to the function.
• global rcs: If not set, the zsh shell doesn’t run the global startup files, but it still runs local startup files.
• rcs: If not set, the zsh shell runs the /etc/zshenv startup file, but no others

The initialization options allow you to specify which (if any) zsh shell startup files are run in your shell environment. You can also set these values within startup files themselves to limit which ones the shell executes.

Scripts and functions

The scripts and functions options allow you to customize the shell scripting environment in thezsh shell. This is a handy way to set the way functions perform within the shell.

• c bases: Display hexadecimal numbers in C format (0xdddd) instead of shell format (16#dddd).
• err exit: If a command exits with a non-zero exit status, perform the command in the ZERR trap and exit.
• err return: If a command has a non-zero exit status, return immediately from the enclosing function.
• eval lineno: If set, the line numbers of expressions evaluated using the eval built-in command are tracked separately from the rest of the shell environment.
• exec: Execute commands. If this option isn’t set, read commands and report errors, but don’t execute the commands.
• function argzero: Set $0 to the name of the function or script. • local options: If set, when a shell function returns, all of the options that were set before the function are restored. • local traps: If set, when a signal trap is set within a function, the previous status of the trap is restored when the function exits. • multios: Perform implicit tees or cats when multiple redirections are attempted. • octal zeroes: Interpret any integer string starting with a zero as an octal number. • typeset silent: If not set, using typeset with the name of a parameter displays the current value of the parameter. • verbose: Displays shell input lines as they are read by the shell. • xtrace: Displays commands and their arguments as the shell executes them. The zsh shell allows you to customize lots of features that occur when you’re exiting functions defined in the shell. The zsh shell files The zsh shell uses files at both login and logout to allow you to preset variables and features of the zsh shell. The zsh shell automatically looks for several default files for setting environment variables and executing commands. If the any of the default files exist, the zsh shell executes them at specific instances. There are four different types of default files the zsh shell can handle: • Shell startup files • Login files • Interactive files • Logout files This section examines the myriad of possible files you can use for your zsh shell. The shell startup files When you start a new zsh shell as a login shell (either by logging into the system, or by running the zsh shell program), the zsh shell looks for commands in two files.The default system-wide zsh shell startup file is: /etc/zshenv After executing this file (if it exists), the zsh shell proceeds to the user’s$HOME directory and looks for the file:

$HOME/.zshenv You can test the order in which the zsh shell executes these files by performing a simple test using the echo statement in each file: % zsh This is the /etc/zshenv file. This is the .zshenv file in HOME. % When I started a new zsh shell, it executed the /etc/zshenv file first, then the .zshenv file in the$HOME directory.The shell startup files also execute if you use the zsh shell for a shell script:

% cat test1
#!/bin/zsh
# test run a script
echo "This is a test"
% ./test1
This is the /etc/zshenv file.
This is the .zshenv file in HOME.
This is a test
%

Notice that before the output of the shell script appears, you see the echo statements from the zsh shell startup files.

If you use the zsh shell as a login shell, it first looks for and executes two files:

• /etc/zprofile

These files are executed for all users who use the zsh shell as their login shell. The files should contain system-wide environment variables that should be set for all users, and executable programs that all users should use (such as the umask command to set default file and directory permissions). Most likely if you’re using a Linux distribution that supports the zsh shell, these files already exist for setting system environment variables at login.

After executing this file, the zsh shell looks for two files in each user’s $HOME directory: •$HOME/.zlogin
• $HOME/.zprofile These files can contain user-specific environment variable settings, and executable commands that an individual user wants to run when logging in to the system, before the command line interface prompt appears. Any environment variable settings you make in the$HOME/.zprofile shell will override any system-wide settings made in the /etc/zprofile file, and similarly for the .zlogin files. You can test the order in which the zsh shell executes these files by adding a simple echo statement to each one, then logging in:

% zsh -l
This is the /etc/zshenv file.
This is the .zshenv file in HOME.
This is the /etc/zprofie file.
This is the .zprofile file in HOME.
This is the .zlogin file in HOME.
%

As you can see from the example, the zsh shell executes the zshenv files first, then the zprofile files, and finally, the zlogin files.

The interactive shell files

If you start an interactive zsh shell session, there’s another set of files that can hold startup variables and commands:

• /etc/zshrc
• $HOME/.zshrc The zsh shell executes these files immediately after the startup files when starting an interactive shell: % zsh This is the /etc/zshenv file. This is the .zshenv file in HOME. This is the /etc/zshrc file. This is the .zshrc file in HOME. % Since a login shell is also an interactive shell, the zsh shell executes the contents of the zshrc files as well: % zsh -l This is the /etc/zshenv file. This is the .zshenv file in HOME. This is the /etc/zprofie file. This is the .zprofile file in HOME. This is the /etc/zshrc file. This is the .zshrc file in HOME. This is the /etc/zlogin file. This is the .zlogin file in HOME. % Notice the order in which the zsh shell executes the files. The zshrc file pair are executed after the zprofile files, but before the zlogin files. The shell logout files Besides the login and startup files, the zsh shell also has the ability to execute commands in files when you log out from an interactive or login shell session. These files can be in the following locations: • /etc/zlogout •$HOME/.zlogout

As you probably figured out by now, every user on the system executes the commands in the /etc/zlogout file at logout, while each individual user has a unique $HOME/.zlogout file. The zsh shell will execute any commands in these files before logging out of the current shell.This doesn’t include just exiting from an interactive shell. Thus, if you just start another zsh shell from an existing shell session, the zsh shell won’t execute the logout files when you exit the shell. However, if you start a login shell, the logout files should execute upon exiting: % zsh -l This is the /etc/zshenv file. This is the .zshenv file in HOME. This is the /etc/zprofie file. This is the .zprofile file in HOME. This is the /etc/zshrc file. This is the .zshrc file in HOME. This is the /etc/zlogin file. This is the .zlogin file in HOME. % exit This is the .zlogout file in HOME. This is the /etc/zlogout file. % Notice that the shell executes the .zlogout file before the global zlogout file, which is in the opposite order from the other zsh file types. Environment variables Just like any other shell, the zsh provides standard environment variables for tracking system and shell information. The zsh uses a combination of lower-case variable names and upper-case variable names. There are a few environment variables for which the zsh shell provides both a lower-case and upper-case version. The reason for this is in the way the zsh handles arrays, and compatibility with other shells. The zsh shell uses a space-separated list of words to define an array. Many Bourne shell–derived shells use a colon to separate array elements in multi-value variables, such as the PATH variable in the bash shell. To maintain compatibility, the zsh shell provides a lower-case path variable, which uses the zsh-style array, and an upper-case PATH variable, which uses the Bourne-style array. Table below lists the environment variables found in the zsh shell. The zsh Environment Variables As you can see from Table 23-2 the zsh shell provides some unique features in the environment variables. One of my favorites is the right prompt (RPROMPT) variable. The RPROMPT variable displays a prompt on the right side of the command line interface: % RPROMPT=’%d’ % /home/test % cd test /home/test % /home/test/test The right prompt displays the defined prompt (set to the current working directory in this example) on the far right if the space isn’t needed to display text. If the shell needs to display text, it doesn’t display the right prompt. The zsh shell supports the typeset command, which allows you to declare attributes for a variable before using it. Table 23-3 show the options available for the zsh typeset command. The typeset Command Parameters Parameter Description -a Create a numerical array variable. -A Create an associative array variable. -E Create a double-precision floating-point variable and display using scientific notation. -f Define a function name instead of a variable. -F Create a double-precision floating-point variable and display using fixed-point decimal notation. -h Create a hidden special variable. -H Don’t display the value of the variable. -i Create an integer data type variable. -l Convert the variable value to lower case. -L Left-justify by removing leading blanks from a variable. -r Make the specified variables read-only. -R Right-justify by adding blanks on the left. -t Tag the specified variables. -u Convert the variable value to upper case. -U Keep only the first occurrence for each duplicated value in a numerical array. -x Mark the specified variable for automatic export. -Z Right-justify using leading zeroes. As you can see from the typeset command parameters, the zsh shell supports arrays, both numeric and associative. If you’re used to using numeric arrays in the bash and ksh shells, you’llhave to be a little careful when using them in the zsh shell. The zsh shell starts arrays with anindex value of 1 instead of 0: % mytest=(one two three four) % echo${mytest[1]}
one
% echo ${mytest[2]} two % Creating an associative array is also slightly different in the zsh shell. You must first declare it using the typeset command: % typeset -A test % Once you’ve declared the variable as being an associative array, you can define keys and values.This is where things are a little different. In the zsh shell, you just alternate listing the keys and values: variable=(key1 value1 key2 value2 ...) Thus, to add data to the test array:$ test=( fruit banana vegetable carrot age 18 )
$echo${test[fruit]}
banana
$echo${test[age]}
18
\$

Because of this syntax, every key must be assigned a value in the zsh associative array.

Built-in commands

The zsh shell is unique in that it allows you to expand the built-in commands available in theshell. This provides for a wealth of speedy utilities at your fingertips for a host of different applications.

This section describes the core built-in commands, along with the various modules available atthe time of this writing.

Core built-in commands

The core of the zsh shell contains the basic built-in commands you’re used to seeing in othershells. Table 23-4 describes the built-in commands available for you.

The zsh shell is no slouch when it comes to providing built-in commands! You should recogniz most of these commands from their bash counterparts. The most important features of the zsh shell built-in commands are modules.

There’s a long list of modules that provide additional built-in commands for the zsh shell, and the list continues to grow as resourceful programmers create new modules. Table 23-5 shows the currently available modules at the time of this writing.

The zsh Core Built-In Commands
Command Description

alias Define an alternate name for a command and arguments. autoload Preload a shell function into memory for quicker access.bg Execute a job in background mode. bindkey Bind keyboard combinations to commands.builtin Execute the specified built-in command instead of an executable file of the same name.bye The same as exit.

cd Change the current working directory.chdir Change the current working directory.command Execute the specified command as an external file instead of a function or built-in command.

declare Set the data type of a variable (same as typeset).dirs Displays the contents of the directory stack.disable Temporarily disable the specified hash table elements.disown Remove the specified job from the job table.echo Display variables and text.emulate Set zsh to emulate another shell, such as the Bourne, Korn, or C shells.

enable Enable the specified hash table elements.eval Execute the specified command and arguments in the current shell process.exec Execute the specified command and arguments replacing the current shell process.exit Exit the shell with the specified exit status. If none specified, use the exit status ofthe last command.

export Allow the specified environment variable names and values to be used in child shell processes.false Returns an exit status of 1.fc Select a range of commands from the history list.
Command Description

fg Execute the specified job in foreground mode.float Set the specified variable for use as a floating point variable.functions Set the specified name as a function. getln Read the next value in the buffer stack and place it in the specified variable.

getopts Retrieve the next valid option in the command line arguments and place it in the specified variable. hash Directly modify the contents of the command hash table. history List the commands contained in the history file.

integer Set the specified variable for use as an integer value.jobs List information about the specified job, or all jobs assigned to the shell process.
kill Send a signal (Default SIGTERM) to the specified process or job.

let Evaluate a mathematical operation and assign the result to a variable.limit Set or display resource limits.local Set the data features for the specified variable. log Display all users currently logged in who are affected by the watch parameter.

logout Same as exit, but only works when the shell is a login shell.popd Remove the next entry from the directory stack. print Display variables and text. printf Display variables and text using C-style format strings.

pushd Change the current working directory, and put the previous directory in the directory stack pushln Place the specified arguments into the editing buffer stack. pwd Display the full pathname of the current working directory. read Read a line and assign data fields to the specified variables using the IFScharacters.readonly Assign a value to a variable that can’t be changed.rehash Rebuild the command hash table.continued
Command Description

set Set options or positional parameters for the shell. setopt Set the options for a shell.shift Read and delete the first positional parameter, then shift the remaining ones down one position.

source Find the specified file and copy its contents into the current location. suspend Suspend the execution of the shell until it receives a SIGCONT signal.test Returns an exit status of 0 if the specified condition is TRUE.

times Display the cumulative user and system times for the shell and processes that run in the shell.trap Block the specified signals from being processed by the shell, and execute the

specified commands if the signals are received.true Return a zero exit status.ttyctl Lock and unlock the display.type Display how the specified command would be interpreted by the shell.

typeset Set or display attributes of variables. ulimit Set or display resource limits of the shell or processes running in the shell.umask Set or display the default permissions for creating files and directories.unalias Remove the specified command alias.unfunction Remove the specified defined function.

unhash Remove the specified command from the hash table.unlimit Remove the specified resource limit. unset Remove the specified variable attribute.unsetopt Remove the specified shell option.

wait Wait for the specified job or process to complete.whence Display how the specified command would be interpreted by the shell.where Display the pathname of the specified command if found by the shell.which Display the pathname of the specified command using csh style output.zcompile Compile the specified function or script for faster autoloading.

The zsh Modules
Module Description

zsh/cap POSIX compatibility commands zsh/clone Commands to clone a running shell to another terminalzsh/compctl Commands to control command completionzsh/complete Command line completion commands

zsh/complist Commands for command line completion listing extensions zsh/computil Utility commands for command line completion zsh/datetime Additional date and time commands and variableszsh/deltochar A line editor function replicating emacs functionality zsh/files Commands for basic file handling zsh/mapfile Access to external files via associative arrays

zsh/mathfunc Additional scientific functions zsh/parameter Access to command hash tables via associative arrays zsh/pcre The extended regular expression libraryzsh/sched Scheduling commands for providing timed command execution zsh/net/socket Unix domain socket support zsh/stat Access to the stat system call to provide system statistics

zsh/system Interface for various low-level system features zsh/net/tcp Access to TCP sockets zsh/termcap Interface to the termcap databasezsh/terminfo Interface to the terminfo database zsh/zftp A specialized FTP client commandzsh/zle The zshell line editor

zsh/zleparameter Access to modify zle using variables zsh/zprof Allows profiling for shell functions zsh/zpty Start a command in a pseudo-terminal zsh/zselect Block and return when file descriptors are ready zsh/zutil Various shell utilities The zsh shell modules cover a wide range of topics, from providing simple command line editing features to advanced networking functions. The idea behind the zsh shell is to provide abasic minimum shell environment and let you add on the pieces you need to accomplish your programming job.

The zmodload command is the interface to the zsh modules. You use this command to view,add, and remove modules from the zsh shell session.Using the zmodload command without any command line parameters displays the currently installed modules in your zsh shell:

zsh/zutil
zsh/complete
zsh/main
zsh/terminfo
zsh/zle
zsh/parameter
%

Different zsh shell implementations include different modules by default. To add a new module,just specify the module name on the zmodload command line:

%

Nothing indicates that the module loaded. You can perform another zmodload command, andthe new module should appear in the list of installed modules.
Once you load a module, the commands associated with the module are available as built-in commands:

% zftp open myhost.com rich testing1
Welcome to the myhost FTP server.
% zftp cd test
% zftp dir
01-21-08 11:21PM 120823 test1
01-21-08 11:23PM 118432 test2
% zftp get test1 > test1.txt
% zftp close
%

The zftp command allows you to conduct a complete FTP session directly from your zsh shell command line! You can incorporate these commands into your zsh shell scripts to perform file transfers directly from your scripts. To remove an installed module, use the -u parameter, along with the module name: