Sie sind auf Seite 1von 579

BMC BladeLogic

Network Shell Command


Reference Manual

Supporting
BMC BladeLogic version 8.0.00
November 2009

www.bmc.com

Contacting BMC Software


You can access the BMC Software website at http://www.bmc.com. From this website, you can obtain information
about the company, its products, corporate offices, special events, and career opportunities.

United States and Canada


Address

BMC SOFTWARE INC


2101 CITYWEST BLVD
HOUSTON TX 77042-2827
USA

Telephone

713 918 8800 or


800 841 2031

Fax

(01) 713 918 8000

Fax

713 918 8000

Outside United States and Canada


Telephone

(01) 713 918 8800

Copyright 2009 BladeLogic, Inc.


BladeLogic and the BladeLogic logo are the exclusive properties of BladeLogic, Inc. The BladeLogic trademark is registered with the U.S.
Patent and Trademark Office, and may be registered or pending registration in other countries. All other BladeLogic trademarks, service
marks, and logos may be registered or pending registration in the U.S. or in other countries. All other trademarks or registered
trademarks are the property of their respective owners.
BMC, BMC Software, and the BMC Software logo are the exclusive properties of BMC Software, Inc., are registered with the U.S. Patent
and Trademark Office, and may be registered or pending registration in other countries. All other BMC trademarks, service marks, and
logos may be registered or pending registration in the U.S. or in other countries. All other trademarks or registered trademarks are the
property of their respective owners.
AIX and IBM are trademarks or registered trademarks of International Business Machines Corporation in the United States, other
countries, or both.
HP-UX is the registered trademark of Hewlett-Package Company.
Java, JRE, JMX, J2SE, Solaris, and Sun are the trademarks or registered trademarks of Sun Microsystems, Inc., in the U.S. and other
countries.
Linux is the registered trademark of Linus Torvalds.
Oracle is the registered trademark of Oracle Corporation.
Red Hat and RPM are registered trademarks of Red Hat, Inc., in the U.S. and other countries.
Sun, Solaris and Java are the registered trademarks of Sun Microsystems, Inc., in the U.S. and other countries.
SUSE is the registered trademark of SUSE Linux AG., in the U.S. and other countries.
UNIX is the registered trademark of The Open Group in the US and other countries.
VMWare is the registered trademark of VMWare, Inc., in the US and other countries.
Microsoft, Windows, Windows 2000, Windows 2003, Windows 2008, and SQL Server are registered trademarks of Microsoft, Inc., in the
U.S. and other countries.
The information included in this documentation is the proprietary and confidential information of BMC Software, Inc., its affiliates, or
licensors. Your use of this information is subject to the terms and conditions of the applicable End User License agreement for the product
and to the proprietary and restricted rights notices included in the product documentation.

Restricted rights legend


U.S. Government Restricted Rights to Computer Software. UNPUBLISHED -- RIGHTS RESERVED UNDER THE COPYRIGHT LAWS OF
THE UNITED STATES. Use, duplication, or disclosure of any data and computer software by the U.S. Government is subject to
restrictions, as applicable, set forth in FAR Section 52.227-14, DFARS 252.227-7013, DFARS 252.227-7014, DFARS 252.227-7015, and
DFARS 252.227-7025, as amended from time to time. Contractor/Manufacturer is BMC SOFTWARE INC, 2101 CITYWEST BLVD,
HOUSTON TX 77042-2827, USA. Any contract notices should be sent to this address.

Customer support
You can obtain technical support by using the BMC Software Customer Support website or by contacting Customer
Support by telephone or e-mail. To expedite your inquiry, see Before contacting BMC.

Support website
You can obtain technical support from BMC 24 hours a day, 7 days a week at http://www.bmc.com/support. From this
website, you can

read overviews about support services and programs that BMC offers
find the most current information about BMC products
search a database for issues similar to yours and possible solutions
order or download product documentation
download products and maintenance
report an issue or ask a question
subscribe to receive proactive e-mail alerts when new product notices are released
find worldwide BMC support center locations and contact information, including e-mail addresses, fax numbers, and
telephone numbers

Support by telephone or e-mail


In the United States and Canada, if you need technical support and do not have access to the web, call 800 537 1813 or
send an e-mail message to customer_support@bmc.com. (In the subject line, enter SupID:<yourSupportContractID>,
such as SupID:12345). Outside the United States and Canada, contact your local support center for assistance.

Before contacting BMC


Have the following information available so that Customer Support can begin working on your issue immediately:

product information
product name
product version (release number)
license number and password (trial or permanent)

operating system and environment information


machine type
operating system type, version, and service pack or other maintenance level such as PUT or PTF
system hardware configuration
serial numbers
related software (database, application, and communication) including type, version, and service pack or
maintenance level

sequence of events leading to the issue

commands and options that you used

messages received (and the time and date that you received them)
product error messages
messages from the operating system, such as file system full
messages from related software

License key and password information


If you have questions about your license key or password, contact BMC as follows:

(USA or Canada) Contact the Order Services Password Team at 800 841 2031, or send an e-mail message to
ContractsPasswordAdministration@bmc.com.

(Europe, the Middle East, and Africa) Fax your questions to EMEA Contracts Administration at +31 20 354 8702, or send
an e-mail message to password@bmc.com.

(Asia-Pacific) Contact your BMC sales representative or your local BMC office.

BMC BladeLogic Network Shell Command Reference Manual

Introduction
The Network Shell (NSH) commands are file manipulation utilities designed to look
and feel like their UNIX counterparts. The difference is that the NSH commands are
able to access and manipulate both local and remote files without using NFS/RFS or
the .rhost remote authentication mechanisms.
Using the NSH commands, you can manage your network of UNIX and Windows
machines as one large host. You can perform system administrative functions on
multiple remote hosts from a single machine. Instead of having to rlogin or telnet to a
host to see what is going is on, or to make a quick change, you can just use the NSH
commands to access files on local and remote hosts directly from the command line.
You can use the NSH commands to write new scripts, or modify existing scripts and
make them distributed.
The BMC BladeLogic Network Shell Command Reference Manual provides both
summarized and complete descriptions of all commands and utilities available in
Network Shell.
Use this document as follows:

To view summarized descriptions of commands and utilities, see the alphabetized


table in Summarized descriptions of commands on page 7.
To view complete descriptions of commands and utilities, see Complete
descriptions of commands on page 11.

Authenticating with Network Shell


When you use Network Shell in conjunction with a Network Shell Proxy Server, you
must first authenticate. Once you successfully authenticate, you are issued a session
credential, which grants you access to the proxy server.
If you are using Network Shell interactively, you can either obtain a session
credential using Configuration Manager or Provisioning Manager or you can use the
blcred command line utility. If you are running Network Shell in batch mode, you
must use blcred to obtain a session credential.

Introduction

ZSH support

For more information about blcred, refer to the blcred man page or see the BMC
BladeLogic Administration Guide, which describes typical scenarios for using the utility.

ZSH support
Network Shell supports both 4_0_4 and 4_3_4 versions of ZSH. By default, Network
Shell calls the 4_3_4 version of ZSH. If you want to access the older version of ZSH,
do the following:

NOTE
HP-UX platforms do not support ZSH 4.3.4. The default ZSH version on HP-UX remains 4.0.4.
The following functionality described in the NSH man page only applies to the default zsh
4.3.4 (zsh-4_3_4) based Network Shell executable. When using the older zsh 4.0.4 (zsh) based
Network Shell executable, the following behavior will not be present.

The ability to use fully qualified paths to specify execution of native commands when
those commands have Network Shell equivalents.

The implicit nexec of a native command on a remote host.

1 Cd to <BladeLogic install directory>\bin. By default, this is C:\Program Files\BMC


Software\BladeLogic\8.0\NSH\bin on Windows and
/opt/bmc/BladeLogic/8.0/NSH/bin on UNIX.
2 Do one of the following:

On UNIX, enter the following commands:


mv nsh nsh-4_3_4
ln s zsh nsh

On Windows, do the following:


A. Rename the existing "nsh.exe" executable to "nsh-4_3_4.exe".
B. Copy the "zsh.exe" executable to "nsh.exe".

BMC BladeLogic Network Shell Command Reference Manual

Shared memory segments requirements

Shared memory segments requirements


On a server where multiple users run Network Shell, assure there is at least N * X
shared memory segments available, where N is the number of simultaneous Network
Shell login sessions and X is the number of times the chrole command is executed
during the Network Shell session lifetime.

Summarized descriptions of commands


The following table provides a brief description of all Network Shell commands and
utilities.
Network Shell
Command

Description

agentctl

Controls the functions of an RSCD agent.

agentinfo

Provides information about an RSCD agent.

autolic

Licenses RSCD agents using a web service.

awk

Scans files for specified patterns.

bl_gen_ssl

Creates an X.509 certificate.

bl_srp_agent

Activates a user information cache on UNIX.

blcred

Manages authentication profiles, session credentials, and


trusted certificates.

blexpr

Creates and evaluates an expression based on input in the form of


arguments.

blkeylogman

Remotely manages keystroke logfiles on a machine running an RSCD


agent.

bllogman

Remotely manages live RSCD agent logfiles.

blquery

Extends the functionality of blexpr by providing functions that are


able to query the asset types supported by the BMC BladeLogic
environment.

bzip2

Utility for compressing files using the Burrows-Wheeler block sorting


text compression algorithm, and Huffman coding. Compression is
generally considerably better than that achieved by more conventional
compressors.

cat

Concatenates and prints files.

chapw

Sets or changes the agent password on one or more Windows servers


that have the BMC BladeLogicRSCD agent running.

chgrp

Changes group (and user) ownership of files.

chmod

Changes the mode (protection attributes) of a file.

chown

Changes user (and group) ownerships of files.

chrole

Changes the current role.

Introduction

Summarized descriptions of commands

Network Shell
Command

Description

cksum

Display file checksums and block counts.

cmp

Compares the content of two files checking to see if they are identical.

colrm

Removes columns from a file.

comm

Selects or rejects lines common to two files.

compress

Compresses data.

cp

Copies files.

csv2xml

Converts data in a comma-separated value format to XML format.

cut

Selects portions of each line of a file.

daalinfo

Displays an overview of the local DAAL registry.

dd

Converts and copies a file.

diff

Compares the differences between files and directories.

df

Executes a remote df command.

dsync

Synchronizes two directories.

du

Displays disk usage information for files.

echo

Echoes arguments.

expand

Expands tabs to spaces.

fields

Extracts specified fields from a data row.

file

Determines file type.

find

Walks a file hierarchy.

fold

Filters the contents of files to limit line length.

fqdn

Prints fully qualified domain name of the current or specified host.

funzip

Extracts files from a ZIP archive in a pipe.

getlic

Gets remote license data from RSCD agents.

grep

Searches files and selects lines matching specified patterns.

head

Displays the first few lines of a file.

hexdump

Performs an ASCII, decimal, hexadecimal, or octal dump.

hgrep

Highlights the results of a grep.

hostname

Prints the name of the current host.

join

Provides a relational database operator.

lam

Outputs files side by side.

less

Displays files on a CRT.

lesskey

Specifies key bindings that are used by the less command.

link

Creates a link to a file.

ln

Creates a link to a file.

ls

Lists the contents of a directory.

man

Get man pages from a remote host.

md5sum

Calculate the MD5 checksum of files.

mkdir

Create directories.

BMC BladeLogic Network Shell Command Reference Manual

Summarized descriptions of commands

Network Shell
Command

Description

mkfifo

Creates a named pipe.

mknod

Creates a special file.

mv

Moves or renames files.

ncp

Copies/synchronizes multiple sources to multiple destinations.

ncpu

Displays CPU information.

ndf

View usage statistics from one or more hosts.

ndircmp

Compares contents of multiple directories.

ndsync

Copies/synchronizes multiple sources to multiple destinations.

nexec

Provides an interface for running remote commands.

nlogin

Log in to a remote host.

nmem

View memory and swap statistics from one or more hosts.

nnet

Displays network adaptor configuration data for one or more servers.

nohup

Invokes a command immune to hangups.

nover

Displays a system overview in a standardized format independent of


the servers operating system.

nprocsum

Displays process summary from one or more hosts.

nps

Displays process information from one or more hosts.

nsh

Outlines the differences between Network Shell and other shells.

NSH-Perl

Describes the use of the Network Shell Perl module.

nshopt

Tests different network write buffer sizes.

nshpath

Shows the path where an nsh executable resides.

nstats

Displays a system overview in a standardized format independent of


the servers operating system.

ntop

Provides a collection of commands used to view information and


statistics for one or more servers.

nukecert

Removes certificates from servers.

nunzip

Decompresses or compresses files.

order

Sorts a list of strings (or lines) in a specified order.

paste

Merges corresponding or subsequent lines of files.

pax

Reads and writes file archives and copies directory hierarchies.

pkgadd

Provides a Network Shell wrapper to the pkgadd command.

pr

Print files.

prune

Prunes log files to a specified size.

putcert

Pushes a certificate generated by bl_gen_ssl to one or more servers.

putlic

Uses raw licensing data to license remote RSCD agents. Used in


conjunction with getlic.

redi

Redirects input to a file.

renice

Alters the priority of running processes.

rm

Removes a file.

Introduction

Summarized descriptions of commands

10

Network Shell
Command

Description

rmdir

Removes an empty directory.

rscd

Describes the Remote System Call Daemon (the RSCD agent).

rsu

Runs an NSH command with alternate privileges.

runcmd

Runs a Network Shell command on one or more hosts.

runscript

Runs a Network Shell script on one or more hosts.

scriptutil

Copies and executes scripts on remote servers.

sdiff

Compares the differences between files and directories side-by-side.

secadmin

Defines encryption security when modifying the secure file.

sed

Provides a stream editor.

sort

Sorts or merges text files.

split

Splits a file into pieces.

strings

Finds printable strings in a file.

su

Substitutes a user identity.

tail

Outputs the last part of files.

tar

Reads and writes file archives and copies directory hierarchies.

tee

Copies standard input to standard output, making copies of the input.

test

Tests the value of an expression.

touch

Changes the last update and modification times of a file.

tr

Translates or deletes characters.

uname

Prints the operating system name.

uncompress

Expands compressed data.

uncp

Uncopies files that were backed up during a cp or dsync.

unexpand

Replaces spaces with tabs (see also expand).

uniq

Reports or filters out repeated lines in a file.

unlink

Unlinks a file and/or directory.

unzip

Lists, tests, and extracts compressed files in a ZIP archive.

unzipsfx

Provides a self-extracting stub for prepending to ZIP archives.

uuencode

Encodes a binary file.

uudecode

Decodes a binary file.

version

Tells what version of BMC BladeLogic software is installed on a server.

vi

Provides a text editor.

vsh

Starts a shell and captures input and output.

vshview

Views the log files created by vsh.

vtree

Shows the directory structure of a file system.

wc

Counts the number of lines, words, and/or characters in a file.

zcat

Expands compressed data. (zcat is an alias for uncompress.)

zip

Packages and compresses (archives) files.

zipcloak

Packages and compresses (archives) files.

BMC BladeLogic Network Shell Command Reference Manual

Complete descriptions of commands

Network Shell
Command

Description

zipgrep

Searches files in an archive for lines matching a pattern.

zipinfo

Lists detailed information about an archive.

zipnote

Packages and compresses (archives) files.

zipsplit

Packages and compresses (archives) files.

zshall

Provides man pages for Network Shells preferred command


interpreter, the Z shell.

Complete descriptions of commands


The following pages provide complete documentation for all commands and utilities
available in Network Shell other than the BMC BladeLogic configuration files. To
view documentation for a particular command, use Adobe Acrobat to click on the
bookmark for that command. When viewed in Acrobat, bookmarks are listed
alphabetically on the left.

Introduction

11

Property of BladeLogic, Inc.


Strictly confidential and proprietary

agentctl(1)

agentctl(1)

NAME
agentctl Control the functions of an RSCD agent

SYNOPSIS
agentctl [-b] [-f] [-q] [-r] [-v] \
list | start | stop | kill | restart | exec cmd [args]

DESCRIPTION
The agentctl command lets you control the running of the RSCD agent.
This command is part of the agent distribution and controls only the agent on the local machine. You cannot
control remote agents with this command. (Note that you can use the nexec command to remotely control
the server agent.)
The following actions are supported:
list

List the current agent processes that are running. This list uses a style similar to the UNIX ps
command.

start

Start the agent on the local server. If the agent is already running, then a warning message is output and the operation is aborted unless you specified the -f or -r options.
On UNIX systems, you must have root privileges to use this command. Otherwise the agent will
not start.
On Windows systems the BladeLogic RSCD Agent service is started.

stop

Stop all RSCD agent processes on the local machine. If no agent processes are running, a corresponding warning message is output.
On UNIX systems, when a sub-agent starts, it creates a new process group. When you issue the
stop command, a SIGHUP (hangup) is first sent to all processes in the respective process groups,
followed by a SIGINT (interrupt) one second later, followed by a SIGKILL (-9) one second later
again. This hopes to allow processes to gently exit before they are forcefully terminated.
On Windows systems, the BladeLogic RSCD Agent service is stopped.

kill

The option is similar to the stop command, except that on UNIX systems it does not try to gently
terminate the processes, but rather just sends the SIGKILL (-9) to each respective process group.
This option is recommended only when you need to halt immediately.

restart

This option is a combination of doing a stop followed by a start. This is not just a convenience
command -- the restart command also lets you restart an agent remotely, using the nexec command, as described below.
Once you issue a stop command, a remote start is no longer possible, because the agent is no
longer running to service the nexec command. However, the restart command has been specifically designed to survive the agent going down while restart is still running. restart accomplishes this by changing its own process group ID, which allows it to run independently of the
agent. To use this functionality, invoke restart with the -b option. For example, to remotely
restart an agent, use the following syntax:
nexec hostname agentctl -b restart
The agentctl command attempts to automatically determine if its parent process is an agent. If it
determines that its parent process is an agent, it automatically turns on the -b option.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

agentctl(1)

exec

agentctl(1)

This option is similar to the restart command, but with the added ability to execute a given command between the stop and the start.

OPTIONS
-b

When performing a restart create a new sub-process with a separate process group ID to do the
actual work and just exit. This operation is necessary to be able to remotely restart an agent,
because stopping an agent will also stop all sub-processes of the same process group ID.
agentctl will attempt to automatically determine if its parent process is an agent. If it determines
that its parent process is an agent, it automatically turns on the -b option.

-f

When starting an agent, either through the start, restart, or exec command, the default is not to
start the agent if agentctl detects than an agent is already running. With this option, agentctl will
always try to start the agent.

-q

Quiet mode. With this option, agentctl does not output warning messages. stdin, stdout, and
stderr are all redirected from/to /dev/null (UNIX) or nul (Windows), so that no messages are displayed when the agent is started.

-r

Pass the -r option to the agent (UNIX only). The agent -r option tells the agent to retry (approximately every 10 seconds) listening on the effective TCP port, if the port is already being listened
on.

-v

Verbose option. With this option, agentctl generates more output to let you know what the program is doing.

EXAMPLES
sol8dev# agentctl list
HOSTNAME USER PID CPU MEM VSIZE RSS PRI START TIME COMMAND
sol8dev root 6086 0.0 0.8 4520 1840 0 14:45:15 0:00 rscd
sol8dev root 6085 0.0 1.2 4656 2968 0 14:45:15 0:00 rscd
sol8dev# agentctl -v stop
Stopping pid 6086 ...
Stopping pid 6085 ...
Stopping pid 8488 ...
sol8dev# agentctl restart
agentctl: Warning - RSCD agent currently not running
rscd - Copyright (C) 1996-2003, BladeLogic Inc.
sol8dev# nexec winhost agentctl -b restart

EXIT VALUES
agentctl exits with a value of 0 if the requested operation was fulfilled without any problems or issues. Otherwise it exits with a non zero value.

ORIGIN
agentctl was written by Thomas Kraus

SEE ALSO
rscd(1).

NSH

agentinfo(1)

agentinfo(1)

NAME
agentinfo Output information about remote RSCD agents.

SYNOPSIS
agentinfo [-?] [-c] [-H] [-f file] [hostname ...]

DESCRIPTION
The agentinfo command gives an overview of generally important information about a remote agent.
agentinfo outputs the information in the following manner:
Agent Release
:
Hostname
:
Operating System:
User Permissions:
Host ID
:
# of Processors :
License Status :

6.3.0.160
solarishost
SunOS 5.8
4507/51 (tmk/sw)
80F8EC76
1
Expires Mon May 12 14:58:38 2005

Note that, by design, the number of processors reported by agentinfo does not consider hyperthreading. If
you need CPU counts which account for hyperthreading, use either the ncpu or nover commands.
With no arguments, agentinfo outputs data about the current remote host. If the current directory is on the
local host, agentinfo displays a message to that effect. You can also specify the names or I.P. addresses of
the hosts for which you want information. Put a space between each host name.

OPTIONS
-?

Displays a general usage message.

-c

Tells agentinfo to output the data in a CSV (comma separated value) format. By default, the CSV
file includes a header line. You can turn off the header line with the -H option. When you use the
-c option, the name that appears under the "Hostname" column is the actual server name that you
passed to the agentinfo command, and not necessarily the real hostname of the server.

-H

Do not output a header.

-f filename
A flat file containing the names or I.P. addresses of the hosts for which you want information. List
one host per line.
hostname
The names or I.P. addresses of the hosts for which you want information. Put a space between
each host name.

EXAMPLE
Display information about the current remote host.
nsh% cd //linuxhost/
linuxhost% agentinfo
Agent Release
: 6.3.0.160
Hostname
: linuxhost
Operating System: Linux 2.4.2-2
User Permissions: 4507/51 (tmk/man)
Host ID
: 44434057
# of Processors : 1
License Status : Licensed for NSH, Configuration Manager
Display information about multiple hosts.
nsh% agentinfo solarishost windowshost

NSH

agentinfo(1)

agentinfo(1)

solarishost:
Agent Release
:
Hostname
:
Operating System:
User Permissions:
Host ID
:
# of Processors :
License Status :
windowshost:
Agent Release
:
Hostname
:
Operating System:
User Permissions:
Host ID
:
# of Processors :
License Status :

6.3.0.160
solarishost
SunOS 5.8
4507/51 (tmk/sw)
80F8EC76
1
Expires Mon May 12 14:58:38 2005
6.3.0.160
windowshost
WindowsNT 5.0
SYSTEM
F454127F
1
Licensed for NSH, Configuration Manager

ORIGIN
The agentinfo utility was written by Thomas Kraus.

SEE ALSO
ncpu (1), nover (1), version(1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

autolic(1)

autolic(1)

NAME
autolic License RSCD agents via web service

SYNOPSIS
autolic [-luexvV] [-f file] [-c count] user password [host1 ... hostn]
autolic [-proxyHost <host>] [-proxyPort <port>] [-proxyUser <user>] [-proxyPass <pass>]

DESCRIPTION
The autolic command lets you license RSCD agents in a single step via the BladeLogic licensing web service. Previously the licensing of an agent consisted of three steps:
1

Run the getlic command to gather data required for licensing.

Login to the BladeLogic support website, upload the license file created by the getlic command, and then download the generated license.dat file.

Apply the licenses with the putlic command.

The autolic command combines these three steps into a single non-interactive step.

OPTIONS
The following four options allow you to select a subset of hosts based on their current license status. You
can specify more than one option. If you do not include any of these four options, autolic processes all the
hosts you specify, regardless of their license status.
-l

Display license information for hosts that currently have a valid permanent license.

-u

License hosts that are currently un-licensed.

-e

License hosts that currently have a valid evaluation (timed) license.

-x

License hosts that currently have an expired evaluation license.

Other options include:


user

Your registered username on the BladeLogic support website.

password
Your registered password for the above user on the BladeLogic support website.
-c <count>
The number of CPUs in the license request.
-v

Verbose output detailing individual steps.

-V

Debug output. In most cases, do not use this option.

-f filename
Instead of listing your hosts one at a time on the command line as arguments, you can use this
option to point to a file containing a list of hosts for which you want license information. List one
host per line.
host1 ... hostn
List of hosts for which you want to retrieve license information.
-proxyHost host
Hostname of the proxy server
-proxyPort port
Port to connect to on the proxy server
-proxyUser user
User to connect to the proxy server as
-proxyPass pass
Password to use to connect to the proxy server

NSH

autolic(1)

Property of BladeLogic, Inc.


Strictly confidential and proprietary

autolic(1)

USAGE
host $ autolic -u username
bombay
: Licensed for
madras
: Licensed for
bagalore
: Licensed for

password bombay madras bagalore


NSH/CM
NSH/CM
NSH/CM

PROXY
If you need to go through a proxy, you must update the autolic configuration file called share/autolic.conf
(from the NSH install directory). Running the following command will Add/Modify the entries in
autolic.conf:
host $ autolic -proxyHost proxy.mycompany.com -proxyPort \
8080 -proxyUser username -proxyPass password
#
# Proxy information
#
proxyhost=proxy.mycompany.com
proxyport=8080
proxyuser=username
proxypassword=password
Adjust values as required. If you are going through a non-authenticating proxy, do not set the proxyuser
and proxypassword entries.

CAVEATS
You cannot select the license type (evaluation or permanent). Instead, the BladeLogic licensing server
automatically determines the license type, based on the your current customer/prospect status.
For autolic to function properly, the host from which you launch autolic must have Internet access through
port 80. If Internet access is not available or if port 80 is blocked (for example, by a firewall), then use the
getlic and putlic commands described above to license your agents.

ORIGIN
autolic was written by Thomas Kraus

SEE ALSO
getlic(NSH), putlic(NSH), agentinfo(NSH).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

awk(1)

awk(1)

NAME
awk - pattern-directed scanning and processing language

SYNOPSIS
awk [-safe] [-V] [-d[n]] [-F fs] [-v var=value] [prog | -f progfile] file ...
nawk ...

DESCRIPTION
Awk scans each input file for lines that match any of a set of patterns specified literally in prog or in one or
more files specified as -f progfile. With each pattern there can be an associated action that will be performed
when a line of a file matches the pattern. Each line is matched against the pattern portion of every patternaction statement; the associated action is performed for each matched pattern. The file name - means the
standard input. Any file of the form var=value is treated as an assignment, not a filename, and is executed at
the time it would have been opened if it were a filename.
The options are as follows:
-d[n]

Debug mode. Set debug level to n, or 1 if n is not specified. A value greater than 1 causes awk to
dump core on fatal errors.

-F fs

Define the input field separator to be the regular expression fs.

-f filename
Read program code from the specified file filename instead of from the command line.
-safe

Disable file output (print >, print >>), process creation (cmd | getline, print |, system) and access
to the environment (ENVIRON; see the section on variables below). This is a first (and not very
reliable) approximation to a safe version of .

-V

Print the version number of awk to standard output and exit.

-v var=value
Assign value to variable var before prog is executed; any number of -v options may be present.
The input is normally made up of input lines (records) separated by newlines, or by the value of RS. If RS
is null, then any number of blank lines are used as the record separator, and newlines are used as field separators (in addition to the value of FS). This is convenient when working with multi-line records.
An input line is normally made up of fields separated by whitespace, or by the regular expression FS. The
fields are denoted $1, $2, ..., while $0 refers to the entire line. If FS is null, the input line is split into one
field per character.
Normally, any number of blanks separate fields. In order to set the field separator to a single blank, use the
-F option with a value of [ ]. If a field separator of t is specified, awk treats it as if had been specified
and uses <TAB> as the field separator. In order to use a literal t as the field separator, use the -F option
with a value of [t].
A pattern-action statement has the form
pattern { action }
A missing { action } means print the line; a missing pattern always matches. Pattern-action statements are
separated by newlines or semicolons.
Newlines are permitted after a terminating statement or following a comma (,), an open brace (()), a logical AND (&&), a logical OR (||), after the do or else keywords, or after the closing parenthesis of an
if , for, or while statement. Additionally, a backslash () can be used to escape a newline between
tokens.
An action is a sequence of statements. A statement can be one of the following:
if (expression) statement [else statement]
while (expression) statement
for (expression; expression; expression) statement
for (var in array) statement

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

awk(1)

awk(1)

do statement while (expression)


break
continue
{ [statement ...]}
expression # commonly var = expression
print [expression-list][>expression]
printf format [..., expression-list][>expression]
return [expression]
next # skip remaining patterns on this input line
nextfile # skip rest of this file, open next, start
delete array[expression]# delete an array element
delete array # delete all elements of array
exit [expression]# exit immediately; status is expression
Statements are terminated by semicolons, newlines or right braces. An empty expression-list stands for $0.
String constants are quoted "", with the usual C escapes recognized within (see printf(1) for a complete list
of these). Expressions take on string or numeric values as appropriate, and are built using the operators + * / % (exponentiation), and concatenation (indicated by whitespace). The operators ! ++ -- += -= *= /=
%= = > >= < <= == != ?: are also available in expressions. Variables may be scalars, array elements
(denoted x[i]) or fields. Variables are initialized to the null string. Array subscripts may be any string, not
necessarily numeric; this allows for a form of associative memory. Multiple subscripts such as [i,j,k] are
permitted; the constituents are concatenated, separated by the value of SUBSEP (see the section on variables below)).
The print statement prints its arguments on the standard output (or on a file if >file or >>file is present or on
a pipe if | cmd is present), separated by the current output field separator, and terminated by the output
record separator. file and cmd may be literal names or parenthesized expressions; identical string values in
different statements denote the same open file. The printf statement formats its expression list according to
the format (see printf(3)).
Patterns are arbitrary Boolean combinations (with ! || &&) of regular expressions and relational expressions. Regular expressions are as in egrep(1). Isolated regular expressions in a pattern apply to the entire
line. Regular expressions may also occur in relational expressions, using the operators and !. /re/ is a constant regular expression; any string (constant or variable) may be used as a regular expression, except in the
position of an isolated regular expression in a pattern.
A pattern may consist of two patterns separated by a comma; in this case, the action is performed for all
lines from an occurrence of the first pattern through an occurrence of the second.
A relational expression is one of the following:
expression matchop regular-expression
expression relop expression
expression in array-name
(expr, expr, ...) inarray-name
where a relop is any of the six relational operators in C, and a matchop is either (matches) or ! (does not
match). A conditional is an arithmetic expression, a relational expression, or a Boolean combination of
these.
The special patterns BEGIN and END may be used to capture control before the first input line is read and
after the last. BEGIN and END do not combine with other patterns.
Variable names with special meanings:
ARGC

Argument count, assignable.

ARGV

Argument array, assignable; non-null members are taken as filenames.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

awk(1)

awk(1)

CONVFMT
Conversion format when converting numbers (default "%.6g").
ENVIRON
Array of environment variables; subscripts are names.
FILENAME
The name of the current input file.
FNR

Ordinal number of the current record in the current file.

FS

Regular expression used to separate fields; also settable by option -F fs.

NF

Number of fields in the current record. $NF can be used to obtain the value of the last field in the
current record.

NR

Ordinal number of the current record.

OFMT

Output format for numbers (default "%.6g").

OFS

Output field separator (default blank).

ORS

Output record separator (default newline).

RLENGTH
The length of the string matched by the match() function.
RS

Input record separator (default newline).

RSTART
The starting position of the string matched by the match() function.
SUBSEP
Separates multiple subscripts (default 034).

FUNCTIONS
The awk language has a variety of built-in functions: arithmetic, string, input/output and general.
Arithmetic Functions
atan2(y, x)
Return the arctangent of y/x in radians.
cos(x)

Return the cosine of x, where x is in radians.

exp(x)

Return the exponential of x.

int(x)

Return x truncated to an integer value.

log(x)

Return the natural logarithm of x.

rand()

Return a random number, n, such that 0<=n<1.

sin(x)

Return the sine of x, where x is in radians.

sqrt(x)

Return the square root of x.

srand(expr)
Sets seed for rand() to expr and returns the previous seed. If expr is omitted, the time of day is
used instead.
String Functions
gsub(r, t, s)
The same as sub() except that all occurrences of the regular expression are replaced. gsub()
returns the number of replacements.
index(s, t)
The position in s where the string t occurs, or 0 if it does not.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

awk(1)

awk(1)

length(s)
The length of s taken as a string, or of $0 if no argument is given.
match(s, r)
The position in s where the regular expression r occurs, or 0 if it does not. The variable RSTART
is set to the starting position of the matched string (which is the same as the returned value) or
zero if no match is found. The variable RLENGTH is set to the length of the matched string, or -1
if no match is found.
split(s, a, fs)
Splits the string s into array elements a[1], a[2], ..., a[n] and returns n. The separation is done with
the regular expression fs or with the field separator FS if fs is not given. An empty string as field
separator splits the string into one array element per character.
sprintf(fmt, expr, ...)
The string resulting from formatting expr, ... according to the printf(3) format fmt.
sub(r, t, s)
Substitutes t for the first occurrence of the regular expression r in the string s. If s is not given, $0
is used. An ampersand (&) in t is replaced in string s with regular expression r. A literal ampersand can be specified by preceding it with two backslashes (\). A literal backslash can be specified by preceding it with another backslash (\). sub() returns the number of replacements.
substr(s, m, n)
Return at most the n-character substring of s that begins at position m counted from 1. If n is
omitted, or if n specifies more characters than are left in the string, the length of the substring is
limited by the length of s.
tolower(str)
Returns a copy of str with all upper-case characters translated to their corresponding lower-case
equivalents.
toupper(str)
Returns a copy of str with all lower-case characters translated to their corresponding upper-case
equivalents.
Input/Output and General Functions
close(expr)
Closes the file or pipe expr. expr should match the string that was used to open the file or pipe.
cmd | getline [var]
Read a record of input from a stream piped from the output of cmd. If var is omitted, the variables
$0 and NF are set. Otherwise var is set. If the stream is not open, it is opened. As long as the
stream remains open, subsequent calls will read subsequent records from the stream. The stream
remains open until explicitly closed with a call to close().
fflush(expr)
Flushes any buffered output for the file or pipe expr. expr should match the string that was used to
open the file or pipe.
getline

Sets $0 to the next input record from the current input file. This form of getline sets the variables
NF, NR, and FNR. getline returns 1 for a successful input, 0 for end of file, and -1 for an error.

getline var
Sets $0 to variable var. This form of getline sets the variables NR and FNR. getline returns 1 for a
successful input, 0 for end of file, and -1 for an error.
getline [var] < file
Sets $0 to the next record from file. If var is omitted, the variables $0 and NF are set. Otherwise
var is set. If file is not open, it is opened. As long as the stream remains open, subsequent calls
will read subsequent records from file. file remains open until explicitly closed with a call to
close().

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

awk(1)

awk(1)

system(cmd)
Executes cmd and returns its exit status.
Functions may be defined (at the position of a pattern-action statement) thusly:
function foo(a, b, c) { ...; return x }
Parameters are passed by value if scalar, and by reference if array name; functions may be called recursively. Parameters are local to the function; all other variables are global. Thus local variables may be created by providing excess parameters in the function definition.

EXAMPLES
Print lines longer than 72 characters:
length($0) > 72
Print first two fields in opposite order:
{ print $2, $1 }
Same, with input fields separated by comma and/or blanks and tabs:
BEGIN { FS = ",[ ]*|[ ]+" }
{ print $2, $1 }
Add up first column, print sum and average:
{ s += $1 }
END { print "sum is", s, " average is", s/NR }
Print all lines between start/stop pairs:
/start/, /stop/
Simulate echo(1):
BEGIN { # Simulate echo(1)
for (i = 1; i < ARGC; i++) printf "%s ", ARGV[i]
printf "0
exit }
Print an error message to standard error:
{ print "error!" > "/dev/stderr" }

SEE ALSO
egrep(1), lex(1), printf(1), sed(1), printf(3)
A. V. Aho, B. W. Kernighan, and P. J. Weinberger, The AWK Programming Language, Addison-Wesley,
1988, ISBN 0-201-07981-X.

HISTORY
An awk utility appeared in Version 7 AT&T UNIX.

BUGS
There are no explicit conversions between numbers and strings. To force an expression to be treated as a
number add 0 to it; to force it to be treated as a string concatenate "" to it.
The scope rules for variables in functions are a botch; the syntax is worse.

COPYRIGHT
/****************************************************************
Copyright (C) Lucent Technologies 1997
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

awk(1)

awk(1)

granted, provided that the above copyright notice appear in all


copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name Lucent Technologies or any of
its entities not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

bl_gen_ssl(1)

bl_gen_ssl(1)

NAME
bl_gen_ssl create an X.509 certificate

SYNOPSIS
bl_gen_ssl

DESCRIPTION
The bl_gen_ssl command creates an X.509 certificate in a file named id.pem. Creating this certificate
generates a users public and private keys. Invoking bl_gen_ssl prompts the user to enter a password and
confirm it. This password is used to gain access to users private key.
Once a certificate is created on a client, every time a Network Shell session is invoked, the user is prompted
for a private key password.
On UNIX, id.pem is stored in /<home_dir>/.bladelogic, where <home_dir> is the users
home directory, such as /home/johnk.
In Windows, id.pem is stored in /<user_profile_dir>/Application Data/BladeLogic,
where <user_profile_dir> specifies a path such as /Documents and Settings/johnk.

OPTIONS
None

EXAMPLE
bl_gen_ssl

ORIGIN
bl_gen_ssl was developed by BladeLogic, Inc.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

bl_srp_agent(1)

bl_srp_agent(1)

NAME
bl_srp_agent activate a user information cache on UNIX

SYNOPSIS
bl_srp_agent --background

DESCRIPTION
The bl_srp_agent command activates a user information cache on UNIX. When you run bl_srp_agent,
the system prompts for a user ID, password, and role. After you provide this information, the system generates a message like the following:
set BL_SRP_INFO to <xy> to reuse this private key.
where <xy> is the hexadecimal value of the location of the shared memory segment. After entering your
user information, bl_srp_agent runs in the background with the user information cached in a shared memory segment. This shared memory segment is only usable for the user who ran bl_srp_agent.
To reuse this shared memory segment with Network Shell, set the BL_SRP_INFO environment variable by
issuing the following command:
BL_SRP_INFO=<xy>
Export the BL_SRP_INFO environment variable by issuing the following command:
export BL_SRP_INFO
The bl_srp_agent program remains in the background holding the user information cached in a shared
memory segment until you kill it.

OPTIONS
--background
Instructs bl_srp_agent to run in the background. If you do not use this option, bl_srp_agent runs
in the foreground. Other programs can use the information cached by bl_srp_agent whether
bl_srp_agent is running in the foreground or background.

EXAMPLE
bl_srp_agent --background

ORIGIN
bl_srp_agent was developed by BladeLogic, Inc.

NSH

blcred(1)

blcred(1)

NAME
blcred A command line utility for managing BMC BladeLogic authentication profiles, session credentials, and trusted certificates.

SYNOPSIS
blcred [-p <authentication profiles filename>]
[-c <credential cache filename>]
[-x <trusted certificates keystore filename>]
[cred -list [-verbose] |
-destroy |
-acquire [-profile <profile_name>]
[[-username <username>] |
[-password <password>]] |
[-i <srp user_info.dat file>] |
[-loginconf <kerberos login.conf file>] |
[-krb5conf <krb5.conf>] |
-test [-profile <profile_name>]
[-username <username>]
[-time <min remaining lifetime (minutes)]] |
[authprofile -list |
-delete [-profile <profile name>] |
-add [-profile <profile name>]
[-host <auth_service host>:<auth_service port>]
[-type [srp |
domainauth |
adk |
ldap [-dnt <distinguished name template>] |
securid |
pki]] |
[cert -list |
-add [-host <hostname>:<port>] [-protocol [tls | ldap]] |
-import <certificate in PEM or DER formatted file> |
-delete [-all | -alias <cert alias>]
[config pki [-provider <provider-library>]]]

DESCRIPTION
The blcred utility manages authentication profiles, session credentials, and trusted certificates.
To use blcred on a client machine, you must have Operations Manager installed.
To log into a BMC BladeLogic system, a user must first acquire a session credential from a BladeLogic
Authentication Service. Using that session credential, a BMC BladeLogic client application (i.e., Configuration Manager, Provisioning Manager, Network Shell, or BLCLI) can connect to a BMC BladeLogic
Application Server or Network Shell Proxy Server.
To obtain a session credential from an Authentication Service, you must provide an authentication profile
and other information. The authentication profile identifies the Authentication Service you are contacting
and your authentication mechanism.
If you are using SRP authentication, you must also provide a user name and password.
If you are using Active Directory/Kerberos authentication, you must also possess an AD/Kerberos user credential (that is, a Kerberos TGT).
If you are using Domain Authentication, you must also provide a fully qualified user name, such as
sally@SUB1.QA.COMPANY.COM, unless you are defined as a member of the default realm. For example,
if SUB1.QA.COMPANY.COM is the default realm, the user sally can simply enter a user name of sally. For
information on how to set up the default realm for Domain Authentication, see the BMC BladeLogic
Administration Guide. Note that when entering a fully qualified user name, the domain name must always

NSH

blcred(1)

blcred(1)

be capitalized.
If you are using LDAP authentication, you must also provide your LDAP distinguished name and a password.
If you are using SecurID authentication, you must also provide a user name and a password. For SecurID,
the password includes two pieces: a PIN and a token code, as displayed on the users SecurID token.
If you are using PKI authentication, you must insert a smart card into a smart card reader.
For any of the authentication types, blcred prompts you for any information you have omitted.
Based on the type of authentication profile and the user information you provide, the Authentication Service validates you as a user and issues a session credential. This session credential is stored in the credential cache file.
The blcred utility lets you acquire a session credential when using a command line environment. The utility lets you test whether a valid session credential already exists and determine the lifetime remaining for
that credential. The utility lets you show, add, and delete authentication profiles. And, blcred lets you
review, add, import, and delete trusted X.509 certificates, which are used when establishing a TLS connection to an Authentication Service, Application Server, Network Shell Proxy Server, or LDAP server. You
can add X.509 certificates to a trust store by retrieving them from a BMC BladeLogic Application Server or
LDAP Server. You can import X.509 certificates to the trust store from a PEM or DER file.

COMMAND OPTIONS
-p <authentication profiles filename>
Name and location of the authentication profile configuration file, which is an XML file that
holds all authentication profile definitions. This option overrides whatever is specified by the
BL_AUTH_PROFILES_FILE environment variable. If neither this option nor the
BL_AUTH_PROFILES_FILE environment variable is specified, the default authentication profile
configuration file is used. This default file resides at <BladeLogic install directory>/NSH/br/
authentication-Profiles.xml
-c <credential cache filename>
Name and location of the credential cache file. This option overrides whatever is specified by the
BL_SSO_CRED_CACHE_FILE environment variable. If neither this option nor the
BL_SSO_CRED_CACHE_FILE environment variable is specified, the default credential cache
file is used. This file resides at <user_home_dir>/.bladelogic/bl_sesscc for UNIX and C:\Documents and Settings\<Windows_user_name>\Application Data\BladeLogic\bl_sesscc for Windows. Default credential caches are unique per user.
-x <trusted certificates keystore filename>
Name and location of the keystore file, which holds trusted X.509 certificates. To acquire a session credential, blcred establishes a TLS connection to the Authentication Service, which
presents its X509 certificate to the client. The user is prompted to trust the unrecognized certificate. This option overrides whatever is specified by the BL_SSO_TRUSTED_CERT_KEYSTORE_FILE
environment
variable.
If
neither
this
option
nor
the
BL_SSO_TRUSTED_CERT_KEYSTORE_FILE environment variable is specified, the default
keystore file is used. The default keystore file resides at <user_home_dir>/.bladelogic/client_keystore.pkcs12
for
UNIX
and
C:\Documents
and
Settings\<Windows_user_name>\Application Data\BladeLogic\client_keystore.pkcs12 for Windows. Default
trust keystores are unique per user.
cred list [-verbose]
Displays credential information, including the user name, authentication type, issuing service
URL, expiration time, and maximum lifetime of session credentials. Using the optional -verbose
argument causes the utility to display the service ticket.
cred destroy
Destroys the contents of the credential cache.

NSH

blcred(1)

blcred(1)

cred acquire [-profile <profile_name>][[-username <username>] [-password <password>]] | [-i <srp


user_info.dat file>] | [-loginconf <kerberos login.conf file>] | [-krb5conf <krb5.conf>]
Acquires a session credential using the specified profile and stores it in the session credential
cache. When employing an AD/Kerberos profile, the users Kerberos credential is loaded from
the local Kerberos cache. When selecting an SRP, LDAP, SecurID, or Domain Authentication
profile, the user is prompted for a user name and password. For Domain Authentication, the
users domain should be included as part of the user name, such as user@KRBDOMAIN.COMPANY.COM. For SRP, LDAP, SecurID, and Domain Authentication, both the user name and
password can be passed on the command line using the optional -username and -password parameters. Alternatively, an SRP credential can be extracted from a persistent credential file (the
user_info.dat) using the -i parameter. When an AD/Kerberos profile is employed, the -loginconf
parameter can be used to override the default location of the blclient_login.conf file and the
-krb5conf parameter can be used to override the blclient_krb5.conf file specified in the config.properties file.
The optional -profile argument overrides whatever is specified by the BL_AUTH_PROFILE_NAME environment variable. If neither the -profile option nor the BL_AUTH_PROFILE_NAME environment variable is specified, blcred prompts the user to specify an authentication profile name.
cred test [-profile <profile_name>] [-username <username>] [-time <min remaining lifetime (minutes)]
Tests whether a cache contains a valid credential corresponding to the specified authentication
profile. If an authentication profile name is not specified, blcred prompts the user to provide a
profile name. If the user name option is present, blcred tests for the presence of a valid credential
issued to the named user. If the time option is present, blcred tests for the presence of a valid credential with a remaining lifetime equal to or greater than the specified minutes remaining.
blcred test can return the exit codes described below in EXIT CODES.
authprofile list
Displays information about each of the profiles defined in the authentication profile configuration
file.
authprofile delete [-profile <profile_name>]
Deletes a profile with the given profile name. If a name is not specified, the user is prompted for a
name.
authprofile add [-profile <profile name>] [-host <auth_service host>:<auth_service port>] [-type [srp |
domainauth | adk | ldap [-dnt <distinguished name template>] | securid | pki]]
Adds a new profile to the authentication profile configuration file. There are various types of
authentication profiles: SRP, Domain Authentication, AD/Kerberos, LDAP, SecurID, and public
key infrastructure (PKI). In all cases the profile must have a unique name and must be associated
with an Authentication Service.
LDAP profiles can include a distinguished name template, which allows users to enter only the
unique portion of their LDAP distinguished name when logging in.
There are two types of AD/Kerberos authentication profiles: Domain Authentication (specified
with the domainauth option) and AD/Kerberos (specified with the adk option). For Domain
Authentication, users must provide a Kerberos user name, domain, and password when logging
in. The domain should be included as part of the users name, such as user@KRBDOMAIN.COMPANY.COM.
The profile name, Authentication Service, and authentication type can be specified on the command line through the -profile, -host, and -type parameters. Additionally, the LDAP distinguished
name template can be specified using the dnt parameter. Users are prompted for omitted information.
SecurID, Domain Authentication, AD/Kerberos, and SRP profiles do not require any additional
setup information. For AD/Kerberos, however, you must set up the blclient_login.conf and

NSH

blcred(1)

blcred(1)
blclient_krb5.conf files. For more information on this process, see the BMC BladeLogic Administration Guide.
Users authenticating with PKI must insert a smart card into the smart card reader. Users must also
run the blcred config pki command to generate a PKCS11 configuration file. You only need to
generate this file once. If you have previously logged in successfully with Configuration Manager
using PKI, this file will already exist.

cert list Lists all X.509 certificates in the trusted certificate store.
cert add [-host <hostname>:<port>] [-protocol [tls | ldap]]
Adds X.509 certificates to the clients trusted certificate store by connecting to a remote system
and retrieving the certificate. When specifying the remote system you must provide a host name
and a port number. When using this option to add an X.509 certificate, you have a choice of two
protocols: TLS or LDAP (through StartTLS). Use the TLS protocol when retrieving a certificates
from a BMC BladeLogic Application Server. Use the LDAP protocol when retrieving a certificate
from an LDAP server. Only the end entity certificate can be retrieved with the add parameter.
All intermediate (CA) certificates are discarded.
cert import <certificate PEM file>
Imports X.509 certificates from a PEM or DER file that you specify using a local path.
cert delete [-all | -alias <cert alias>]]
Deletes X.509 certificates in the trusted certificate store. The -all parameter deletes all certificates.
The -alias lets you provide an alias for the certificate you want to delete. (Use the -list option to
obtain aliases for all certificates in the store.)
config pki [provider <provider-library>]
Creates a configuration file that relates the configuration of a card reader and its ActivClient middleware to the BMC BladeLogic client software. This file identifies the location of the pkcs11
DLL file and the pkcs11 slot to which the card reader is attached.
The <provider-library> option refers to the DLL file provided with ActivClient. It also provides
the PKCS11 interface for BladeLogics version of PKCS11. The default value for <providerlibrary> is C:\Windows\system32\acpkcs211.dll.
Caveats for using this command:
A smart card must be in the card reader for this command to function correctly.
If you have more than one card reader attached to your machine, blcred will choose the first one.
If you change slots for the card reader, you must run this command again.

EXIT CODES
0

Successful test result; cache contained credential with desired properties.

Named authentication profile did not exist.

Cached credential did not match named authentication profile.

Cached credential issued to user is different than named user.

Lifetime remaining for the cached credential is less than minimum lifetime specified.

EXAMPLES
See the BMC BladeLogic Administration Guide for some typical scenarios that use blcred.

ENVIRONMENT VARIABLES
BL_AUTH_PROFILES_FILE
Location of the authentication profile configuration file (override with -p).

NSH

blcred(1)

blcred(1)

BL_SSO_CRED_CACHE_FILE
Location of the session credential cache file (override with -c).
BL_SSO_TRUSTED_CERT_KEYSTORE_FILE
Location of the trusted certificate store (override with -x).
BL_AUTH_PROFILE_NAME
Name of the selected BMC BladeLogic authentication profile (override using the -profile option
in conjunction with another option, such as -acquire -profile profile_name.)

ORIGIN
blcred was developed by BMC Software, Inc.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blexpr(1)

blexpr(1)

NAME
blexpr BladeLogic Expression

SYNOPSIS
blexpr expr ...

DESCRIPTION
blexpr is generic expression evaluator. It takes all of its arguments as input, then creates and evaluates an
expression. It prints the result to stdout. If you do not specify any arguments, blexpr reads the expression
from stdin.
An expression consists of operands and operators. You can nest these (multiple levels) using parentheses (
and ).

OPERATORS
blexpr supports the following operators. Lower priorities have higher precedence:
Operator
%
/
*
+
>
>=
!=
=
<=
<
!
&&
||
&
|

Name
REMAINDER
DIVIDE
MULTIPLY
SUBTRACT
ADD
GREAT
GREAT THAN OR EQUAL
NOT EQUAL
EQUAL
LESS THAN OR EQUAL
LESS
NOT
AND
OR
BINARY AND
BINARY_OR
BINARY_XOR
BINARY NOT

Priority
1
1
1
2
2
3
3
3
3
3
3
4
5
6
6
6
6
6

OPERANDS
blexpr supports the following operands:
Operand
nnn
0nnn
nnn%
nn.mm
0xABC
a.b.c.d
"abc"
abc
$name
function()

Name
Decimal Number
Octal Number
Percentage
Floating point number
Hex Number
I.P. address (converted to integer)
String supporting \ for special characters
String (no special character support)
Variable name (see set_variable() function)
Supported function.

You can use whitespaces (SPACE, TAB, CR, LF) as optional operand/operator separators.

OPERATOR TYPES
blexpr supports the following operator types:
Integers

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blexpr(1)

blexpr(1)

Floating point numbers


64 bit integers
Strings
Here are some examples of how blexpr handles operations between two different operator types. In the
case of the three numeric types, blexpr will make the appropriate conversions as necessary. If one operator
is a floating point value and the other is an integer or a 64 bit integer then blexpr converts the integer values
to floating point, with the resulting value also being a floating point value.
If one value is a 64 bit integer and the other is regular integer value then blexpr converts the (regular) integer value to a 64 bit integer, with the result also being a 64 bit integer value.
blexpr handles operations between a string and a non-string value such that the operation does not just
automatically fail. When blexpr encounters an operation between a string and a non-string value, it first
checks to see if the string is a recognizable numeric value. If it is, blexpr converts the string to the respective numeric type, then proceeds with the operation. If the string is not a recognizable numeric value, then
blexpr returns an appropriate error value.

FUNCTIONS
blexpr also supports functions to determine operand values. The supported functions are:
average (arg1, ...)
Return the average of all arguments given. blexpr adds the arguments, then divides by the number of arguments.
Example:
$ blexpr average (1, 2, 3, 4)
2
$ blexpr average (1, 2, 3.0, 4)
2.5000
atoi (val)
Convert val into an integer value. If the argument is a string, then this function uses the same
function as the internals of the API to detect a numeric value. It detects octal numbers (strings
starting with a zero), hex numbers (strings starting with 0x), decimal numbers, and floating point
numbers. The function also checks for a trailing % which will cause the value to be treated as a
percentage (meaning divide by 100). If atoi cannot convert val to an integer, it returns 0 (false).
Example:
$ blexpr atoi ("4") * atoi (3.14)
12
equals_any (val, arg1, arg2, ...)
This function returns true (value of 1) if val equals any of the remaining function arguments.
Example:
$ blexpr equals_any (atoi ("3.14"), 1, 3, 5)
1
$ blexpr equals_any (atoi ("3.5") * 2, 5, 7)
0
equals_range (val, min_val, max_val)
This functions returns true (value of 1) if the value of val is greater than or equal to the value of
min_val and less than or equal to the value of max_value.
Example:
$ blexpr equal_range (strlen ("Hello world"), 7, 12)
1

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blexpr(1)

blexpr(1)

get_date ()
This function returns the date and time on the local system. The date and time is expressed as the
value in seconds since the epoch (00:00:00 Jan 1 1970). Use the show_date () function to turn
this value into a more meaningful string format.
Example:
$ blexpr get_date ()
1060378146
$ blexpr show_date (get_date ())
Tue Jan 14 11:56:02 2003
if (val, true_val, false_val)
The if function evaluates the value of val. If val is true, it returns true_val, otherwise it returns
false_val
Example:
$ blexpr if (atoi ("3"), 14, 27)
14
printf (format, args ...)
sprintf (format, args ...)
Both these functions generate a formatted output. The printf function just prints the output to
stdout and returns the number of bytes it wrote, while the sprintf function returns the formatted
output as a string.
The functions work in a similar way to the C-library printf function call but without all the bells
and whistles.
The functions support the following argument types:
string (%s)
floating point (%f)
integer
The functions support the following output format types:
decimal (%d)
unsigned int (%u)
octal (%o)
hex (%x or %X)
I.P. address notation (%p or %P)
The functions also support left justification with the optional - after the % as well as output precision in the
form of n[.m].
Example:
$ blexpr sprintf ("%12.9s", "Hello " + "world")
Hello wor
$ blexpr
set_variable ("FIRSTNAME", "Peter");
set_variable ("LASTNAME", "Pan");
sprintf ("Name = -- %s %s --\n", $FIRSTNAME, $LASTNAME)
Name = -- Peter Pan -$ blexpr set_variable ("IP", 10.20.30.40);
printf ("ADDRESS:\n DEC = %11u\n HEX = %11X\n

NSH

IP

= %p\n",

blexpr(1)

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blexpr(1)

$IP, $IP, $IP);


ADDRESS:
DEC =
169090600
HEX =
A141E28
IP = 10.20.30.40
set_variable (string, expr)
You can use the set_variable function to create an addressable variable. You define the name of
the variable with string, and you define the value of the variable with expr.
Once you have created a variable this way, you can use the variable in a subsequent expression by
prefixing the variable name with a $ symbol.
Example:
$ blexpr
set_variable ("FOO", "bar");
$FOO
bar
$ blexpr
set_variable ("FOO", "Hello " + "world");
toupper ($FOO)
HELLO WORLD
show_date (date, format)
This function takes the numeric date argument and converts it into a string representation. The
optional format arguments specifies output format. The function uses the C-library strftime
function to convert the value and therefore, you should use the respective macros supported by
the call. If you do not specify a format, then the generated date is in the form of Fri Nov
08:31:22 2001.
Example:
$ blquery -h linux -e show_date (get_date())
Tue Jan 14 11:56:02 2003
$ blquery -h win2k -e show_date (get_date (), "%b %d %Y %H:%M:%S")
Jan 14 2003 11:56:02
strstr (string, val)
strstr can be used in one of two ways. If val is a string then the function returns the first occurrence of val in the string. In val is of type integer then the function returns the string with an offset of val bytes.
Example:
$ blexpr strstr ("Hello world", "ll")
llo world
$ blexpr strstr ("Hello world", 6)
world
strlen (string)
Return the length of value string. If you supply a value that is not a string, strlen returns a
length of 0.
Example:
$ blexpr strlen ("Hello") + strlen ("World")
10$

NSH

blexpr(1)

blexpr(1)

toupper (string)
toupper converts a string into all uppercase. This can be useful when you want to compare two
strings in a case neutral way. If the value of the parameter is not a string then toupper returns the
value.
Example:
$ blexpr toupper ("Hello")
HELLO
$ blexpr toupper ("Hello") = toupper ("HeLlO")
1

SPECIAL CHARACTERS
In the context of a string defined using double quotes (") blexpr supports special characters. As you do in
the C language, you indicate these special characters with a preceding backslash (\). The special characters
are:
\\
\a
\b
\f
\n
\r
\t
\v

Backslash
Alert
Backspace
Form Feed
Newline
Carriage Return
TAB
vertical tab

ORIGIN
blexpr was written by Thomas Kraus

SEE ALSO
blquery (NSH), expr (1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blkeylogman(1)

blkeylogman(1)

NAME
blkeylogman remotely manage keystroke logfiles on a machine running an RSCD agent

SYNOPSIS
blkeylogman [GLOBAL_OPTION]... [COMMAND] [COMMAND_OPTION]... [TARGET]...
bllogkeyman [GLOBAL_OPTION]... [COMMAND] [COMMAND_OPTION]... [TARGET]...

DESCRIPTION
blkeylogman allows a system administrator to manage live keystroke logfiles on the RSCD agent to
accomplish basic tasks. blkeylogman provides a limited set of functionality that can be used in conjunction with existing, traditional logfile management systems to provide a complete solution.
There are four primary functions provided by blkeylogman, as follows:
list

List live keystroke logfiles for a specific host

copy

Copy remote keystroke logfiles

cat

Concatenate remote keystroke logfiles

listsessions

View a list of nexec sessions logged in remote keystroke logfiles

COMMANDS, COMMAND_OPTIONS, and TARGETS


list <hostname>
list --verify <hostname>|<keystrokelogfile>
List (and optionally verify) keystroke logfiles for host
--verify This option is useful only when you have enabled keystroke logging on a remote host,
and the resulting keystroke files have been digitally signed. This option displays the status of each keystroke file as either "Consistent", "Inconsistent", or "Unknown." An
"Inconsistent" status indicates that the log file may have been tampered with.
You can request the status of all the keystroke files on a host, or specify a full NSH path
to an individual keystroke file to request just that files status.
If the signature file needed for verification is missing on the target host, the status displays as "Unknown."
hostname
Name of host for which to list keystroke logfiles
keystroke_logfile
Full NSH Path to remote keystroke logfile. e.g. //<hostname>/<Path to keystroke logfile>
copy keystroke_logfile localfile
Copy remote keystroke logfile to local host
keystroke_logfile
Full NSH path to remote keystroke logfile. e.g. //<hostname>/<Path to keystroke logfile>
localfile Path to local file
cat [-t 0123] [-s <session id>] [-h <clienthost>]
[-u <clientuser>] [-a <time>] [-b <time>] [-p]
<hostname>|<keystroke_logfile>
Output remote logfile
-t

List specified type of entries. This option takes a combination of the following characters as input: 0 1 2 3

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blkeylogman(1)

blkeylogman(1)

0 Show STDIN entries


1 Show STDOUT entries
2 Show STDERR entries
3 Show STARTSESSION and ENDSESSION entries.
-s

Show entries for the session specified by <session id>

-h

Show entries for the specified client host

-u

Show entries for the specified client user

-a

Show entries where "entry timestamp" > "specified timestamp". The format of the
timestamp is "MM/DD/YY HH:MM:SS.mmm" or "MM/DD/YY HH:MM:SS"

-p

Process non-printable output characters before printing


Sometimes, if output of interactive commands is logged inside a keystroke log file,
executing a blkeylogman cat command causes the terminal to process and interpret
special terminal handling control characters (contained in the log data). As a result, the
display gets garbled or sometimes even cleared. Exercising the p option, makes blkeylogman process the special terminal control characters to printable ones.

-b

Show entries where "entry timestamp" < "specified timestamp". The format of the
timestamp is "MM/DD/YY HH:MM:SS.mmm" or "MM/DD/YY HH:MM:SS"

keystroke_logfile
Full NSH Path to remote keystroke log file
listsessions [-s <session id>] [-h <clienthost>]
[-u <clientuser>] [-a <time>] [-b <time>] <hostname>|<keystroke_logfile>
List all nexec sessions on a particular host or keystroke logfile
-s

Show the session specified by <session id>

-h

Show sessions for the specified client host

-u

Show sessions for the specified client user

-a

Show sessions that were in progress after specified timestamp. The format of the
timestamp is "MM/DD/YY HH:MM:SS.mmm" or "MM/DD/YY HH:MM:SS"

-b

Show sessions that were in progress before the specified timestamp. The format of the
timestamp is "MM/DD/YY HH:MM:SS.mmm" or "MM/DD/YY HH:MM:SS"

hostname
Name of the host whose sessions you want to list
keystroke_logfile
Full NSH path to remote keystroke logfile whose sessions you want to list. e.g. //<hostname>/<path to keystroke log file>

EXAMPLES
The following will cat the logfile "keystroke.log" on the remote host "host1":
$ blkeylogman cat //host1/usr/nsh/log/keystroke.log
To list all keystroke logfiles on host "linux1":
$ blkeylogman list linux1
To list all keystroke logfiles with verification status on host "solaris10":

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blkeylogman(1)

blkeylogman(1)

$ blkeylogman list --verify solaris10


To list only one log file with verification status on host "solaris10":
$ blkeylogman list --verify //solaris10/usr/nsh/log/keystroke.log2
To list nexec sessions on host "solaris10":
$ blkeylogman listsessions solaris10
To list nexec sessions from file "keystroke.log1" on host "solaris10":
$ blkeylogman listsessions //solaris10/usr/nsh/log/keystroke.log1

ORIGIN
blkeylogman was written by Rajesh Jangam of BladeLogic, Inc.

SEE ALSO
bllogman (1) exports (5)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

bllogman(1)

bllogman(1)

NAME
bllogman remotely manage live RSCD agent logfiles

SYNOPSIS
bllogman [GLOBAL_OPTION]... [COMMAND] [COMMAND_OPTION]... [TARGET]...
logman [GLOBAL_OPTION]... [COMMAND] [COMMAND_OPTION]... [TARGET]...

DESCRIPTION
bllogman allows a system administrator to manage live RSCD agent logfiles to accomplish basic tasks.
bllogman is not intended to be a feature-complete logfile management solution, but rather provides a limited set of functionality that can be used in conjunction with existing, traditional logfile management systems to provide a complete solution.
There are six primary functions provided by bllogman, as follows:
tail

Tail remote logfiles

copy

Copy remote logfiles or signature files

list

List live logfiles for a specific host

cat

Concatenate remote logfiles

rotate

Rotate remote logfiles or signature files

verify

Verify a digitally signed log file locally

GLOBAL OPTIONS
There are global options which affect all functions, and there are command-specific options affecting only
particular commands, as follows:
-?

Generate run-time usage

-v

Be verbose when performing functions

COMMANDS, COMMAND_OPTIONS, and TARGETS


tail [-f -v] target
Output the last part of a logfile
-f

Tail forever

-n n

Tail n lines

target

Name of remote logfile you want to tail

copy [-S] logfile|signature_file localfile


Copy remote logfile/signature_file to local host
-S

Indicates that the file you are copying is a signature file. Use only when copying a signature file.

logfile/signature_file
Full NSH path to remote logfile/signature_file
localfile Path to local file
cat [-1|-2] [-d] [-l file] <-h host> | logfile
Output remote logfile
logfile

Path to remote logfile

-1

Show INFO/INFO1 logfile entries only (default is all)

-2

Show INFO2 logfile entries only (default is all)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

bllogman(1)

bllogman(1)

-d

Output selected fields in tab separated values format

-h host

Show all logfiles for host

-l file

Create a tab delimited last entry timestamp file

-s file

Use the last entry timestamp file to determine start of searching

list [--verify] hostname


list --verify //hostname/Full_NSH_Path_To_logfile
List logfiles on a host
--verify This option is useful only when you have enabled secure agent logging on a remote
host, and the resulting log files have been digitally signed. This option displays the status of each log file as either "Consistent", "Inconsistent", or "Unknown."
An "Inconsistent" status indicates that the log file may have been tampered with.
You can request the status of all the log files on a host, or specify a full NSH path to an
individual log file to request just that files status.
If you have not enabled secure agent logging on the remote host, this option returns a
status as "Unknown."
hostname
Name of host for which to list logfiles
rotate [-S] logfile/signature_file
Rotate provides a simple, iterative rotation function which simply increments the filename extension by one until an available filename is found. For example, the rotate option will rename the
file "rscd.log" to "rscd.log.1," assuming "rscd.log.1" does not already exist.
-S

Indicates that the file you are rotating is a signature file. Use only when rotating a signature file.

logfile/signature_file
Full NSH path to remote logfile/signature_file
verify logfile signature_file certificate_file privatekey_file
Verify log file consistency at local host. To execute this command, you must have the corresponding signature file, certificate file, and private key file on the local host.
logfile

Full path to local log file.

signature_file
Full path to corresponding local signature file.
certificate_file
Full path to the local certificate file that was used to sign the log file.
privateKey_file
Full path to the local privateKey file that was used to sign the log file.
Note: All files needed for this command should be local. This command is intended to be used for
client side verification.

EXAMPLES
The following will cat the logfile "rscd.log" on the remote host "host1":
$ bllogman cat //host1/usr/nsh/log/rscd.log

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

bllogman(1)

bllogman(1)

To retrieve a list of tail-specific options and usage:


bllogman tail -h
For general usage:
bllogman -h
To list all logfiles on host "linux1":
bllogman list linux1
To list all logfiles with verification status on host "solaris10":
$ bllogman list --verify solaris10
To list only one log file with verification status on host "solaris10":
$ bllogman list --verify //solaris10/usr/nsh/log/rscd.log2
To copy a signature file from host solaris10 to local host:
$ bllogman copy -S //solaris10/usr/nsh/log/rscd.log.sig2
To tail forever (or watch) logfile "rscd.log" on host "sun1":
bllogman tail -f //sun1/usr/nsh/log/rscd.log
To rotate a signature file on host solaris10:
$ bllogman rotate -S //solaris10/usr/nsh/log/rscd.log.sig2
To verify the consistency of logfile "rscd.log3" against its corresponding signature file "rscd.log.sig3"
using the certificate stored in file "certificate.pem" and the private key stored in "privateKey.pem":
$ bllogman verify /usr/tmp/rscd.log3 /usr/tmp/rscd.log.sig3
/usr/tmp/certificate.pem /usr/tmp/privateKey.pem
All files need to be on the local host. You cannot use this command for remote logfiles.

NOTE
Logman was renamed bllogman as part of the 6.3.0 release. For backwards compatibility purposes a logman command is still included. logman is just a copy or symlink of bllogman. bllogman should be the preferred utility moving forward as logman may be fully removed in the future.

ORIGIN
bllogman was written by Damon Miller of BladeLogic, Inc.

SEE ALSO
exports (5)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

NAME
blquery Evaluate expression to query BladeLogic assets

SYNOPSIS
blquery [ -h -l ] [ host1 ... hostn | -f file ] { -e expr | -E file }

DESCRIPTION
The blquery utility is an extension to the blexpr utility. blquery provides additional functions that can
query various asset types in the BladeLogic environment.
You can query against the local host (see CAVEATS), or against any number of remote servers. To query
the local host, just omit any server names. If you specify server names, then blquery will query against
each of the given servers.
blquery works by applying the given expression to each host and then outputting the results to stdout. The
default output format for each server is:
hostname: value

OPTIONS
-l

Generate output only for hosts that resolve to true.

-h

Do not include the hostname as part of the output. Instead, output only the resulting value. This is
the default behavior if you specify only a single host.

host1 ... hostN


The hosts you want to query. In addition to specifying host names on the command line, you can
also use the -f option to specify a hosts file. If you do not specify a host name, blquery will
query the local server. See the CAVEATS section for limitations on local servers.
-f file

A flat file containing the list of hosts you want to query.

-e expr

Expression to run against the given hosts. To help avoid some of the shell special character handling issues, and the subsequent escaping thereof, you can also use the -E option to define a file
containing your expression.

-E file

A file containing the expression you want to run. To create comment lines, start them with a hash
(#) and blquery will ignore them. If file is a - then blquery reads input from stdin.

FILE AND DIRECTORY FUNCTIONS


file_is_directory (path)
This function returns 1 if the given path exists on the host and is a directory, otherwise it returns
0.
Example:
$ blquery -h solaris8 -e file_is_directory ("/etc")
1
$ blquery solaris8 -e file_is_directory ("/etc/passwd")
0
file_is_regular (path)
This function returns 1 if the given path exists on the host and is a regular file, otherwise it
returns 0.
Example:
$ blquery -h solaris8 -e file_is_regular ("/etc")
0
$ blquery solaris8 -e file_is_regular ("/etc/passwd")
1
file_is_symlink (path)
This function returns 1 if the given path exists on the host and is a symbolic link, otherwise it
returns 0.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

Example:
$ blquery -h solaris8 -e file_is_symlink ("/etc/passwd")
0
$ blquery solaris8 -e file_is_symlink ("/etc/hosts")
1
file_exists (path)
This function returns 1 if the given path exists on the host, otherwise it returns 0.
Example:
$ blquery -h solaris8 -e file_exists ("/etc/passwd")
1
$ blquery solaris8 -e file_exists ("/etc/PASSWD")
0
file_size (path)
This function returns the size of the file path. If the path does not exist or is not accessible it
returns the value of -1.
Example:
$ blquery -h solaris8 -e file_size ("/etc/passwd")
635
file_uid (path)
This function returns the paths ownership as a numeric UID. If the path does not exist or is not
accessible it returns the value of -1.
Example:
$ blquery -h solaris8 -e file_uid ("/etc/passwd")
0
file_gid (path)
This function returns the paths group ownership as a numeric GID. If the path does not exist or
is not accessible it returns the value of -1.
Example:
$ blquery -h solaris8 linux -e file_gid ("/etc/passwd")
solaris8: 3
linux: 0
file_mode (path)
This function returns the paths file permissions. If the path does not exist or is not accessible it
returns the value of -1.
Example:
$ blquery -h solaris8 linux -e \
sprintf ("0%o", file_mode ("/etc/passwd") & 07777)
solaris8: 0444
linux: 0644
file_md5sum (file)
This function returns the 32 byte string representation of the files MD5 checksum. If the file
does not exist then it returns a zero length string with the appropriate error set.
Example:
$ blquery -h solaris8 -e file_md5sum ("/etc/passwd")
f59c3bfa14ac178b4098e03f9afe64fe

SOFTWARE INSTALLATIONS
Although the various supported platforms all have their own concept of what a software package is, they
mostly support the general concept of software installations, patches, and bundles.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

The following three functions abstract this concept for the various platforms and will automatically adapt to
the type of server you are dealing with. Note that the concept of patches is not supported on RedHat Linux
systems, and that bundles are HP-UX specific.
patch_installed (patch)
This function will check if the software patch patch is installed on the given server.
Example:
$ blquery -h solaris8 -e patch_installed ("109608-*")
1
$ blquery -h win2k -e patch_installed ("Q811493")
1
package_installed (software)
This function will check if the software package software is installed on the given server.
Example:
$ blquery -h linux -e package_installed ("cracklib-2.7-8")
1
$ blquery -h win2k -e package_installed ("Norton AntiVirus*")
1
bundle_installed (software)
This function will check if the software bundle software is installed on the given server. Bundles
exist only on HPUX machines.
Example:
blquery -h authpux11agt3 -e bundle_installed ("Base*")
1
You can use the next three functions to scan/search through the list of
patches and software. These functions take an expression as their argument, where the following dynamic variables are initialized for each
software/patch entry.
NAME

Installable name

VERSION

Installable version

VENDOR

Installable vendor

DATE

Installable date of installation (0 if you do not know the date)

CATEGORY Installable software category (On AIX the install status)


DESCRIPTION
Installable short description
SIZE

Size of installable in KB (0 if you do not know the size)

All the above variables are of type string with the exception of SIZE which is an integer. Note that not all
platforms furnish all the above data, so the values are not guaranteed to be set.
You do not need to specify the type of machine you dealing with, because the function automatically determines the platform type at runtime.
patch_record_count (expr)
package_record_count (expr)
bundle_record_count (expr)
rpm_record_count (expr)
Return the number of installed patch/software/bundle/rpm components that match the expression
expr. All platforms support the concept of installed patches and software components (the names
however differ from OS to OS), with the exception of Linux, which does not support patches. The

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

concept of bundles however is supported only by HP-UX machines.


Because these functions scan through all entries, you can also use them for reporting. To do this,
include the printf call inside of the given expression.
Example:
#
# Number of hotfixes installed on Windows server
#
$ blquery win2k -e patch_record_count ()
25

#
# Show install date of the "cracklib" RPMS
#
$ cat expr.blq
package_record_count (NAME = "cracklib*" &&
printf ("%s - %s\n
Install date: %s\n\n",
NAME, DESCRIPTION,
if (DATE <= 0,
"Unknown install date", show_date (DATE, "%b %d %Y")))
$ blquery linuxdev -E expr.blq
cracklib-2.7-8 - A password-checking library.
Install date: Nov 16 2001
cracklib-dicts-2.7-8 - The standard CrackLib dictionaries.
Install date: Nov 16 2001
The following functions let you extract individual fields from a given piece of software.
patch_version (software)
package_version (software)
bundle_version (software)
rpm_version (software)
Return the softwares version number. Not all software has a version number. In this case, these
functions return a zero length string.
patch_latest (software)
package_latest (software)
bundle_latest (software)
rpm_latest (software)
Although specifically designed for Solaris patches, these functions may still have a universal
appeal. The idea is that because the patch name also incorporates a version number (which is also
stored in the VERSION field), you may have the same patch installed twice but with different
versions, making it seem like two different patches are installed. By using these functions, you
can find the name of the patch that has the highest version number.
Example:
$ cat patch.blq
patch_record_count
(NAME = "109793-*" &&
printf ("%s\n", NAME));
$ blquery solaris8 -E patch.blq

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

109793-12
109793-03
$ blquery solaris8 -e patch_latest ("109793-*")
109793-12
$ blquery solaris8 -e patch_version (patch_latest ("109793-*"))
12

CONFIG FILE FUNCTIONS


The following functions let you access the BladeLogic config files. The grammar to be used to scan a given
config file is automatically determined by consulting the index file. For UNIX and Linux systems, the file is
found in /usr/nsh/scripts. For Windows systems, the file is found in <install dir>/NSH/scripts.
Config files are generally treated as a series of sequential records that contain a number of fields. The first
record/field is 0.
The supported functions are:
config_record_count (configfile, expr)
This function returns the total number of records in the configfile that match the expression expr.
The expr argument is optional. If you omit the expression, the function returns the total number
of records.
Example:
#
# Number of records in password file
#
$ blquery -h solaris8 -e config_record_count ("/etc/passwd")
15
#
#
#
#
#
$

Field 5 is the HOME directory field and as such we are


finding all entries in the password file that have "/"
as the HOME directory and outputting their user names

blquery -h solaris8 -e
set_variable ("HOME", "/");
config_record_count ("/etc/passwd",
"$5 = $HOME && printf (\"%s\n\", $0)");
root
daemon
sys
nobody
noaccess
nobody4

config_record_number (configfile, expr, skip)


This function returns the record number of the first record in configfile that matches the expression expr. The skip parameter is optional. If you use it, it will skip over the first skip matched
records allowing one to find alternate records to the first matching one.
This function is often used with the config_field_value() function to identify the particular record
you need a field value for.
As its second parameter, this function accepts an expression that it matches against each record.
Because you often want to match against specific fields within a record, this function automatically recognizes and interprets specific variable names. The variable names matching the (string)
fields are $0, $1 ... $N for each respective field in the current record. The variable $RECORD
indicates the current record number you are dealing with. The variable $FIELDS indicates the
number of fields in the record.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

Example:
#
# Record number for first entry in the passwd file with a HOME
# directory of "/usr/bin"
#
$ blquery -h solaris8 -e \
config_record_number ("/etc/passwd", "$5 = \"/usr/bin\"")
2
#
# Scan the Windows INI file and get the value of the entry
# "Access" in the "connect CustomerDatabase" section
#
$ blquery -h win2k -e
set_variable ("INI",
"/c/WINNT/MSDFMAP.BNI");
set_variable ("ACCESS", "Access");
set_variable ("CUSTDB", "connect CustomerDatabase");
config_field_value ($INI,
config_record_number ($INI,
"($0 = $ACCESS) &&
(config_parent_field_value ($INI, $RECORD, 0) = $CUSTDB)"),
1)

ReadWrite
config_field_value (configfile, record, field)
This function returns the value of field field from record record of the config file configfile.
In many cases, records occur in a config file in no particular order. If you do not know the specific record number you need a field value from, then you can use the config_record_number ()
function to search for a particular record.
Example:
#
# Return the GCOS field of the first record in the
# passwd file
#
$ blquery -h solaris8 -e \
config_field_value ("/etc/passwd", 0, 4)
Super-User
#
#
#
#
#
$

Output the username of the first account in the


password file that has "/usr/bin" as its HOME
directory
blquery -h solaris8 -e
set_variable ("PASSWD", "/etc/passwd");
set_variable ("USRBIN", "/usr/bin");
config_field_value ($PASSWD,
config_record_number ($PASSWD, "$5 = $USRBIN"), 0)

bin

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

config_parent_field_value (configfile, record, field)


This function looks at the parent record of record record in the config file configfile, and returns
the value of field field. Although config files are generally treated as flat files, there is an implicit
hierarchy by which particular records may point to a parent record. Not all config files have a
hierarchy, but ones that do include Windows .BNI files and Linux Xinetd config files. On its own
this function has limited value, however you can use it in conjunction with the config_record_number() function to find particular records in a file.
Example:
#
# Scan the Windows INI file and get the value of the entry
# "Access" in the "connect CustomerDatabase" section
#
$ blquery -h win2k -e
set_variable ("INI",
"/c/WINNT/MSDFMAP.BNI");
set_variable ("ACCESS", "Access");
set_variable ("CUSTDB", "connect CustomerDatabase");
config_field_value ($INI,
config_record_number ($INI,
"($0 = $ACCESS) &&
(config_parent_field_value ($INI, $RECORD, 0) = $CUSTDB)"),
1)

ReadWrite
config_parent_record_number (configfile, record)
This function returns the parent record number of record record in the config file configfile. If
the function returns a negative number (-1), then the record does not have a parent record.
Example:
$ blquery -h win2k -e
config_parent_record_number ("/c/WINNT/MSDFMAP.BNI", 3)
2

LOCAL USER AND GROUP ACCOUNTS


These functions let you access local user and group accounts. These functions work cross platform (UNIX
type systems and Windows systems) however some of the available data may be OS specific. Details are
included below.
For the user based functions that take a expression as an argument, the following dynamic variable are supported.
NAME

The username.

GROUP

The name of the primary group the user is a member of.

UID

The numeric UID of the user.

GID

The numeric GID of the primary group the user is a member of.

FULLNAME The configured name of the user.


COMMENT The comment associated with the user account.
HOME

The users HOME directory.

SHELL

The users initial shell (UNIX) or script (Windows) program.

TYPE

This is the type of account which can be one of:

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

BUA_ADMIN_ACCOUNT (1)
On UNIX systems, accounts that are root (UID = 0) accounts are considered to
be of this type. On Windows systems, accounts that are Administrator
accounts are of this type.
BUA_NORMAL_ACCOUNT (2)
One UNIX systems, account have this type if they are not root accounts (UID
!= 0). On Windows systems, accounts that are Normal accounts are of this
type.
BUA_GUEST_ACCOUNT (3)
UNIX systems do not have the concept of guest user accounts and therefore
will never be of this type. On Windows systems, accounts that are Guest
accounts are of this type.
LASTLOGIN
The date and time of the users last login. If the date and time is not known this
value is 0. This value is expressed as a time in seconds since the epoch.
LASTCHANGE
The date and time of the users last password change. If the date and time is not
known this value is 0. This value is expressed as a time in seconds since the epoch.
EXPIRES

The date and time of the users password expiration. If the date and time is not
known this value is 0. This value is expressed as a time in seconds since the epoch.

GROUPS

This value is a space separated list of the groups to which the user belongs.

The supported functions are:


user_record_count (expr)
This function enumerates through all local user accounts and returns the number of users that
match the expression. expr.
Example:
blquery -e user_record_count ()
15
$ blquery -e user_record_count (
"printf (\"%-8s: %s (uid = %d)\n\",
NAME,
if (TYPE = BUA_ADMIN_ACCOUNT,
\"Super User Account\", \"Normal Account\"),
UID)");
root
: Super User Account (uid = 0)
daemon : Normal Account (uid = 1)
bin
: Normal Account (uid = 2)
sys
: Normal Account (uid = 3)
adm
: Normal Account (uid = 4)
lp
: Normal Account (uid = 71)
.
.
user_exists (user)
This function returns 1 if the given user exists as a local user account. If the local account does
not exist it returns 0.
Example:
$ blquery linux1 linux2 linux3 -e user_exists ("toor")
linux1: 1
linux2: 0
linux3: 1

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

user_uid (user)
This function returns the UID of the user. If the user does not exist then it returns an error message.
Example:
$ blquery linux1 linux2 linux3 -e user_uid ("toor")
linux1: 0
linux2: Bad argument type: Unknown local user "toor"
linux3: 2
user_gid (user)
This function returns the GID of the user. If the user does not exist then it returns an error message.
Example:
$ blquery solaris linux -e user_gid ("root")
solaris: 1
linux: 0
user_fullname (user)
This function returns the fullname associated with the user. On Windows, local user accounts
have such a field associated with the account and therefore, that field is returned. For UNIX systems the GECOS field is returned. If the user does not exist then this function returns an error
message.
Example:
$ blquery win2k solaris -e user_fullname ("Administrator")
win2k: Local Administrator Account
solaris: Bad argument type: Unknown local user "Administrator"
user_comment (user)
This function returns the comment associated with the user. On Windows, local user accounts
have such a field associated with the account and therefore, that field is returned. For UNIX systems the GECOS field is returned. Note that the user_fullname () and user_comment () functions also return the GECOS field for UNIX systems. If the user does not exist then this function
returns an error message.
Example:
$ blquery win2k -e user_comment ("Administrator")
win2k: Built-in account for administering the computer/domain
user_homedir (user)
This function returns the HOME directory of the user. On Windows this value is most often not
set and therefore has limited value. If the user does not exist, the function returns an error message.
Example:
$ blquery linux solaris -e user_homedir ("bin")
linux: /bin
solaris: /usr/bin
user_shell (user)
This function returns the start program (shell) for when the user logs in. On Windows this value
is most often not set and therefore has limited value. When it is set, the function refers to a start
script. If the user does not exist, the function returns an error message.
Example:
$ blquery linux solaris -e user_shell ("lp")
solaris: /bin/sh
linuxdev: /sbin/nologin

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

user_type (user)
This function returns the type of user account user is. There are three types of possible accounts:
, administrator, normal, and guest, with respective return values of 1, 2, or 3. For Windows,
account type is one of the inherent account properties while for Unix systsems an account is an
administrator account if the UID is 0. Otherwise it is a normal account. There are no guest
accounts for UNIX systems. If the user does not exist, the function returns an error message.
Example:
$ blquery linux solaris -e user_type ("root")
solaris: 1
linuxdev: 1
$ blquery win2k -e user_type ("Guest")
3
user_last_login (user)
This function returns the date and time of last login (as expressed in seconds since the epoch) of
user user. If the function cannot determine a date of last login for the user, the function returns 0.
To display the date of last login in human readable form, use the show_date () function.
Example:
$ blquery win2k -e user_last_login ("Guest")
1067983862
$ blquery solaris -e show_date (user_last_login ("root"))
Fri Feb 13 13:30:48 2004
user_locked (user)
This function returns value of 1 if the users account is locked, otherwise it returns 0. For Windows systems, these are inherent attributes of a user account. For UNIX systems, an account is
considered to be locked if you can unlock it without having to provide a new password.
Example:
$ blquery win2k -e user_locked ("Administrator")
0
$ blquery solaris -e user_locked ("Oracle")
1
user_group_names (user, sep)
This function returns a string representing a list of user groups to which the user belongs. The
optional argument sep must be a string whose first character will be used as the separator for the
list of values. The default separator is a SPACE character.
Example:
$ blquery solaris8 -e user_group_names ("root")
other root bin sys adm uucp mail tty lp nuucp daemon
user_group_gids (user, sep)
This function returns a string representing a list of GIDs to which the user belongs. The optional
argument sep must be a string whose first character will be used as the separator for the list of
values. The default separator is a SPACE character.
Example:
$ blquery solaris8 -e user_group_gids ("root", ",")
1,0,2,3,4,5,6,7,8,9,12
user_group_count (user)
This function returns the number of groups to which the user belongs.
Example:
$ blquery solaris8 -e user_group_count ("root")
11

NSH

10

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

For the group based functions that take an expression as an argument, the following dynamic variables are
supported.
NAME

The groupname.

GID

The numeric GID of the user.

COMMENT The comment string associated with the group.


MEMBERS

The users who are members of the group (space separated)

The group related functions are:


group_exists (group)
This function returns 1 if the given group exists as a local group account. If the local account
does not exist it returns 0.
Example:
$ blquery linux solaris win2k -e group_exists ("uucp")
linux: 1
solaris: 1
win2k: 0
group_record_count (expr)
This function returns the number of groups that match the expression expr.
Example:
blquery -e group_record_count ()
18
$ cat showgroups.blq
printf ("Group
GID\n");
printf ("-----------------\n");
group_record_count (printf ("%-10s %d\n", NAME, GID));
$ cat showgroups.blq | blquery solaris -E Group
GID
----------------root
0
other
1
bin
2
.
.
group_gid (group)
This function returns the GID of the given local user. group
Example:
$ blquery solaris -e group_gid ("other")
1
group_comment (group)
This function returns the comment field of the given local user group.

Example:
$ blquery win2k -e group_comment ("Administrators")
Administrators have complete and unrestricted access to the computer/dom
group_members (group, sep)
This function returns a string representing a list of users who are members of the given local user
group. The optional argument sep must be a string whose first character will be used as the separator for the list of values. The default separator is a SPACE character.
Example:

NSH

11

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

$ blquery solaris8 -e group_members ("uucp", ",")


root,uucp
group_member_count (group)
This function returns the number of users who are members of the local user group.
Example:
$ blquery win2k -e group_member_count ("Administrator")
6

NETWORK ADAPTERS
The following functions let you query against the configured network adapters and their respective settings.
All of these functions take an expression as an argument. This argument identifies the particular adapter
you want to query. Within these expressions, you can use the following dynamic variables.
NAME

The name of the adapter (for example "hme0")

MAC

The adapters MAC address. Each hex value is treated as a two character value
using lower case alpha characters.

IP

The adapters I.P. address in the standard 4 octet notation.

SUBNET

The adapters subnet mask in the standard 4 octet notation.

BROADCAST
The adapters broadcast address in the standard 4 octet notation.
IN

The number of bytes received by the adapter (supported only on Solaris and Linux)

OUT

The number of bytes sent by the adapter (supported only on Solaris and Linux)

The supported network functions are:


net_interface_name (expr)
This function enumerates the available adapters, and returns the name of the first interface that
matches the expression expr.
Example:
$ blquery solaris linux -e net_interface_name ("IP = \"10.20.30.*\"")
solaris: hme0
linux: eth0
net_mac_address (expr)
This function enumerates the available adapters, and returns the MAC address of the first interface that matches the expression expr.
Example:
$ blquery solaris8 -e net_mac_address ("NAME = \"hme0\"")
08:00:20:c1:d6:8c
net_ip_address (expr)
This function enumerates the available adapters, and returns the I.P. address of the first interface
that matches the expression expr as a string in the standard 4 octet notation.
Example:
$ blquery solaris8 -e net_ip_address ("NAME = \"hme0\"")
10.20.30.40
net_subnet_mask (expr)
This function enumerates the available adapters, and returns the subnet mask of the first interface
that matches the expression expr as a string in the standard 4 octet notation.
Example:
$ blquery solaris8 -e net_subnet_mask ("IP = \"10.20.30.40\"")
255.255.255.0

NSH

12

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

net_broadcast_address (expr)
This function enumerates the available adapters, and returns the broadcast address of the first
interface that matches the expression expr as a string in the standard 4 octet notation.
Example:
$ blquery solaris8 -e net_broadcast_address ("IP = \"10.20.30.40\"")
10.20.30.255
net_bytes_in (expr)
This function enumerates the available adapters, and returns the number of bytes received by the
first interface that matches the expression expr. The return value is a 64 bit integer. This function
returns useful information for Solaris and Linux servers only.
Example:
$ blquery solaris8 -e net_bytes_in ("NAME = \"hme0\"")
651703216
net_bytes_out (expr)
This function enumerates the available adapters, and returns the number of bytes sent by the first
interface that matches the expression expr. The return value is a 64 bit integer. This function
returns useful information for Solaris and Linux servers only.
Example:
$ blquery solaris8 -e net_bytes_in ("NAME = \"hme0\"")
330533685
net_flags (expr)
This function enumerates the available adapters, and returns the status flag for the first interface
that matches the expression expr. The status flag of an interface is a series of bits that may have
the following values (available only on Solaris)
1

The interface is running at a speed of 10Mb/sec.

The interface is running at a speed of 100Mb/sec.

The interface is running at a speed of 1000Mb/sec (1 Gb/sec).

32

The interface is running in half duplex mode.

64

The interface is running in full duplex mode.

Example:
$ cat speed.blq
set_variable ("FLAGS", net_flags (NAME = "hme0"));
printf
if
if
if

("SPEED
($FLAGS
($FLAGS
($FLAGS

=
&
&
&

%s/sec (%s)0,
1, "10 Mb",
2, "100 Mb",
4, "1Gb", "NA"))),

if ($FLAGS & 32, "Half Duplex",


if ($FLAGS & 64, "Full Duplex", "Auto")));
$ blquery solaris8 -E speed.blq
SPEED = 100 Mb/sec (Auto)
net_record_count (expr)
This function enumerates all available adapters and returns the number of adapters that match the
expression expr. If you do not specify expr, the function matches all adapters.

NSH

13

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

Example:
$ blquery solaris8 -e net_record_count ()
2
$ cat adapters.blq
printf ("INTERFACE
IP ADDRESS
SUBNET MASK\n");
net_record_count (printf ("%-10s %12s %15s\n", NAME, IP, SUBNET));
$ blquery solaris8 -E adapters.blq
INTERFACE
IP ADDRESS
SUBNET MASK
lo0
127.0.0.1
255.0.0.0
hme0
10.20.21.101
255.255.255.0

SYSTEM STATISTICS FUNCTIONS (NTOP VALUES)


blquery has a generic mechanism to access ntop data. It also has a series of pre-defined wrapper functions
where you do not need to know any ntop details to get the information. The wrapper functions are
described first, followed by the generic functions.
os_name ()
This function return the name of the operating system of each host.
Example:
$ blquery solaris8 linux win2k hpux11 -e os_name ()
solaris8: SunOS
linux: RedHat
win2k: WindowsNT
hpux11: HP-UX
os_release ()
This function return the OS release for each host.
Example:
$ blquery solaris8 linux win2k hpux11 -e os_release ()
solaris8: 5.8
linux: 7.1
win2k: 5.0
hpux11: B.11.00
os_patch ()
This function returns the maintenance release of the each host. Different operating systems deal
with this in different ways. On Linux, the function returns the kernel release number. On AIX,
the function returns the maintenance release. On Windows, the function returns the Service Pack.
Other platforms, such as Solaris and HPUX return a zero length string (meaning no value).
Example:
$ blquery -h solaris8 linux win2k -e os_patch ()
solaris8:
linux: 2.4.2-2
win2k: SP3
sys_cpu_count ()
This function returns the number of CPUs on the system.
Example:
$ blquery -h solaris8 linux win2k -e sys_cpu_count ()
solaris8: 4
linux: 2
win2k: 1

NSH

14

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

sys_cpu_speed ()
This function returns the CPU speed in MHz. Not all systems return a value.
Example:
$ blquery -h solaris8 linux win2k -e sys_cpu_speed ()
solaris8: 440
linux: 2386
win2k: 797
sys_memory ()
This function returns the total amount of main memory in MB as reported by the OS.
Example:
$ blquery -h solaris8 linux win2k -e sys_memory ()
solaris8: 256
linux: 128
win2k: 511
sys_swap ()
This function returns the total amount of swap space in MB as reported by the OS.
Example:
$ blquery -h solaris8 linux win2k -e sys_swap ()
solaris8: 513
linux: 258
win2k: 2047
stat_load_average ()
This function returns the systems load average as a floating point value.
Example:
$ blquery -h solaris8 linux win2k -e stat_load_average ()
solaris8: 0.0100
linux: 0.0300
win2k: 0.1400
stat_mem_capacity ()
This function returns the percentage of memory used on the system.
Example:
$ blquery -h solaris8 linux win2k -e stat_mem_capacity ()
solaris8: 0.5100
linux: 0.9100
win2k: 0.4100
stat_swap_capacity ()
This function returns the percentage of swap space used on the system.
Example:
$ blquery -h solaris8 linux win2k -e stat_swap_capacity ()
solaris8: 0.0100
linux: 0.0800
win2k: 0.1000
stat_proc_count ()
This function returns the number of processes running on the system.
Example:
$ blquery -h solaris8 linux win2k -e stat_proc_count ()
solaris8: 43
linux: 57
win2k: 38

NSH

15

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

stat_uptime ()
This function returns the number seconds that the machine has been running (meaning the number of seconds since it was booted).
Example:
$ blquery -h solaris8 linux win2k -e stat_uptime ()
solaris8: 2524551
linux: 598933
win2k: 107898
df_total (partition)
This function returns size in KB of the named partition.
Example:
$ blquery -h solaris8 linux win2k -e \
df_total (if (os_name () = "WindowsNT", "/C", "/usr"))
solaris8: 2056211
linux: 1035660
win2k: 39045982
df_used (partition)
This function returns the number of used blocks (in KB) of the named partition.
Example:
$ blquery -h solaris8 linux win2k -e \
df_used (if (os_name () = "WindowsNT", "/C", "/usr"))
solaris8: 775191
linux: 829532
win2k: 9579678
df_free (partition)
This function returns the number of free blocks (in KB) of the named partition.
Example:
$ blquery -h solaris8 linux win2k -e \
df_free (if (os_name () = "WindowsNT", "/C", "/usr"))
solaris8: 1281020
linux: 206128
win2k: 29466303
df_capacity (partition)
This function returns the percentage of used disk space of the named partition.
Example:
$ blquery -h solaris8 linux win2k -e \
df_capacity (if (os_name () = "WindowsNT", "/C", "/usr"))
solaris8: 0.3800
linux: 0.8000
win2k: 0.2500
The following functions are generic functions to access ntop data.
ntop_value (type, column, expr)
This function calls up the ntop data of type type (one of "PS", "DF", "STATS", "OVER", "NET",
or "MEM") and returns the value the field named by column of the first record that matches the
expression expr.
Column names are specific to the particular ntop data type. Check the individual ntop commands for more details. A quick guideline is that if you run the corresponding ntop command,
the first line of output consists of the column names. Some columns have a two word name. In
this case, use the first word of the name to identify the column.

NSH

16

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

The expression argument (third argument) is useful for ntop data that consists of more than a single output record (such as, "DF" and "PS"). If you specify an expression as a string, the function
will loop through all records and apply the expression to each record. When a record matches the
expression (expression evaluates to true), the function returns the appropriate field value (based
on column name). You may use column names to construct the expression. If the expression is a
numeric, the function considers the numeric to be the specific record number you want to access.
The first record is 0. Negative numbers tell the function to start looking from the back of the list
(for example, a value of -1 means the last record). If you do not specify an expression, the function returns the field value of the first record. If the function does not find any matching records,
it returns a value of -1.
Example:
#
# Same as stat_swap_capacity ()
#
$ blquery solaris8 linux -e ntop_value ("STATS", "SWAP")
solaris8: 0.1200
linux: 0.0100

#
# Same as calling df_capacity ("/usr")
#
$ blquery linux -e ntop_value ("DF", "CAPACITY", "MOUNTED = \"/usr\"")
linux: 0.3800
ntop_sum (type, column, expr)
This function returns the sum of a series of ntop fields (named by column) of type type that
match the expression expr. Records that do not match the expression are not included in the summary.
Column names and ntop data types are equivalent to the workings of the ntop_value function
(see above).
Example:
#
# For each server, the sum of memory usage (as %)
# of all apache processes
#
$ blquery linux1 linux2 linux3 -e
set_variable ("APACHE_USER",
"apache");
set_variable ("APACHE_PROCNAME", "*httpd*");
ntop_sum ("PS", "MEM",
"(USER = $APACHE_USER) && (COMMAND = $APACHE_PROCNAME)")

linux1: 0.1480
linux2: 0.0560
linux3: 0.0890
#
# For each server, the total amount of free disk space
#
$ blquery -h linux solaris8 win2k -e
sprintf ("Total free space on %-9s: %8.1f MB",
$HOSTNAME, ntop_sum ("DF", "FREE") / 1024.0)

Total free space on linux


:
7911.2 MB

NSH

17

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

Total free space on solaris8 :


Total free space on win2k
:

12101.8 MB
36208.0 MB

ntop_average (type, column, expr)


This function works just like the ntop_sum function with the exception that it returns the average
value of the matched entries instead of the sum of the values.
Example:
#
# Average free disk space of several servers
#
$ blquery -h linux solaris8 win2k -e
sprintf ("Average disk capacity on %-9s: %4.1f%%",
$HOSTNAME, ntop_average ("DF", "CAPACITY") * 100)

Average disk capacity on linux


: 45.4%
Average disk capacity on solaris8 : 13.1%
Average disk capacity on win2k
: 7.6%
ntop_record_count (type, expr)
This function returns the number of entries in the ntop data type that match the expression expr.
If expr is not given, then it return the total number of entries.
Example:
#
# Total number of processes running
#
$ blquery linux solaris8 win2k -e ntop_record_count ("PS")
linux: 46
solaris8: 48
win2k: 44
#
# Total number of java processes running
#
$ blquery linux solaris8 win2k -e
ntop_record_count ("PS", "COMMAND = \"*java*\"")
linux: 8
solaris8: 13
win2k: 16

WINDOWS REGISTRY FUNCTIONS


The following functions let you query a Windows registry. Registry paths must always be absolute including the root hive name (for example, "HKEY_LOCAL_MACHINE"). All registry key paths in Windows
are backslash (\) separated. Whenever you want to use a backslash in an expression string in NSH, you
need to escape it. Therefore, within an expression string, separate your registry key paths with two backslashes, for example: "HKEY_LOCAL_MACHINE\\SOFTWARE".
reg_key_exists (keypath)
This function returns 1 if the registry key keypath exists, otherwise it returns 0.
Example:
$ blquery win2k -e \
reg_key_exists ("HKEY_LOCAL_MACHINE\\SOFTWARE")
1

NSH

18

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

reg_value_exists (valpath)
This function returns 1 if the registry value valpath exists, otherwise it returns 0.
Example:
$ blquery -h win2k -e
reg_value_exists
("HKEY_LOCAL_MACHINE\\SOFTWARE\\INTEL\\CurrentLanguage")
1
reg_value (valpath)
This function returns the value of registry value valpath. If valpath is not a valid registry path
then the function returns -1. Since -1 is a possible valid value of a registry value, use this function
in conjunction with the reg_value_exists function to determine if the registry value exists.
Examples:
$ blquery -h win2k -e
reg_value
("HKEY_LOCAL_MACHINE\\SOFTWARE\\INTEL\\CurrentLanguage")
ENU
$ blquery -h win2k -e reg_value (
"HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Lsa\\bounds"
)
0030000000200000
Note, when storing the results of a reg_value command in a variable (as shown in the following
examples), you need to escape the backslashes (\) in the path of the registry value as follows:
Use two backslashes when using the $() form
Use four backslashes when using the form (back-tick form)
$ LANG=$(blquery -h win2k -e reg_value("HKEY_LOCAL_MACHINE
\\SOFTWARE\\INTEL\\CurrentLanguage"))
$ echo $LANG
$ ENU
$ LANG=blquery -h win2k -e reg_value("HKEY_LOCAL_MACHINE
\\\\SOFTWARE\\\\INTEL\\\\CurrentLanguage")
$ echo $LANG
$ ENU
The return type (for example, string, int, etc.) depends on the registry value type. The supported
types are:
REG_DWORD, REG_DWORD_BIG_ENDIAN
Returns a 32 bit integer value.
REG_SZ, REG_LINK, REG_EXPAND_SZ
Returns a string.
REG_MULTI_SZ
Returns a string containing all strings in the multi string space separated.
REG_NONE
Returns a zero length string.
REG_BINARY, and all others
Returns a string consisting of the hex values of each item in the array of values. Each hex value consists of two (zero filled) hex characters. There are no

NSH

19

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

spaces between the array values.

WINDOWS SERVICES FUNCTIONS


The following functions let you query Windows services. There are several functions that let you pass an
expression to find a matching service. These (sub) expressions support the following dynamic variable
names:
NAME

Name of service (short name).

DISPLAY

Display name of service (long name).

STATUS

One of "RUNNING", "STOPPED", or "PENDING".

STARTUP

One of "BOOT_START", "SYSTEM_START", "AUTO_START", "MANUAL", or


"DISABLED".

LOGON

Account name service is run as.

DESCRIPTION
Description of service.
PROGRAM

Name of executable used by service.

service_exists (name)
This function returns 1 if the Windows service name (as defined by the services display name)
exists. If accessing a non Windows server or if the service does not exist, the function returns 0.
Example:
$ blquery -h win2k -e service_exists ("MySql")
win2k: 1
service_running (service)
This function returns 1 if the named service exists and is currently running. service can be either
a string or an integer. In the case of a string, service is taken to be a service name (as defined by
the services display name). If service is an integer, it is taken to be a record number as returned
by service_record_number (). If the service does not exist, if it is not running, if you
specified an out of range record number, or if you are not accessing a Windows server then the
function returns 0.
Example:
$ blquery -h win2k -e service_running ("MySql")
1
#
# Check if the service that runs "mysqld-nt.exe" is running
#
$ blquery -h win2k -e
set_variable ("EXE", "*\\mysqld-nt.exe");
service_running (service_record_number ("PRORGAM = $EXE"))
1
service_record_count (expr)
This function returns the number of services that match the expression expr. If you do not specify expr, the function returns the total number of configured services. See the top of this section
for dynamic variable names and their possible values.
Example:
#
# Total number of services currently disabled
#
$ blquery win2k -e
set_variable ("DISABLED", "DISABLED");

NSH

20

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

service_record_count ("STARTUP = $DISABLED")


1
#
# Services summary
#
$ cat expr.blq
set_variable ("RUNNING", service_record_count (STATUS = "RUNNING"));
set_variable ("STOPPED", service_record_count (STATUS = "STOPPED"));
set_variable ("PENDING", service_record_count (STATUS = "PENDING"));
printf
printf
printf
printf

("Total services: %d\n", service_record_count ());


("
RUNNING: %d\n", $RUNNING);
("
STOPPED: %d\n", $STOPPED);
("
PENDING: %d\n", $PENDING);

$ blquery win2k -E expr.blq


Total services: 63
RUNNING: 35
STOPPED: 28
PENDING: 0
service_record_number (expr, skip)
This function returns the record number for the first service that matches the expression expr.
See the top of this section for dynamic variable names that can be used in this expression. Once
you get this record number, you can use it in other services functions, to access particular service
records. The optional skip parameter tells the function to skip the first skip number of matched
records.
This function is useful when you do not yet know the name of the service that you will be dealing
with.
Example:
#
# Find out if the service using the executable
# "mysqld-nt.exe" is running or not.
#
$ blquery -h win2k -e
set_variable ("EXE", "*\\mysqld-nt.exe");
service_running (service_record_number ("PRORGAM = $EXE"))

1
service_field_value (service, field)
This function returns the string value of a particular service field. field should be one of the following string values.
NAME

Returns the name of service (short name).

DISPLAY

Returns the display name of service (long name).

STATUS

Returns one of the following strings:"RUNNING", "STOPPED", or "PENDING".

STARTUP

Returns one of the following strings: "BOOT_START", "SYSTEM_START",


"AUTO_START", "MANUAL", or "DISABLED".

LOGON

Returns the account name service is run as.

DESCRIPTION
Returns the description of the service.

NSH

21

Property of BladeLogic, Inc.


Strictly confidential and proprietary

blquery(1)

blquery(1)

PROGRAM

Returns the name of the executable used by the service.

<other>

Returns zero length string.

The argument service can be either a string or an integer. In the case of a string, service is taken to be a service name (as defined by the services display name). If service is an integer, it is taken to be a record number as returned by service_record_number ().
Example:
#
# Get the name of the executable associated with
# the MySql service
#
$ blquery win2k -e service_field_value ("MySql", "PROGRAM")
C:\nsh\mysql\bin\mysqld-nt.exe
#
# The same again
#
$ blquery win2k -e
set_variable ("MYSQL", "MySql");
service_field_value (
service_record_number ("NAME = $MYSQL"),
"PROGRAM")

C:\nsh\mysql\bin\mysqld-nt.exe

CAVEATS
Windows Services queries against the local server are not supported.

NOTES
The blquery utility itself is a very short program. It just interfaces the underlying blquery API.

ORIGIN
blquery was written by Thomas Kraus

SEE ALSO
blexpr (NSH), ntop (NSH), ndf (NSH), nps (NSH), nmem (NSH), nover (NSH), nstats (NSH), nnet (NSH)

NSH

22

Property of BladeLogic, Inc.


Strictly confidential and proprietary

bl_srp_agent(1)

bl_srp_agent(1)

NAME
bl_srp_agent activate a user information cache on UNIX

SYNOPSIS
bl_srp_agent --background

DESCRIPTION
The bl_srp_agent command activates a user information cache on UNIX. When you run bl_srp_agent,
the system prompts for a user ID, password, and role. After you provide this information, the system generates a message like the following:
set BL_SRP_INFO to <xy> to reuse this private key.
where <xy> is the hexadecimal value of the location of the shared memory segment. After entering your
user information, bl_srp_agent runs in the background with the user information cached in a shared memory segment. This shared memory segment is only usable for the user who ran bl_srp_agent.
To reuse this shared memory segment with Network Shell, set the BL_SRP_INFO environment variable by
issuing the following command:
BL_SRP_INFO=<xy>
Export the BL_SRP_INFO environment variable by issuing the following command:
export BL_SRP_INFO
The bl_srp_agent program remains in the background holding the user information cached in a shared
memory segment until you kill it.

OPTIONS
--background
Instructs bl_srp_agent to run in the background. If you do not use this option, bl_srp_agent runs
in the foreground. Other programs can use the information cached by bl_srp_agent whether
bl_srp_agent is running in the foreground or background.

EXAMPLE
bl_srp_agent --background

ORIGIN
bl_srp_agent was developed by BladeLogic, Inc.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

bl_srp_agent(1)

bl_srp_agent(1)

NAME
bl_srp_agent activate a user information cache on UNIX

SYNOPSIS
bl_srp_agent --background

DESCRIPTION
The bl_srp_agent command activates a user information cache on UNIX. When you run bl_srp_agent,
the system prompts for a user ID, password, and role. After you provide this information, the system generates a message like the following:
set BL_SRP_INFO to <xy> to reuse this private key.
where <xy> is the hexadecimal value of the location of the shared memory segment. After entering your
user information, bl_srp_agent runs in the background with the user information cached in a shared memory segment. This shared memory segment is only usable for the user who ran bl_srp_agent.
To reuse this shared memory segment with Network Shell, set the BL_SRP_INFO environment variable by
issuing the following command:
BL_SRP_INFO=<xy>
Export the BL_SRP_INFO environment variable by issuing the following command:
export BL_SRP_INFO
The bl_srp_agent program remains in the background holding the user information cached in a shared
memory segment until you kill it.

OPTIONS
--background
Instructs bl_srp_agent to run in the background. If you do not use this option, bl_srp_agent runs
in the foreground. Other programs can use the information cached by bl_srp_agent whether
bl_srp_agent is running in the foreground or background.

EXAMPLE
bl_srp_agent --background

ORIGIN
bl_srp_agent was developed by BladeLogic, Inc.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

bzip2(1)

bzip2(1)

NAME
bzip2, bunzip2 a block-sorting file compressor, v1.0
bzcat decompresses files to stdout
bzip2recover recovers data from damaged bzip2 files

SYNOPSIS
bzip2 [ cdfkqstvzVL123456789 ] [ filenames ... ]
bunzip2 [ fkvsVL ] [ filenames ... ]
bzcat [ s ] [ filenames ... ]
bzip2recover filename

DESCRIPTION
bzip2 compresses files using the Burrows-Wheeler block sorting text compression algorithm, and Huffman
coding. Compression is generally considerably better than that achieved by more conventional
LZ77/LZ78-based compressors, and approaches the performance of the PPM family of statistical compressors.
The command-line options are deliberately very similar to those of GNU gzip, but they are not identical.
bzip2 expects a list of file names to accompany the command-line flags. Each file is replaced by a compressed version of itself, with the name "original_name.bz2". Each compressed file has the same modification date, permissions, and, when possible, ownership as the corresponding original, so that these properties
can be correctly restored at decompression time. File name handling is naive in the sense that there is no
mechanism for preserving original file names, permissions, ownerships or dates in filesystems which lack
these concepts, or have serious file name length restrictions, such as MS-DOS.
bzip2 and bunzip2 will by default not overwrite existing files. If you want this to happen, specify the f
flag.
If no file names are specified, bzip2 compresses from standard input to standard output. In this case, bzip2
will decline to write compressed output to a terminal, as this would be entirely incomprehensible and therefore pointless.
bunzip2 (or bzip2 d) decompresses all specified files. Files which were not created by bzip2 will be
detected and ignored, and a warning issued. bzip2 attempts to guess the filename for the decompressed file
from that of the compressed file as follows:
filename.bz2 becomes filename
filename.bz becomes filename
filename.tbz2 becomes filename.tar
filename.tbz becomes filename.tar
anyothername becomes anyothername.out
If the file does not end in one of the recognised endings, .bz2, .bz, .tbz2 or .tbz, bzip2 complains that it cannot guess the name of the original file, and uses the original name with .out appended.
As with compression, supplying no filenames causes decompression from standard input to standard output.
bunzip2 will correctly decompress a file which is the concatenation of two or more compressed files. The
result is the concatenation of the corresponding uncompressed files. Integrity testing (t) of concatenated
compressed files is also supported.
You can also compress or decompress files to the standard output by giving the c flag. Multiple files may
be compressed and decompressed like this. The resulting outputs are fed sequentially to stdout.

Property of BladeLogic, Inc.


Strictly confidential and proprietary

bzip2(1)

bzip2(1)

Compression of multiple files in this manner generates a stream containing multiple compressed file representations. Such a stream can be decompressed correctly only by bzip2 version 0.9.0 or later. Earlier versions of bzip2 will stop after decompressing the first file in the stream.
bzcat (or bzip2 -dc) decompresses all specified files to the standard output.
bzip2 will read arguments from the environment variables BZIP2 and BZIP, in that order, and will process
them before any arguments read from the command line. This gives a convenient way to supply default
arguments.
Compression is always performed, even if the compressed file is slightly larger than the original. Files of
less than about one hundred bytes tend to get larger, since the compression mechanism has a constant overhead in the region of 50 bytes. Random data (including the output of most file compressors) is coded at
about 8.05 bits per byte, giving an expansion of around 0.5%.
As a self-check for your protection, bzip2 uses 32-bit CRCs to make sure that the decompressed version of
a file is identical to the original. This guards against corruption of the compressed data, and against undetected bugs in bzip2 (hopefully very unlikely). The chances of data corruption going undetected is microscopic, about one chance in four billion for each file processed. Be aware, though, that the check occurs
upon decompression, so it can only tell you that something is wrong. It cant help you recover the original
uncompressed data. You can use bzip2recover to try to recover data from damaged files.
Return values: 0 for a normal exit, 1 for environmental problems (file not found, invalid flags, I/O errors,
&c), 2 to indicate a corrupt compressed file, 3 for an internal consistency error (eg, bug) which caused
bzip2 to panic.

OPTIONS
c --stdout
Compress or decompress to standard output.
d --decompress
Force decompression. bzip2, bunzip2 and bzcat are really the same program, and the decision
about what actions to take is done on the basis of which name is used. This flag overrides that
mechanism, and forces bzip2 to decompress.
z --compress
The complement to d: forces compression, regardless of the invokation name.
t --test
Check integrity of the specified file(s), but dont decompress them. This really performs a trial
decompression and throws away the result.
f --force
Force overwrite of output files. Normally, bzip2 will not overwrite existing output files. Also
forces bzip2 to break hard links to files, which it otherwise wouldnt do.
k --keep
Keep (dont delete) input files during compression or decompression.
s --small
Reduce memory usage, for compression, decompression and testing. Files are decompressed and
tested using a modified algorithm which only requires 2.5 bytes per block byte. This means any
file can be decompressed in 2300k of memory, albeit at about half the normal speed.
During compression, s selects a block size of 200k, which limits memory use to around the same
figure, at the expense of your compression ratio. In short, if your machine is low on memory (8
megabytes or less), use s for everything. See MEMORY MANAGEMENT below.

Property of BladeLogic, Inc.


Strictly confidential and proprietary

bzip2(1)

bzip2(1)

q --quiet
Suppress non-essential warning messages. Messages pertaining to I/O errors and other critical
events will not be suppressed.
v --verbose
Verbose mode -- show the compression ratio for each file processed. Further vs increase the verbosity level, spewing out lots of information which is primarily of interest for diagnostic purposes.
L --license -V --version
Display the software version, license terms and conditions.
1 to 9
Set the block size to 100 k, 200 k .. 900 k when compressing. Has no effect when decompressing.
See MEMORY MANAGEMENT below.
-

Treats all subsequent arguments as file names, even if they start with a dash. This is so you can
handle files with names beginning with a dash, for example: bzip2 - myfilename.

-repetitive-fast --repetitive-best
These flags are redundant in versions 0.9.5 and above. They provided some coarse control over
the behaviour of the sorting algorithm in earlier versions, which was sometimes useful. 0.9.5 and
above have an improved algorithm which renders these flags irrelevant.

MEMORY MANAGEMENT
bzip2 compresses large files in blocks. The block size affects both the compression ratio achieved, and the
amount of memory needed for compression and decompression. The flags 1 through 9 specify the block
size to be 100,000 bytes through 900,000 bytes (the default) respectively. At decompression time, the
block size used for compression is read from the header of the compressed file, and bunzip2 then allocates
itself just enough memory to decompress the file. Since block sizes are stored in compressed files, it follows that the flags 1 to 9 are irrelevant to and so ignored during decompression.
Compression and decompression requirements, in bytes, can be estimated as:
Compression: 400k + ( 8 x block size )
Decompression: 100k + ( 4 x block size ), or
100k + ( 2.5 x block size )
Larger block sizes give rapidly diminishing marginal returns. Most of the compression comes from the first
two or three hundred k of block size, a fact worth bearing in mind when using bzip2 on small machines. It
is also important to appreciate that the decompression memory requirement is set at compression time by
the choice of block size.
For files compressed with the default 900k block size, bunzip2 will require about 3700 kbytes to decompress. To support decompression of any file on a 4 megabyte machine, bunzip2 has an option to decompress using approximately half this amount of memory, about 2300 kbytes. Decompression speed is also
halved, so you should use this option only where necessary. The relevant flag is -s.
In general, try and use the largest block size memory constraints allow, since that maximises the compression achieved. Compression and decompression speed are virtually unaffected by block size.
Another significant point applies to files which fit in a single block -- that means most files youd encounter
using a large block size. The amount of real memory touched is proportional to the size of the file, since
the file is smaller than a block. For example, compressing a file 20,000 bytes long with the flag -9 will
cause the compressor to allocate around 7600k of memory, but only touch 400k + 20000 * 8 = 560 kbytes
of it. Similarly, the decompressor will allocate 3700k but only touch 100k + 20000 * 4 = 180 kbytes.

Property of BladeLogic, Inc.


Strictly confidential and proprietary

bzip2(1)

bzip2(1)

Here is a table which summarises the maximum memory usage for different block sizes. Also recorded is
the total compressed size for 14 files of the Calgary Text Compression Corpus totalling 3,141,622 bytes.
This column gives some feel for how compression varies with block size. These figures tend to understate
the advantage of larger block sizes for larger files, since the Corpus is dominated by smaller files.
Compress Decompress Decompress Corpus
Flag usage
usage
-s usage Size
-1
-2
-3
-4
-5
-6
-7
-8
-9

1200k
2000k
2800k
3600k
4400k
5200k
6100k
6800k
7600k

500k
900k
1300k
1700k
2100k
2500k
2900k
3300k
3700k

350k
600k
850k
1100k
1350k
1600k
1850k
2100k
2350k

914704
877703
860338
846899
845160
838626
834096
828642
828642

RECOVERING DATA FROM DAMAGED FILES


bzip2 compresses files in blocks, usually 900kbytes long. Each block is handled independently. If a media
or transmission error causes a multi-block .bz2 file to become damaged, it may be possible to recover data
from the undamaged blocks in the file.
The compressed representation of each block is delimited by a 48-bit pattern, which makes it possible to
find the block boundaries with reasonable certainty. Each block also carries its own 32-bit CRC, so damaged blocks can be distinguished from undamaged ones.
bzip2recover is a simple program whose purpose is to search for blocks in .bz2 files, and write each block
out into its own .bz2 file. You can then use bzip2 t to test the integrity of the resulting files, and decompress those which are undamaged.
bzip2recover takes a single argument, the name of the damaged file, and writes a number of files
"rec0001file.bz2", "rec0002file.bz2", etc, containing the extracted blocks. The output filenames are
designed so that the use of wildcards in subsequent processing -- for example, "bzip2 -dc rec*file.bz2 >
recovered_data" -- lists the files in the correct order.
bzip2recover should be of most use dealing with large .bz2 files, as these will contain many blocks. It is
clearly futile to use it on damaged single-block files, since a damaged block cannot be recovered. If
you wish to minimise any potential data loss through media or transmission errors, you might consider
compressing with a smaller block size.

PERFORMANCE NOTES
The sorting phase of compression gathers together similar strings in the file. Because of this, files containing very long runs of repeated symbols, like "aabaabaabaab ..." (repeated several hundred times) may compress more slowly than normal. Versions 0.9.5 and above fare much better than previous versions in this
respect. The ratio between worst-case and average-case compression time is in the region of 10:1. For previous versions, this figure was more like 100:1. You can use the vvvv option to monitor progress in great
detail, if you want.
Decompression speed is unaffected by these phenomena.
bzip2 usually allocates several megabytes of memory to operate in, and then charges all over it in a fairly
random fashion. This means that performance, both for compressing and decompressing, is largely determined by the speed at which your machine can service cache misses. Because of this, small changes to the

Property of BladeLogic, Inc.


Strictly confidential and proprietary

bzip2(1)

bzip2(1)

code to reduce the miss rate have been observed to give disproportionately large performance
improvements. I imagine bzip2 will perform best on machines with very large caches.

CAVEATS
I/O error messages are not as helpful as they could be. bzip2 tries hard to detect I/O errors and exit cleanly,
but the details of what the problem is sometimes seem rather misleading.
This manual page pertains to version 1.0 of bzip2. Compressed data created by this version is entirely forwards and backwards compatible with the previous public releases, versions 0.1pl2, 0.9.0 and 0.9.5, but
with the following exception: 0.9.0 and above can correctly decompress multiple concatenated compressed
files. 0.1pl2 cannot do this; it will stop after decompressing just the first file in the stream.
bzip2recover uses 32-bit integers to represent bit positions in compressed files, so it cannot handle compressed files more than 512 megabytes long. This could easily be fixed.

AUTHOR
Julian Seward, jseward@acm.org.
http://sourceware.cygnus.com/bzip2 http://www.muraroa.demon.co.uk
The ideas embodied in bzip2 are due to (at least) the following people: Michael Burrows and David
Wheeler (for the block sorting transformation), David Wheeler (again, for the Huffman coder), Peter Fenwick (for the structured coding model in the original bzip, and many refinements), and Alistair Moffat, Radford Neal and Ian Witten (for the arithmetic coder in the original bzip). I am much indebted for their help,
support and advice. See the manual in the source distribution for pointers to sources of documentation.
Christian von Roques encouraged me to look for faster sorting algorithms, so as to speed up compression.
Bela Lubkin encouraged me to improve the worst-case compression performance. Many people sent
patches, helped with portability problems, lent machines, gave advice and were generally helpful.

Property of BladeLogic, Inc.


Strictly confidential and proprietary

CAT (1)

CAT (1)

NAME
cat concatenate and print files
SYNOPSIS
cat [ benstuv] [file . . .]
DESCRIPTION
The cat utility reads files sequentially, writing them to the standard output. The file operands are processed in command-line order. If file is a single dash ( - ) or absent, cat reads from the standard input.
The options are as follows:
b

Implies the n option but doesnt count blank lines.

Implies the v option and also prints a dollar sign ( $ ) at the end of each line.

Number the output lines, starting at 1.

Squeeze multiple adjacent empty lines, causing the output to be single spaced.

Implies the v option and also prints tab characters as I.

The output is guaranteed to be unbuffered (see setbuf(3)).

Displays non-printing characters so they are visible. Control characters print as X for control-X,
with the exception of the tab and EOL characters, which are displayed normally. The tab character,
control-I, can be made visible via the t option. The DEL character (octal 0177) prints as ?.
Non-ASCII characters (with the high bit set) are printed as M- (for meta) followed by the character
for the low 7 bits.

The cat utility exits 0 on success or >0 if an error occurred.


EXAMPLES
Print the contents of file1 to the standard output:
$ cat file1
Sequentially print the contents of file1 and file2 to the file file3, truncating file3 if it already
exists. See the manual page for your shell (e.g., sh(1)) for more information on redirection.
$ cat file1 file2 > file3
Print the contents of file1, print data it receives from the standard input until it receives an EOF ( D )
character, print the contents of file2, read and output contents of the standard input again, then finally output the contents of file3. Note that if the standard input referred to a file, the second dash on the command-line would have no effect, since the entire contents of the file would have already been read and printed
by cat when it encountered the first - operand.
$ cat file1 - file2 - file3
SEE ALSO
head(1), less(1), more(1), pr(1), sh(1), tail(1), vis(1), setbuf(3)
Rob Pike, "UNIX Style, or cat -v Considered Harmful", USENIX Summer Conference Proceedings, 1983.
STANDARDS
The cat utility is compliant with the IEEE Std 1003.2-1992 (POSIX.2) specification.

BSD

May 2, 1995

CAT (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

CAT (1)

The flags [ benstv] are extensions to the specification.


HISTORY
A cat utility appeared in Version 1 AT&T UNIX.
BUGS
Because of the shell language mechanism used to perform output redirection, the command cat file1
file2 > file1 will cause the original data in file1 to be destroyed!

BSD

May 2, 1995

Property of BladeLogic, Inc.


Strictly confidential and proprietary

chapw(1)

chapw(1)

NAME
chapw Change RSCD Agent password on remote Windows servers

SYNOPSIS
chapw [-r] [-p passwd] [-q] [-f file] host1 [host2 ...]

DESCRIPTION
This command is used to set / change the agent password on one or more Windows hosts that have BladeLogic agent running.
When the RSCD Agent comes up on a Windows server, it needs to impersonate the BladeLogicRSCD
user (created at install time) in order to have the privileges it requires to run properly. To this end, the
RSCD Agent needs to supply a password to the OS. To determine which password to use, the RSCD Agent
looks at a pre-determined registry location (see below) in which a password may be set. If the registry
location is not found/set, the RSCD Agent uses a default password shipped with the agent.

OPTIONS
The following options are supported:
-f file

Specify a flat file containing the list of hosts whose RSCD Agent password one wishes to update.
In addition, one can also name additional hosts as arguments on the command line.

-p passwd
By default one is prompted to enter (and confirm) the desired password. With this option one can
specify the desired password as an argument.
-r

If a password was not specified with the -p option, then this option will cause chapw to automatically randomly generate a 16 character password.

-q

By default chapw displays information about the progress of the update. With this option only
error messages are output.

host ...

The name of the hosts to be updated. Servers that are not Windows servers are not updated and an
appropriate error message is output. In addition, one can also use the -f file option to specify
additional hosts from the file content.

REGISTRY
The password is kept encrypted in the following registry key:
SECURITY\SAM\BladeLogic\Operations Manager\RSCD\P

CAVEATS
The specified hosts for this command should all be Windows systems and should have the agent running
with the "Local System" privileges.
This command does not prompt for the old password as the default password with which the agent was
shipped is unknown to the user.
If for some reason the user decides to revert back to the default value with which the BladeLogic agent was
shipped, then the user should remove the RSCD registry location from the registry and delete the BladeLogicRSCD user.

SEE ALSO
rscd (1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

chgrp(1)

chgrp(1)

NAME
chgrp Change group (and user) ownerships of files

SYNOPSIS
chgrp [-fhRv?] group file ...
chgrp [-fhRv?] user.group file ...

DESCRIPTION
chgrp changes the group or the group and user ownership of the named files. By default, chgrp changes
only the group ownership. However, if you precede the group name by a user name and a period (.), then
chgrp changes the user ownership as well.

OPTIONS
-f

Do not report any errors that occur.

-h

When changing the ownership of a file that is a symbolic link, change the ownership of the link
itself rather than the file it is pointing to.

-l

Always resolve the groupname and optional username on the local system. See the -r option.

-r

Indicates that the groupname and the (optional) username are not numeric, and therefore will not
be resolved on the local system. Instead, chgrp will resolve the username and groupname on the
system on which the change of ownership is to take place.
By default, this option is turned on. To turn it off, use the -l option.

-R

If any of the named arguments is a directory, then chgrp will recursively descend the directory
and change the appropriate ownerships of all files and sub-directories below it.

-v

Output a message for each file whose ownership is being changed. This can be useful for monitoring progress in recursive file ownership changes.

-?

Output a brief summary of available options and then exit with a zero status without changing any
ownerships.

group

New group owner of the file (group name or GID).

user

New owner of the file (user name or UID).

EXAMPLE
The first example changes the group ownership of the file myprog to bin. The second example changes
the group ownership of all files in the directory /u1/myapps to group adm on host paris.
$ chgrp bin myprog
$ chgrp -R adm //paris/u1/myapps

DIAGNOSTICS
chgrp: Unable to access file filename
chgrp was unable to access the file filename.
chgrp: Unable to access directory dirname
When changing ownerships of a file (directory) recursively, this message will appear if chgrp is
unable to access the directory dirname.
chgrp: Unable to change group ownership of file filename
An error has occurred when changing the ownership of the file filename.
chgrp: Unknown group ID groupname
The groupname groupname is unknown, and consequently a GID is not available for this group.
chgrp: Unknown user ID username
The username username is unknown, and consequently a UID is not available for this user.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

chgrp(1)

chgrp(1)

EXIT CODES
0

No errors detected.

Unknown option or missing file argument.

chgrp was unable to access the file it was trying to change ownership of.

chgrp was unable to access one of the directories in a recursive change of ownership.

You specified an unknown GID or UID.

255

Unable to get a license to use the software.

CAVEATS
If you do not specify either the -l option or the -r option, and you use a groupname/username (as opposed
to a GID/UID), chgrp resolves the groupname/username to the GID/UID on the local machine. If the
GID/UID of the group/user differs on the host on which you are making the change, you may not achieve
the ownership change you want.
The -h option may have no effect on systems that do not support the appropriate system call to perform this
action (lchown(2)).

ORIGIN
chgrp was written by Thomas Kraus

SEE ALSO
chown(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

chmod(1)

chmod(1)

NAME
chmod Change the mode (protection attributes) of a file

SYNOPSIS
chmod [-Rdfv?] mode file ...

DESCRIPTION
chmod changes the mode or access permissions of the named file(s) to mode.
mode can be an absolute octal value, or a series of comma separated instructions, each having the following
format:
[who][op][perms]
The who section determines whose permissions are to be changed. who can be one or a combination of
two or more characters from the following set:
who

If you do not specify a value for who , it defaults to the value of a


u
Modify the user permissions
g
Modify the group permissions
o
Modify the other permissions
a
Modify all permissions (same as ugo)

op

You must specify one of the following values for the op section:
+
Add the specified permissions to the existing permissions of the file
Subtract the specified permissions from the existing permissions of the file
=
Set the specified value as the file permissions

perms

Set the new permissions using any combination of the following characters
r
Modify the read permissions for who
w
Modify the write permissions for who
x
Modify the execute permissions for who
s
Modify the set UID/GID permissions for who
t
Modify the set sticky bit permissions for who

OPTIONS
-R

If any of the named arguments is a directory, then chmod will recursively descend the directory
and change the appropriate permissions of all files and sub-directories below it.

-d

This option tells chmod to change the permissions of a file ONLY if the file is a directory. This
includes both files specifically named in the command argument list, and files encountered while
doing a recursive (-R) permissions change. If chmod encounters a file that is not a directory,
chmod silently skips it. This can be a useful option in a recursive change of permissions if you
only want to change the permissions of directories, since directories usually have different permissions than files.

-f

This option tells chmod to change the permissions of a file ONLY if the file is not a directory (i.e.
regular files, special files, ... etc). This includes both files specifically named in the command
argument list, and files encountered while doing a recursive (-R) permissions change. If chmod
encounters a directory, chmod silently skips it. This can be a useful option in a recursive change
of permissions if one does not want to change the permissions of any directories.

-v

Output a message for each file whose permissions are being changed. This can be useful to monitor the progress of a recursive permissions change.

-?

Output a brief summary of available options and then exit with a zero status without changing any
permissions.

mode

The permissions changes you want to make. See the DESCRIPTION section above.

file

File whose mode you want to change.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

chmod(1)

chmod(1)

EXAMPLE
The first example changes the permissions of the file myprog to 755 (read, write, execute for user, and
read, execute for both the group and other users). The second example adds execute permission to other
users and read, write, execute permissions for the owner of the file.
$ chmod 0755 myprog
$ chmod o+x,u+rwx //madrid/u1/myprog

DIAGNOSTICS
chmod: Invalid mode (mode)
The mode you specified contained unknown characters.
chmod: Unable to access the file filename
chmod was unable to access the filename
chmod: Unable to access directory dirname
When changing permissions of a file (directory) recursively, chmod was unable to access the
directory dirname
chmod: Cannot change ownership of file filename
An error occurred when changing the permissions of the file filename

EXIT CODES
0

No errors detected.

Unknown option or missing file argument.

chmod was unable to access the file it was trying to change ownership of.

chmod was unable to access one of the directories in a recursive change of permissions.

255

Unable to get a license to use the software.

ORIGIN
chmod was written by Thomas Kraus.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

chown(1)

chown(1)

NAME
chown Change user (and group) ownerships of files

SYNOPSIS
chown [-fhlrRv?] user file ...
chown [-fhlrRv?] user.group file ...

DESCRIPTION
This command changes the user or the user and group ownership of the named files. By default, this command changes only the user ownership. However, you can also change the group ownership of a file by
appending a period (.) and a group name to the user name.

OPTIONS
-f

Do not report any errors if they occur.

-h

When changing the ownership of a file that is a symbolic link, change the ownership of the link
itself rather than the file it is pointing to.

-l

Always resolve the username and optional groupname on the local system. See the -r option.

-r

Indicates that the username and the (optional) groupname are not numeric, and therefore will not
be resolved on the local system. Instead, the username and groupname will be resolved on the
system on which the change of ownership is to take place.
By default, this option is turned on. You can turn it off with the -l option.

-R

If any of the named arguments is a directory, then chown will recursively descend the directory
and change the appropriate ownerships of all files and sub-directories below it.

-v

Output a message for each file whose ownership is being changed. Useful for monitoring
progress in recursive file ownership changes.

-?

Output a brief summary of available options and then exit with a zero status, without changing
any ownerships.

user

New owner of the file (user name or UID).

group

New group owner of the file (group name or GID).

EXAMPLE
The first example changes the user ownership of the file myprog to bin. The second example changes the
group ownership of all files in the directory /u1/myapps to user adm on host bern.
$ chown bin myprog
$ chown -R adm //bern/u1/myapps

DIAGNOSTICS
chown: Unable to access file filename
chown was unable to access the file filename.
chown: Unable to access directory dirname
When changing ownerships of a file (directory) recursively, this message will appear if chown is
unable to access the directory dirname.
chown: Unable to change user ownership of file filename
An error has occurred when changing the ownership of the file filename.
chown: Unknown user ID username
The username username is unknown, and consequently a UID is not available for this user.
chown: Unknown group ID groupname
The groupname groupname is unknown, and consequently a GID is not available for this group.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

chown(1)

chown(1)

EXIT CODES
0

No errors detected.

Unknown option or missing file argument.

chown was unable to access the file it was trying to change ownership of.

chown was unable to access one of the directories in a recursive change of ownership.

chown encountered an unknown GID or UID.

255

Unable to get a license to use the software.

When a user or group name is explicitly used (as opposed to numeric values), the UID and GID of the
user/group as defined on the local host is used. Consequently, the change of ownership may not reflect the
desired effect if the UID/GID of the user/group differ on the host on which the change is being made,
The -h option may have no effect on systems that do not support the appropriate system call to perform this
action (lchown(2)).

ORIGIN
chown was written by Thomas Kraus.

SEE ALSO
chgrp(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

chrole(1)

chrole(1)

NAME
chrole Change the active role for the current Network Shell session.

SYNOPSIS
chrole [role]

DESCRIPTION
The chrole command changes the role preference for the current NSH session. All subsequent NSH commands issued from within that session are executed within the context of the new role.
If you do not provide a role preference when entering the chrole command, you are presented with a numbered list of authorized roles and prompted to make a selection from that list.
Entering a chrole command only changes the role for new connections with Network Shell Proxy Servers.
To set up a new role for agents with which you already have proxy connections, you must disconnect. See
the EXAMPLES section below for a demonstration of the required procedure.

COMMAND OPTIONS
None

EXAMPLES
The following example changes the active role to WindowsAdmins, provided the active user is authorized
for that role.
$ chrole WindowsAdmins
The following example shows the procedure that is necessary to change roles for existing connections to
agents. Because the chrole command does not change the role for the current session, when you have an
existing connection, you must specify a new role preference, disconnect from the host where you are currently connected, and then reconnect.
$ cd //host1
# Connect to host1. Your current role is role1.
$ chrole role2
# Change to role2.
$ cd //
# Make no connection the active context.
$ disconnect
# Disconnect from all servers. Note that this command will not
# disconnect from host1 if the current working directory is //host1.
$ cd //host1
# Reconnect to host1.

DIAGNOSTICS
If the user attempts to chrole to an unauthorized role, the role selection is ignored. The user is presented
with a list of roles to choose from.

EXIT CODES
0

Always returns with a 0 exit code.

CAVEATS
The chrole command is a "built-in" Network Shell command and can only be issued from within an active
NSH session.

ORIGIN
chrole was developed by BladeLogic.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

cksum(1)

cksum(1)

NAME
cksum, sum display file checksums and block counts

SYNOPSIS
cksum [-?] [-r] [-o [1 | 2]] [file ...]
sum [-?] [-r] [-o [1 | 2]] [file ...]

DESCRIPTION
The cksum utility writes to the standard output three whitespace separated fields for each input file. These
fields are a checksum CRC, the total number of octets in the file and the file name. If no file name is specified, the standard input is used and no file name is written.
Sum is a link to cksum and is provided for compatibility. Using this interface, one only has access to the historic algorithms ( -o 1 | 2 ). Please read the UNIVERSE BEHAVIOR section to determine the default
behavior of this command.

OPTIONS
The following options may modify the behavior of cksum.
-r

Same as -o 1.

-o 1 | 2

Use historic algorithms instead of the (superior) default one. See description below.

-?

Output a brief summary of available options and then exit with calculating any checksums.

ALGORITHMS
Algorithm 1 is the algorithm used by historic BSD systems as the sum(1) algorithm and by historic AT&T
System V UNIX systems as the sum algorithm when using the -r option. This is a 16-bit checksum, with a
right rotation before each addition; overflow is discarded.
Algorithm 2 is the algorithm used by historic AT&T System V UNIX systems as the default sum algorithm.
This is a 32-bit checksum, and is defined as follows:
s = sum of all bytes;
r = s % 216 + (s % 232) / 216;
cksum = (r % 216) + r / 216;
Both algorithm 1 and 2 write to the standard output the same fields as the default algorithm except that the
size of the file in bytes is replaced with the size of the file in blocks. For historic reasons, the block size is
1024 for algorithm 1 and 512 for algorithm 2. Partial blocks are rounded up.
The default CRC used is based on the polynomial used for CRC error checking in the networking standard
ISO 8802-3: 1989 The CRC checksum encoding is defined by the generating polynomial:
G(x) = x32 + x26 + x23 + x22 + x16 + x12 +
x11 + x10 + x8 + x7 + x5 + x4 + x2 + x + 1
Mathematically, the CRC value corresponding to a given file is defined by the following procedure:
The n bits to be evaluated are considered to be the coefficients of a mod 2 polynomial M(x) of degree n-1.
These n bits are the bits from the file, with the most significant bit being the most significant bit of the first
octet of the file and the last bit being the least significant bit of the last octet, padded with zero bits (if necessary) to achieve an integral number of octets, followed by one or more octets representing the length of
the file as a binary value, least significant octet first. The smallest number of octets capable of representing
this integer are used.
M(x) is multiplied by x32 (i.e., shifted left 32 bits) and divided by G(x) using mod 2 division, producing a
remainder R(x) of degree <= 31.
The coefficients of R(x) are considered to be a 32-bit sequence.
The bit sequence is complemented and the result is the CRC.
The cksum utility exits 0 on success, and >0 if an error occurs.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

cksum(1)

cksum(1)

EXAMPLE
The first example prints out the checksum for two password files using the new improved checksum algorithm. The second example uses the historic AT&T algorithm for all files in the directory /home/data on
host ottawa.
$ cksum /etc/passwd //ottawa/etc/passwd
$ cksum -o 2 //ottawa/home/data/*

DIAGNOSTICS
cksum: Cannot open file filename
The file for which the checksum was to be calculated was not accessible. A system error message
follows the output of the error message.

EXIT CODES
0

No errors detected

An unknown option was given

One of the files to be checksummed was not accessible

255

Unable to get a license to use the software.

UNIVERSE BEHAVIOR
The universe setting only takes affect when the sum version of the command is used and no checksum type
has been selected. When the P_BSD variable is set (Berkeley behavior), algorithm 1 is used. With the
P_ATT variable set, algorithm 2 is used.

COPYRIGHT
Please read the Copyright notice in intro(1) section of documentation.

ORIGIN
Cksum includes software developed by the University of California, Berkeley and its contributors. Please
see the intro section for complete acknowledgments.

SEE ALSO
sum(1), cksum(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

cmp(1)

cmp(1)

NAME
cmp Compare two files

SYNOPSIS
cmp [-ls?] file1 file2 [skip1] [skip2]

DESCRIPTION
cmp compares the content of two files, checking to see if they are identical. cmp exits with an exit code
that indicates whether or not the files are identical. By default, cmp stops processing after it finds the first
difference.
If one of the files is shorter in length than the other, cmp outputs an appropriate message and stops the
comparison, even with the -l option. When this happens, cmp always considers the files not to be identical.

OPTIONS
-l

Do not stop checking after finding the first difference. Instead, find all differences in the files. For
each difference it finds, cmp outputs a line consisting of the character number, and the two different character values found in the files.

-s

This option tells cmp not to output any message when it finds a difference. cmp will just exit
with the appropriate exit code.

-?

Output a brief summary of available options and then exit with a zero status without doing any
comparing.

file1

The first file in the comparison. If file1 is -, then cmp uses the standard input.

file2

The second file in the comparison.

skip1

Start comparing at skip1 bytes from first file by seeking to that position in the file. If the standard
input is being used ( file1 is -), then the offset is read instead of being seeked over.

skip2

Start comparing at skip2 bytes from second file by seeking to that position in the file.

EXAMPLE
The following example checks to see the .rhosts file on a remote host has changed from the expected
contents. If it has, the proper one is copied back over it with the proper permissions and ownerships.
$
$
>
>
>
>
>
>
$

cmp -s rhosts.master //oslo/.rhosts


if test $? -eq 1
then
echo .rhosts file on host oslo has changed.
cp rhosts.master //oslo/.rhosts
chmod 0700 //oslo/.rhosts
chown root.root //oslo/.rhosts
fi

DIAGNOSTICS
cmp: Cannot access file filename
cmp was unable to access the file filename.
cmp: Illegal option xyz
The given option xyz is not a valid option.
cmp: EOF on filename
If one of the two files is shorter than the other, cmp outputs an appropriate message indicating
which file is shorter.

EXIT CODES
0

Files are identical.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

cmp(1)

Files are not identical.

One of the files was not accessible, or cmp encountered a bad or missing argument.

255

Unable to get a license to use the software.

cmp(1)

ORIGIN
cmp was written by Thomas Kraus.

NSH

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

colrm ( 1 )

NAME

colrm - remove columns from a file


SYNOPSIS

colrm [start [stop]]


DESCRIPTION

Colrm removes selected columns from the lines of a file. A column is defined as a single character in a
line. Input is read from the standard input. Output is written to the standard output.
If only the start column is specified, columns numbered less than the start column will be written. If both
start and stop columns are specified, columns numbered less than the start column or greater than the stop
column will be written. Column numbering starts with one, not zero.
Tab characters increment the column count to the next multiple of eight. Backspace characters decrement
the column count by one.
ORIGIN

Colrm includes software developed by the University of California, Berkeley and its contributors. Please
see the intro section for complete acknowledgements.
SEE ALSO

column(1), cut(1), paste(1)

SunOS 5.8

Last change: NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

comm ( 1 )

NAME

comm - select or reject lines common to two files


SYNOPSIS

comm [-123] file1 file2


DESCRIPTION

The comm utility reads file1 and file2, which should be sorted lexically, and produces three text columns as
output: lines only in file1; lines only in file2; and lines in both files.
The filename - means the standard input.
The following options are available:
-1

Suppress printing of column 1.

-2

Suppress printing of column 2.

-3

Suppress printing of column 3.

Each column will have a number of tab characters prepended to it equal to the number of lower numbered
columns that are being printed. For example, if column number two is being suppressed, lines printed in
column number one will not have any tabs preceding them, and lines printed in column number three will
have one.
Comm assumes that the files are lexically sorted; all characters participate in line comparisons.
Comm exits 0 on success, >0 if an error occurred.
ORIGIN

Comm includes software developed by the University of California, Berkeley and its contributors. Please
see the intro section for complete acknowledgements.
SEE ALSO

cmp(1), sort(1), uniq(1)

SunOS 5.8

Last change: NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

COMPRESS (1)

System General Commands Manual

COMPRESS (1)

NAME
compress, uncompress, zcat compress and expand data (compress mode)
SYNOPSIS
compress [ 123456789cdfghLlNnOqrtVv] [ b bits] [ o filename] [ S suffix]
[file . . .]
uncompress [ cfhlNnqrtv] [ o filename] [file . . .]
zcat [ fghqr] [file . . .]
DESCRIPTION
The compress utility reduces the size of the named files using adaptive Lempel-Ziv coding, in compress
mode. If invoked as compress g, the deflate mode of compression is chosen; see gzip(1) for more
information. Each file is renamed to the same name plus the extension .Z. As many of the modification
time, access time, file flags, file mode, user ID, and group ID as allowed by permissions are retained in the
new file. If compression would not reduce the size of a file, the file is ignored (unless f is used).
The uncompress utility restores compressed files to their original form, renaming the files by removing
the extension (or by using the stored name if the N flag is specified). It has the ability to restore files compressed by both compress and gzip(1), recognising the following extensions: .Z, -Z, _Z, .gz,
-gz, _gz, .tgz, -tgz, _tgz, .taz, -taz, and _taz. Extensions ending in tgz and taz are not
removed when decompressing, instead they are converted to tar.
The zcat command is equivalent in functionality to uncompress c.
If renaming the files would cause files to be overwritten and the standard input device is a terminal, the user
is prompted (on the standard error output) for confirmation. If prompting is not possible or confirmation is
not received, the files are not overwritten.
If no files are specified, the standard input is compressed or uncompressed to the standard output. If either
the input or output files are not regular files, the checks for reduction in size and file overwriting are not performed, the input file is not removed, and the attributes of the input file are not retained.
By default, when compressing using the deflate scheme ( g), the original file name and time stamp are
stored in the compressed file. When uncompressing, this information is not used. Instead, the uncompressed
file inherits the time stamp of the compressed version and the uncompressed file name is generated from the
name of the compressed file as described above. These defaults may be overridden by the N and n flags,
described below.
The options are as follows:
1...9
Use the deflate scheme, with compression factor of 1 to 9. Compression factor 1 is the
fastest, but provides a poorer level of compression. Compression factor 9 provides the best level
of compression, but is relatively slow. The default is 6. This option implies g.
b bits
Specify the bits code limit ( see below ) .

BSD

Compressed or uncompressed output is written to the standard output. No files are modified (force
zcat mode).

Decompress the source files instead of compressing them (force uncompress mode).

Force compression of file, even if it is not actually reduced in size. Additionally, files are overwritten without prompting for confirmation. If the input data is not in a format recognized by
compress and if the option c is also given, copy the input data without change to the standard

April 3, 2008

Property of BladeLogic, Inc.


Strictly confidential and proprietary

COMPRESS (1)

System General Commands Manual

COMPRESS (1)

output: let zcat behave as cat(1).


g

Use the deflate scheme, which reportedly provides better compression rates (force gzip(1) mode).

Print a short help message.

Print the license.

List information for the specified compressed files. The following information is listed:
compressed size

Size of the compressed file.

uncompressed size

Size of the file when uncompressed.

compression ratio

Ratio of the difference between the compressed and uncompressed sizes


to the uncompressed size.

uncompressed name

Name the file will be saved as when uncompressing.

If the v option is specified, the following additional information is printed:


compression method

Name of the method used to compress the file.

crc

32-bit CRC ( cyclic redundancy code ) of the uncompressed file.

time stamp

Date and time corresponding to the last data modification time (mtime)
of the compressed file (if the n option is specified, the time stamp
stored in the compressed file is printed instead).

When uncompressing or listing, use the time stamp and file name stored in the compressed file, if
any, for the uncompressed version. This information is only available when the deflate scheme ( g)
is used.

When compressing, do not store the original file name and time stamp in the header of the compressed file.

Use compress mode (the default).

o filename
Set the output file name.
q

Be quiet: suppress all messages.

Recursive mode: compress will descend into specified directories.

S suffix
Set the suffix for compressed files.
t

Test the integrity of each file leaving any files intact.

Display the program version ( RCS IDs of the source files ) and exit.

Print the percentage reduction of each file and other information.

compress uses a modified Lempel-Ziv algorithm ( LZW ) . Common substrings in the file are first
replaced by 9-bit codes 257 and up. When code 512 is reached, the algorithm switches to 10-bit codes and
continues to use more bits until the limit specified by the b flag is reached. bits must be between 9 and
16 ( the default is 16 ) .
After the bits limit is reached, compress periodically checks the compression ratio. If it is increasing,
compress continues to use the existing code dictionary. However, if the compression ratio decreases,
compress discards the table of substrings and rebuilds it from scratch. This allows the algorithm to adapt
to the next block of the file.

BSD

April 3, 2008

Property of BladeLogic, Inc.


Strictly confidential and proprietary

COMPRESS (1)

System General Commands Manual

COMPRESS (1)

The b flag is omitted for uncompress since the bits parameter specified during compression is
encoded within the output, along with a magic number to ensure that neither decompression of random data
nor recompression of compressed data is attempted.
The amount of compression obtained depends on the size of the input, the number of bits per code, and the
distribution of common substrings. Typically, text such as source code or English is reduced by 50 60%
using compress. Compression is generally much better than that achieved by Huffman coding (as used in
the historical command pack), or adaptive Huffman coding (as used in the historical command compact), and
takes less time to compute.
The compress, uncompress, and zcat utilities exit with 0 on success; 1 if an error occurred; or 2 if a
warning occurred.
SEE ALSO
Welch, Terry A., "A Technique for High Performance Data Compression", IEEE Computer, 17:6, pp. 819,
June, 1984.
STANDARDS
The compress, uncompress, and zcat utilities are compliant with the specification.
The compress flags [ 123456789dghLlNnOqrtV], uncompress flags [ hlNnqrt], and the
zcat flags [ fghqr] are extensions to that specification.
HISTORY
The compress command appeared in 4.3 BSD. Deflate compression support was added in OpenBSD 2.1.

BSD

April 3, 2008

Property of BladeLogic, Inc.


Strictly confidential and proprietary

cp(1)

cp(1)

NAME
cp Copy files

SYNOPSIS
cp [-bifnpPtuvBCLST?] [-s suf] file1 file2
cp [-bifnpPrtuvBCLPRST?] [-s suf] [-IX wildcarded path] file ... dir

DESCRIPTION
cp makes copies of files. In the first form, cp copies the contents of one file to a second file. In the second
form, cp copies multiple files into a directory. When copying to a directory, cp creates copied files with the
same names as the source files.
By default, when cp creates a new file, the new file gets the same permissions as the source file, and inherits
the ownership of the calling user. If the target file already exists, and is consequently overwritten, then it
retains its current permissions and ownerships.

OPTIONS
-b

Backup the target file, if it exists, before copying over the new source file. By default, cp appends
the target file name with the suffix "". You can use the -s suf option to specify a different suffix.

-i

If a target file already exists, then cp will prompt the user to see if the user wants cp to overwrite
the file. If the user confirms with an entry beginning with the letter y, then cp overwrites the file.
See UNIVERSE BEHAVIOR for details on how this option interacts with the -f option.

-f

By default, if the target file already exists, it will retain its current file permissions after cp overwrites it. This option deletes the target file before the copy begins, so that the target file inherits
the same file permissions as the source file.

-m

Synchronize file permissions. Even if the file itself does not get copied to the destination (conditional copy and no changes in file) the cp command will still update the destination files permissions to match the source files permissions.

-n

Dont actually make any changes. This option automatically turns on the verbose option -v and
just lists the copies that cp would make if you had not turned on the -n option. cp does not create
or remove any files or directories. This option is useful when you are performing a conditional
copy and you just want to see what files would be copied if you were doing a real copy. This
option turns off the -i option.

-o

Synchronize file ownerships. Even if the file itself does not get copied to the destination (conditional copy and no changes in file) the cp command will still update the destination files
user/group ownerships to match the source files user/group ownerships.

-p

With this option, cp will attempt to give the target file the same ownerships (UID/GID), permissions, and access and modification times as the source file. This also applies to new directories
being created.

-P

Preserve parent. By default, when cp copies a directory, it behaves differently depending on


whether or not the destination (directory) already exists. If the destination directory does not
exist, cp creates it and copies the content into it. If the destination directory does exist, cp creates
a new directory inside of the existing directory, and copies the content into it. With the -P option,
cp always acts as if the destination directory does not exist. When the destination directory does
exist, cp overwrites it, so that, for example, two consecutive copies to the same destination directory will always produce the same result.

-r

With his option, if one of the files to be copied is a directory, then cp recursively copies all files
and sub-directories from the directory into the target directory. If the target directory does not
already exist, then cp will create the directory as required. If the target directory does already
exist, then cp will create the new target directory within the (existing) target directory.

-s suf

Set the suffix for backup files to suf. The default suffix for files being backed up is "" (foo.c
becomes foo.c) This option alone does not turn on the file backup feature. To turn on the file
backup feature, use the -b command.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

cp(1)

cp(1)

-t

Make a textual copy of the file. This option is useful when copying text files to or from a Windows based system. This option will ensure proper handling of the <CR><LF> issues.

-u

There are three options you can use to perform conditional copies. They are -T, -S and -C. The
-u option is equivalent to using the -T and -S options. These options cause the target file to be
overwritten only if either the file sizes differ or if the source file has a newer modification date
than the target file.

-v

Output a message for each file being copied. Useful for monitoring progress in a recursive copy.

-B

Like -b except that if a backup version of the file already exists, then the backup will not be overwritten.

-C

Conditional copy. The target file will be overwritten only if its content differs from the source file.
This option implies the -S option. If the file sizes are the same, cp will perform a byte for byte
analysis of the source and target files to determine if a difference exists. This option can be very
resource intensive, especially on a large file.

-I (wildcarded path)
This option includes the specified files/directories in the sync operation.
-K

This option is like the -L option, except that it applies only to the top level file, should it be a
symbolic link.

-L

When recursing through directories, follow symbolic links.

-P

This is the no parent option. This option is useful when (recursively) copying the content of one
directory to another existing directory. The default action of the cp command would be to re-create the source directory in the destination directory. With the -P option, the content of the source
directory is re-created in the target directory essentially overlaying the source directory on to the
destination instead of creating the subdirectory.

-R

This option is the same as the -r option, except that newly created directories automatically get
the user permissions read, write, and execute. If you use this option with the -p option, then the
-R option is treated as a -r option.

-S

Conditional copy. This option tells cp to overwrite target files only if source and target file sizes
differ. See the -u option.

-T

Conditional copy. This option tells cp to overwrite target files only if the modification date of the
source file is newer than the modification date of the target file. See the -u option.

-X (wildcarded path)
This option excludes the specified files/directories from the sync operation.
-?

Output a brief summary of available options and then exit with a zero status without copying any
files.

EXAMPLE
The first example copies the file myprog to the directory /usr/local/bin on the host brussels.
The second example copies the contents of the directory datadir to the directory
/usr/local/datadir which is first created.
$ cp -p myprog //brussels/usr/local/bin
$ rm -fr //brussels/usr/local
$ cp -rvf datadir //brussels/usr/local

DIAGNOSTICS
cp: Target directory (dirname) not found
When copying multiple files to a directory, this message will appear if cp is unable to access the
target directory (last argument).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

cp(1)

cp(1)

cp: Target file (filename) must be a directory


When copying multiple files to a directory, this message will appear if the target directory (last
argument) is not a directory.
cp: Unable to create directory dirname
When copying a directory recursively, cp may need to create new directories in the target directory tree. If cp is not able to create one of these directories, this message will appear.
cp: Unable to access directory dirname
When copying a directory recursively, cp traverses the source directory hierarchy. If cp has a
problem accessing a directory, this message will appear.
cp: file filename is a directory (not copied)
If one of the files to be copied is a directory and you did not specify the recursive option (-r) ,
then this message appears, indicating that cp cannot copy directories.
cp: Unable to access file filename
cp: Unable to read file filename
If cp is unable to access the source file filename, it will display this message, along with a possible reason why it was not able to access the file.
cp: Unable to create file filename
If the new target file cannot be created, cp will display this message, along with a possible reason
why cp was not able to create the file filename.
cp: Error writing to file filename
If an error occurs while copying a file into the new target file, this message will appear indicating
that the copy may not be complete.

EXIT CODES
0

No errors detected.

Unknown option or missing file argument.

cp was unable to copy all files requested.

255

Unable to get a license to use the software.

UNIVERSE BEHAVIOR
If both the -i and -f options are used, then with the P_BSD variable set (Berkeley behavior), the -i option
will override the -f option. With the P_ATT variable set, the -f option will override the -i option.

ORIGIN
cp was written by Thomas Kraus.

SEE ALSO
dsync (1), ncp(1), uncp(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

csv2xml(1)

csv2xml(1)

NAME
csv2xml Convert CSV input to an XML output

SYNOPSIS
csv2xml [-?] [-<number>] [-h] [-n name] [-s sep] [-q quote] [-r] [-x]

DESCRIPTION
The csv2xml utility is a filter that converts a CSV input stream to an XML output stream.

OPTIONS
-<number>
By default, record names are numbered sequentially starting from 1. With this option, csv2xml
uses the value of column (field) <number> of the respective line as the record name. This can be
useful if the CSV input contains a unique field (for example, hostname) that can be used as an
identifier.
-n name By default the master XML tag is called csv2xml. The -n option lets you specify name as the
master XML tag.
-s sep

By default csv2xml uses the comma (,) character as the field separator. The -s option lets you
specify the first character of sep as the field separator.

-q quote By default csv2xml uses the double quote (") character as a string delimiter. The -q option lets
you specify the first character of quote as a string delimiter.
-h

By default csv2xml assumes that the first line of the CSV input is a header line. It uses this
header line to name the columns of input. With this option, csv2xml generates column names,
and in turn XML tags, in the format of column-<record number>.

-r

Do not output the root node tag. This option is often used in conjunction with the -x option.

-x

Do not output the XML header entry. Use this option only if you will be embedding the output
into another XML document.

-?

Output a usage message and exit with a 0 exit code.

EXAMPLE
athens% nover -c -h london rome | csv2xml -1 -n "Host Overview"
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<csv2xml name="Host Overview">
<record name="london">
<HOSTNAME>london</HOSTNAME>
<OS>RedHat ES3</OS>
<MAINT>2.4.21-4.EL</MAINT>
<CPUS>1</CPUS>
<SPEED>797</SPEED>
<ARCH>i686</ARCH>
<MEMORY>121</MEMORY>
<SWAP>251</SWAP>
<DISK>18</DISK>
</record>
<record name="rome">
<HOSTNAME>rome</HOSTNAME>
<OS>SunOS 5.8</OS>
<MAINT></MAINT>
<CPUS>1</CPUS>
<SPEED>440</SPEED>
<ARCH>sparcv9</ARCH>
<MEMORY>256</MEMORY>
<SWAP>513</SWAP>
<DISK>17</DISK>

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

csv2xml(1)

csv2xml(1)

</record>
</csv2xml>

CAVEATS
The first record (line of input) determines the number of fields that csv2xml will display. If subsequent
records have more fields than the first record, csv2xml will not display these additional fields. If subsequent records have fewer fields than the first record, csv2xml will add empty fields to the record.
XML has certain restrictions as to which characters are allowed in an XML tag. Because csv2xml generates
XML tag names based on the fields in the first line of input, csv2xml may need to modify these fields to
ensure that they do not contain unsupported characters. If csv2xml finds an unsupported character, it converts it to an underscore (_) character.

ORIGIN
csv2xml was written by Thomas Kraus

SEE ALSO
The following commands are able to output in CSV format (-c option):
nps(1), ncpu(1), ndf(1), nover(1), nnet(1), nmem(1), nstats(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

cut(1)

cut(1)

NAME
cut select portions of each line of a file

SYNOPSIS
cut -c list file ...
cut -f list [-d string] [-s] file ...

DESCRIPTION
The cut utility selects portions of each line (as specified by list) from each file (or the standard input by
default), and writes them to the standard output. The items specified by list can be in terms of column position or in terms of fields delimited by a special character. Column numbering starts from 1.
List is a comma or whitespace separated set of increasing numbers and/or number ranges. Number ranges
consist of a number, a dash (-), and a second number and select the fields or columns from the first number
to the second, inclusively. Numbers or number ranges may be preceded by a dash, which selects all fields or
columns from 1 to the first number. Numbers or number ranges may be followed by a dash, which selects
all fields or columns from the last number to the end of the line. Numbers and number ranges may be
repeated, overlapping, and in any order. It is not an error to select fields or columns not present in the input
line.

OPTIONS
The cut utility accepts the following options:
-c list

Identifies the list specifying character positions.

-d string Specifies that the first character of the string should function as the field delimiter character
instead of the tab character.
-f list

Indicates that the list specifies fields, delimited in the input by a single tab character. Output fields
are separated by a single tab character unless you use -d to specify a different field delimiter. If
you do, that character is used to separate output fields.

-s

Suppresses lines with no field delimiter characters. Unless specified, lines with no delimiters are
passed through unmodified.

The arguments following the options -c, -d, and -f must not be separate arguments and can also be defined
directly after the option. Consequently the command:
cut -d : -f 2is equivalent to:
cut -d: -f2-

EXIT CODES
The cut utility exits 0 on success, 1 if an error occurred. The cut utility includes software developed by the
University of California, Berkeley and its contributors. Please see the intro section for complete acknowledgements.

SEE ALSO
paste(1)

NSH

daalinfo(1)

daalinfo(1)

NAME
daalinfo Output information about local DAAL registry.

SYNOPSIS
daalinfo

DESCRIPTION
The daalinfo command gives an overview of the local DAAL registry. daalinfo does not require that the
local agent be up, and does not work with remote agents. daalinfo accesses the local registry directly as a
read-only resource on the file system. daalinfo outputs the information in the following format:
=== Registry ==========================================
Registry Root : /usr/nsh/daal
Timestamp : 1223403691
Asset Class Count : 16
Asset Implementation Count : 9
=== Asset Classes =====================================
Asset Class Name : /DAALRegistry
Version : 0
Override Asset Class Name :
Implementation : /DAALMgt
Asset Class Name : /MyClass1
Version : 1
Override Asset Class Name :
Implementation : /MyCustomObjectScript
.
.
.
(example output truncated)
.
.
.
=== Asset Implementations =============================
Implementation Name : /DAALMgt
Version : 0
Handler Implementation :
Implementation API Version : BLPLUGIN_VERSION_XETA (13)
Implementation File : File||libdaalplugindaalmgt.so
Implementation Name : /ExternalProgramAdapter
Version : 1
Handler Implementation :
Implementation API Version : BLPLUGIN_VERSION_ETA (12)
Implementation File : File|16547abf4eb258fd9b2d2f81704aee20|/usr/nsh/daal/
Implementation Name : /MyCustomObjectScript
Version : 1
Handler Implementation : /ExternalProgramAdapter
Implementation API Version : BLPLUGIN_VERSION_UNKNOWN (0)
Implementation File : Directory||/usr/nsh/daal/Implementation/MyCustomObje
Implementation File : File|400e7b1225e5842c93c750f6ec532d9a|/usr/nsh/daal/
Implementation File : File|d148515b64f753f4709d0fdc0cfffa6d|/usr/nsh/daal/
.

NSH

daalinfo(1)

daalinfo(1)

.
.
(example output truncated)
.
.
.

The output is divided into three sections: the Registry section, the Asset Classes section, and the Asset
Implementations section.
Registry
The registry section identifies the path to the local DAAL registry, the Unix time stamp of the last time
that the registry was modified, and some basic statistics on the number of objects in the registry.
It should be noted that the DAAL models itself as a collection of DAAL plug-in backed custom objects.
Because of this, some of the asset classes and asset implementations reported by daalinfo should be considered built-in and immutable. See BUILT-IN OBJECTS below for more details.
Asset Classes
The asset classes section lists all custom object asset classes currently known to the DAAL. Each asset
class section is versioned, and specifies which implementation should be used to back instances of that
class.
The Override Asset Class Name is used when the asset class name in the registry differs from the asset
class name as it is understood by the implementation. This situation can occur when templates are used.
Asset Implementations
The asset implementations section lists all asset implementations currently known to the DAAL. Asset
implementations are the actual code that will be run to back object instances of a custom object asset
class. This code may take the form of a shared library that complies to the DAAL C Plug-in API ("native"
implementations), or may be "chained".
Native asset implementations are shared library files that must comply to the DAAL C Plug-in API.
Implementations of this type are loaded and called directly by the DAAL to service custom object operations. Native implementations must always have a empty Handler Implementation field. Native implementations should always have a known Implementation API version. This version describes the revision
of the plug-in/DAAL interface that the plug-in conforms to. Not all versions of the DAAL may support all
API versions.
Chained implementations are implementations that are not understood directly by the DAAL. Rather, the
DAAL calls a "handler" implementation that is given the chained implementation. Such handler implementations also go by the name "adapter plug-ins", but there is really nothing special about them. Adapter
plug-ins implement the same C Plug-in API as native implementations. What format chained implementations take is dictated by the adapter plug-in specified. Chained implementations must have a Handler
Implementation field that points to a valid adapter plug-in implementation. Chained implementations
should always have a unknown Implementation API version, since chained plug-ins should conform to an
API specification dictated by their handler plug-in, which is unknown to the core DAAL logic.
Currently, one adapter plug-in is provided with the RSCD agent, the External Program Adapter or EPA.
The EPA provides a way to implement DAAL custom object functionality with an external program or
script. The interface between the EPA plug-in and implementations that specify the EPA as their Handler Implementation is beyond the scope of this document.

NSH

daalinfo(1)

daalinfo(1)

All files comprising an implementation will be listed. The file listing consists of three parts separated by
the pipe ("|") character. The first part specifies the file type, the second part shows the MD5 hash of the
file, and the third part shows the path to the file.
The file type may be either Directory or File.
The MD5 checksum will only be computed for files of type File. For implementation files of type File a
missing MD5 checksums indicates that the file could not be found. Normally this should be considered an
error, but is expected for built-in implementations. (See BUILT-IN OBJECTS and BUGS below.) Directory implementation files will have a blank MD5 checksum.
Note: it is possible for asset implementations to exist in the registry that are not used being used by any
asset classes.

OPTIONS
daalinfo has no command line options.

BUILT-IN OBJECTS
The DAAL models itself as a collection of DAAL plug-in backed custom objects. Because of this, some of
the asset classes and asset implementations reported by daalinfo should be considered built-in and
immutable. Most built-in objects will report a version of 0, but this is subject to change in future releases.
Built-in asset implementations are not stored in the registry like normal asset implementations are. Because
of this, daalinfo will not report MD5 checksums for these implementation files.
As of the current release, the following asset classes and asset implementations are built-in. The model
behind built-in objects is private. Instances of objects of these classes are not available for manipulation by
end-users.
Built-in asset classes:
/DAALRegistry
Object class to represent the DAAL registry itself.
/AssetClass
Object class to represent an asset class.
/Implementation
Object class to represent an asset class implementation.
/Containers
Object class for internal organization. This does not represent anything concrete.
/AssetContainer
Object class to represent container assets that may be supplied to other custom object instances.
Built-in asset implementations:
/DAALMgt
Implementation used to manage DAAL with the DAAL.
/Container
Implementation used to back asset containers.
It is possible that distributions may be installed with bundled asset classes or implementations. These are
not built-in, and are treated as true equals with any user supplied custom object asset class or implementation.

NSH

daalinfo(1)

daalinfo(1)

DIAGNOSTICS
daalinfo should return non-zero if any errors or warnings are encountered.

ENVIRONMENT
Built-in objects are implemented as plug-ins just like any user supplied custom object. Unlike user-supplied objects, built-in objects are not upgradable through the normal object management interfaces, and
have their implementation shared libraries installed with the product code rather than in the registry.
Because of this, the implementation shared libraries of built-in objects are loaded with "naked" library
names. These libraries are expected to be locatable through normal operating system mechanisms, just as
the daalinfo command itself is located by PATH settings. Different operating systems use different mechanisms for determining shared library locations, but common methods include the ld.so.conf file, the
LD_LIBRARY_PATH environment variable, the SHLIB_PATH environment variable, and the LIBPATH
environment variable. Check with your operating system documentation for details.

BUGS
- MD5 sums are not displayed for built-in asset implementation files.

EXAMPLE
Display information about the current local hosts DAAL registry:
nsh% daalinfo
=== Registry ==========================================
Registry Root : /usr/nsh/daal
Timestamp : 1223403691
Asset Class Count : 16
Asset Implementation Count : 9
=== Asset Classes =====================================
Asset Class Name : /DAALRegistry
Version : 0
Override Asset Class Name :
Implementation : /DAALMgt
Asset Class Name : /AssetClass
Version : 0
Override Asset Class Name :
Implementation : /DAALMgt
Asset Class Name : /Implementation
Version : 0
Override Asset Class Name :
Implementation : /DAALMgt
Asset Class Name : /AssetContainer
Version : 0
Override Asset Class Name :
Implementation : /Container
Asset Class Name : /Containers
Version : 0
Override Asset Class Name :
Implementation : /Container

NSH

daalinfo(1)

daalinfo(1)

Asset Class Name : /BMC_UnixDaemon


Version : 1
Override Asset Class Name :
Implementation : /BMC_UnixDaemons_libdaalpluginunixdaemon.so
Asset Class Name : /BMC_UnixDaemons
Version : 1
Override Asset Class Name :
Implementation : /BMC_UnixDaemons_libdaalpluginunixdaemon.so
Asset Class Name : /MyClass2
Version : 1
Override Asset Class Name :
Implementation : /MyCustomObjectScript
Asset Class Name : /MyClass1
Version : 1
Override Asset Class Name :
Implementation : /MyCustomObjectScript
Asset Class Name : /MyRootClass
Version : 1
Override Asset Class Name :
Implementation : /MyCustomObjectScript

=== Asset Implementations =============================


Implementation Name : /DAALMgt
Version : 0
Handler Implementation :
Implementation API Version : BLPLUGIN_VERSION_XETA (13)
Implementation File : File||libdaalplugindaalmgt.so
Implementation Name : /Container
Version : 0
Handler Implementation :
Implementation API Version : BLPLUGIN_VERSION_ETA (12)
Implementation File : File||libdaalplugincontainer.so
Implementation Name : /ExternalProgramAdapter
Version : 1
Handler Implementation :
Implementation API Version : BLPLUGIN_VERSION_ETA (12)
Implementation File : File|16547abf4eb258fd9b2d2f81704aee20|/usr/nsh/daal/
Implementation Name : /BMC_UnixDaemons_libdaalpluginunixdaemon.so
Version : 1
Handler Implementation :
Implementation API Version : ERROR
ERROR: Error in dlopen("/usr/nsh/daal/Implementation/BMC_UnixDaemons_libdaalpl
Implementation File : File||/usr/nsh/daal/Implementation/BMC_UnixDaemons_l
Implementation Name : /MyCustomObjectScript
Version : 1

NSH

daalinfo(1)

daalinfo(1)

Handler Implementation : /ExternalProgramAdapter


Implementation API Version : BLPLUGIN_VERSION_UNKNOWN (0)
Implementation File : Directory||/usr/nsh/daal/Implementation/MyCustomObje
Implementation File : File|400e7b1225e5842c93c750f6ec532d9a|/usr/nsh/daal/
Implementation File : File|d148515b64f753f4709d0fdc0cfffa6d|/usr/nsh/daal/

SEE ALSO
rscd(1) bldeploy(1)

ORIGIN
The daalinfo utility was written by Carl Adams.

COPYRIGHT
Copyright (c) 2008 BMC Software Inc.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

dd(1)

dd(1)

NAME
dd - convert and copy a file

SYNOPSIS
dd [operands ...]

DESCRIPTION
The dd utility copies the standard input to the standard output. Input data is read and written in 512-byte
blocks. If input reads are short, input from multiple reads are aggregated to form the output block. When
finished, dd displays the number of complete and partial input and output blocks and truncated input
records to the standard error output.
The following operands are available:
bs=n

Set both input and output block size, superseding the ibs and obs operands. If no conversion values other than noerror, notrunc or sync are specified, then each input block is copied to the output as a single block without any aggregation of short blocks.

cbs=n

Set the conversion record size to n bytes. The conversion record size is required by the record
oriented conversion values.

count=n Copy only n input blocks.


files=n

Copy n input files before terminating. This operand is only applicable when the input device is a
tape.

ibs=n

Set the input block size to n bytes instead of the default 512.

if=file

Read input from file instead of the standard input.

obs=n

Set the output block size to n bytes instead of the default 512.

of=file

Write output to file instead of the standard output. Any regular output file is truncated unless the
notrunc conversion value is specified. If an initial portion of the output file is skipped (see the
seek operand) the output file is truncated at that point.

seek=n

Seek n blocks from the beginning of the output before copying. On non-tape devices, a lseek(2)
operation is used. Otherwise, existing blocks are read and the data discarded. If the user does not
have read permission for the tape, it is positioned using the tape ioctl(2) function calls. If the
seek operation is past the end of file, space from the current end of file to the specified offset is
filled with blocks of NUL bytes.

skip=n

Skip n blocks from the beginning of the input before copying. On input which supports seeks, a
lseek(2) operation is used. Otherwise, input data is read and discarded. For pipes, the correct
number of bytes is read. For all other devices, the correct number of blocks is read without distinguishing between a partial or complete block being read.

conv= value[, value ...]


Where value is one of the symbols from the following list.
ascii, oldascii
The same as the unblock value except that characters are translated from ECBDIC to
ASCII before the records are converted. (These values imply unblock if the operand
cbs is also specified.) There are two conversion maps for ASCII. The value ascii specifies the recommended one which is compatible with System V. The value oldascii
specifies the one used in historic AT&T and pre-4.3BSD-reno systems.
block

Treats the input as a sequence of newline or end-offile terminated variable length


records independent of input and output block boundaries. Any trailing newline character is discarded. Each input record is converted to a fixed length output record where
the length is specified by the cbs operand. Input records shorter than the conversion
record size are padded with spaces. Input records longer than the conversion record
size are truncated. The number of truncated input records, if any, are reported to the
standard error output at the completion of the copy.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

dd(1)

dd(1)

ebcdic, ibm, oldebcdic, oldibm


The same as the block value except that characters are translated from ASCII to
EBCDIC after the records are converted. (These values imply block if the operand cbs
is also specified.) There are four conversion maps for EBCDIC. The value ebcdic specifies the recommended one which is compatible with AT&T System V UNIX. The
value ibm is a slightly different mapping, which is compatible with the AT&T System
V UNIX ibm value. The values oldebcdic and oldibm are maps used in historic AT&T
and pre-4.3BSD-reno systems.
lcase

Transform uppercase characters into lowercase characters.

noerror

Do not stop processing on an input error. When an input error occurs, a diagnostic
message followed by the current input and output block counts will be written to the
standard error output in the same format as the standard completion message. If the
sync conversion is also specified, any missing input data will be replaced with NUL
bytes (or with spaces if a block oriented conversion value was specified) and processed
as a normal input buffer. If the sync conversion is not specified, the input block is
omitted from the output. On input files which are not tapes or pipes, the file offset will
be positioned past the block in which the error occurred using lseek(2).

notrunc Do not truncate the output file. This will preserve any blocks in the output file not
explicitly written by dd The notrunc value is not supported for tapes.
osync

Pad the final output block to the full output block size. If the input file is not a multiple
of the output block size after conversion, this conversion forces the final output block to
be the same size as preceding blocks for use on devices that require regularly sized
blocks to be written. This option is incompatible with use of the bs=n block size specification.

swab

Swap every pair of input bytes. If an input buffer has an odd number of bytes, the last
byte will be ignored during swapping.

sync

Pad every input block to the input buffer size. Spaces are used for pad bytes if a block
oriented conversion value is specified, otherwise NUL bytes are used.

ucase

Transform lowercase characters into uppercase characters.

unblock Treats the input as a sequence of fixed length records independent of input and output
block boundaries. The length of the input records is specified by the cbs operand. Any
trailing space characters are discarded and a newline character is appended.
Where sizes are specified, a decimal number of bytes is expected. If the number ends with a b, k,
m or w, the number is multiplied by 512, 1024 (1K), 1048576 (1M) or the number of bytes in an integer, respectively. Two or more numbers may be separated by an x to indicate a product.
When finished, dd displays the number of complete and partial input and output blocks, truncated input
records and odd-length byte-swapping blocks to the standard error output. A partial input block is one
where less than the input block size was read. A partial output block is one where less than the output
block size was written. Partial output blocks to tape devices are considered fatal errors. Otherwise, the rest
of the block will be written. Partial output blocks to character devices will produce a warning message. A
truncated input block is one where a variable length record oriented conversion value was specified and the
input line was too long to fit in the conversion record or was not newline terminated.
Normally, data resulting from input or conversion or both are aggregated into output blocks of the specified
size. After the end of input is reached, any remaining output is written as a block. This means that the final
output block may be shorter than the output block size.
If dd receives a SIGINFO (see the status argument for stty(1)) signal, the current input and output block
counts will be written to the standard error output in the same format as the standard completion message.
If dd receives a SIGINT signal, the current input and output block counts will be written to the standard
error output in the same format as the standard completion message and dd will exit.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

dd(1)

dd(1)

The dd utility exits 0 on success and >0 if an error occurred.

ORIGIN
Dd includes software developed by the University of California, Berkeley and its contributors. Please see
the intro section for complete acknowledgements.

SEE ALSO
cp(1), tr(1)

STANDARDS
The dd utility is expected to be a superset of the IEEE Std1003.2 (POSIX) standard. The files operand
and the ascii, ebcdic, ibm, oldascii, oldebcdic and oldibm values are extensions to the POSIX standard.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

df(1)

df(1)

NAME
df Execute remote df command

SYNOPSIS
df [df options] [target ...]

DESCRIPTION
For each named target, which may be a directory or host name, df will execute a remote df command on
the appropriate host and then print the returned output. If one of the targets is a directory name only, then
df uses the current host (as directed by nsh) as the remote host. If you do not specify any targets, df again
uses the current host.

OPTIONS
df on its own does not support any options. Any options it does find are passed to the remote df command.

EXAMPLE
The first example displays the disk usage of a remote host. The second example displays the disk usage of
the current directory of the current host and also the disk usage of a remote directory.
paris $ df -k //athens
paris $ df . //rome/tmp

CAVEATS
Remote df commands typically output a one line header as part of the disk usage report. Since a remote df
command is executed for each named target, this header line will be included for each named target.

ORIGIN
df was written by Thomas Kraus

NSH

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

DIFF (1)

DIFF (1)

NAME
diff differential file and directory comparator
SYNOPSIS
diff
diff
diff
diff
diff

[ abdilpqtTw] [ I pattern] [ c | e | f | n | u] [ L label] file1 file2


[ abdilpqtTw] [ I pattern] [ L label] C number file1 file2
[ abdilqtw] [ I pattern] D string file1 file2
[ abdilpqtTw] [ I pattern] [ L label] U number file1 file2
[ abdilNPpqtTw] [ I pattern] [ c | e | f | n | u] [ L label] [ r] [ s]
[ S name] [ X file] [ x pattern] dir1 dir2

DESCRIPTION
The diff utility compares the contents of file1 and file2 and writes to the standard output the list of
changes necessary to convert one file into the other. No output is produced if the files are identical.
Output options (mutually exclusive):
c

Produces a diff with 3 lines of context. With c the output format is modified slightly: the output
begins with identification of the files involved and their creation dates and then each change is separated by a line with fifteen s. The lines removed from file1 are marked with - ; those added to
file2 are marked + . Lines which are changed from one file to the other are marked in both files
with ! . Changes which lie within 3 lines of each other are grouped together on output.

Produces output in a form suitable as input for the editor utility, ed(1), which can then be used to
convert file1 into file2.
Extra commands are added to the output when comparing directories with e, so that the result is a
sh(1) script for converting text files which are common to the two directories from their state in
dir1 to their state in dir2.

Identical output to that of the e flag, but in reverse order. It cannot be digested by ed(1).

Produces a script similar to that of e, but in the opposite order and with a count of changed lines
on each insert or delete command. This is the form used by rcsdiff(1).

Just print a line when the files differ. Does not output a list of changes.

Produces a unified diff with 3 lines of context. A unified diff is similar to the context diff produced
by the c option. However, unlike with c, all lines to be changed (added and/or removed) are
present in a single section.

C number
Like c but produces a diff with number lines of context.
D string
Creates a merged version of file1 and file2 on the standard output, with C preprocessor controls included so that a compilation of the result without defining string is equivalent to compiling file1, while defining string will yield file2.
U number
Like u but produces a diff with number lines of context.
Comparison options:
a

BSD

Treat all files as ASCII text. Normally diff will simply print Binary files . . . differ if files contain binary characters. Use of this option forces diff to produce a diff.

July 21, 2003

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

DIFF (1)

DIFF (1)

Causes trailing blanks (spaces and tabs) to be ignored, and other strings of blanks to compare equal.

Try very hard to produce a diff as small as possible. This may consume a lot of processing power
and memory when processing large files with many changes.

I pattern
Ignores changes, insertions, and deletions whose lines match the extended regular expression
pattern. Multiple I patterns may be specified. All lines in the change must match some pattern for the change to be ignored. See re_format(7) for more information on regular expression
patterns.
i

Ignores the case of letters. E.g., A will compare equal to a.

Long output format; each text file diffd is piped through pr(1) to paginate it; other differences
are remembered and summarized after all text file differences are reported.

L label
Print label instead of the first (and second, if this option is specified twice) file name and time in
the context or unified diff header.
p

With unified and context diffs, show with each change the first 40 characters of the last line before
the context beginning with a letter, an underscore or a dollar sign. For C source code following
standard layout conventions, this will show the prototype of the function the change applies to.

Will expand tabs in output lines. Normal or c output adds character(s) to the front of each line
which may screw up the indentation of the original source lines and make the output listing difficult
to interpret. This option will preserve the original sources indentation.

Print a tab rather than a space before the rest of the line for the normal, context or unified output formats. This makes the alignment of tabs in the line consistent.

Is similar to b but causes whitespace (blanks and tabs) to be totally ignored. E.g., if ( a == b )
will compare equal to if(a==b).

Directory comparison options:


N

If a file is found in only one directory, act as if it was found in the other directory too but was of zero
size.

If a file is found only in dir2, act as if it was found in dir1 too but was of zero size.

Causes application of diff recursively to common subdirectories encountered.

Causes diff to report files which are the same, which are otherwise not mentioned.

S name
Re-starts a directory diff in the middle, beginning with file name.
X file
Exclude files and subdirectories from comparison whose basenames match lines in file. Multiple
X options may be specified.
x pattern
Exclude files and subdirectories from comparison whose basenames match pattern. Patterns are
matched using shell-style globbing via fnmatch(3). Multiple x options may be specified.
If both arguments are directories, diff sorts the contents of the directories by name, and then runs the regular file diff algorithm, producing a change list, on text files which are different. Binary files which differ,
common subdirectories, and files which appear in only one directory are described as such. In directory
mode only regular files and directories are compared. If a non-regular file such as a device special file or

BSD

July 21, 2003

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

DIFF (1)

DIFF (1)

FIFO is encountered, a diagnostic message is printed.

If only one of file1 and file2 is a directory, diff is applied to the non-directory file and the file contained in the directory file with a filename that is the same as the last component of the non-directory file.
If either file1 or file2 is , the standard input is used in its place.
Output Style
The default (without e, c, or n options) output contains lines of these forms, where XX, YY, ZZ, QQ are
line numbers respective of file order.
At (the end of) line XX of file1, append the contents of line YY of file2 to make them
equal.
XXaYY,ZZ
Same as above, but append the range of lines, YY through ZZ of file2 to line XX of file1.
XXdYY
At line XX delete the line. The value YY tells to which line the change would bring file1
in line with file1.
XX,YYdZZ
Delete the range of lines XX through YY in file1.
XXcYY
Change the line XX in file1 to the line YY in file2.
XX,YYcZZ
Replace the range of specified lines with the line ZZ.
XX,YYcZZ,QQ Replace the range XX,YY from file1 with the range ZZ,QQ from file2.
XXaYY

These lines resemble ed(1) subcommands to convert file1 into file2. The line numbers before the
action letters pertain to file1; those after pertain to file2. Thus, by exchanging a for d and reading the
line in reverse order, one can also determine how to convert file2 into file1. As in ed(1), identical pairs
(where num1 = num2) are abbreviated as a single number.
ENVIRONMENT
TMPDIR If the environment variable TMPDIR exists, diff will use the directory specified by TMPDIR as
the temporary directory.
FILES
/tmp/diff.XXXXXXXX Temporary file used when comparing a device or the standard input. Note that
the temporary file is unlinked as soon as it is created so it will not show up in a
directory listing.
DIAGNOSTICS
The diff utility exits with one of the following values:
0
1
>1

No differences were found.


Differences were found.
An error occurred.

SEE ALSO
cmp(1), comm(1), diff3(1), ed(1), pr(1), fnmatch(3), re_format(7)
STANDARDS
The diff utility is expected to be a superset of the 1003.1-2001 specification.
HISTORY
A diff command appeared in Version 6 AT&T UNIX.
BUGS
When comparing directories with the b, w or i options specified, diff first compares the files ala
cmp(1), and then decides to run the diff algorithm if they are not equal. This may cause a small amount of

BSD

July 21, 2003

DIFF (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

DIFF (1)

spurious output if the files then turn out to be identical because the only differences are insignificant whitespace or case differences.

BSD

July 21, 2003

Property of BladeLogic, Inc.


Strictly confidential and proprietary

dsync(1)

dsync(1)

NAME
dsync Synchronize two directories

SYNOPSIS
dsync [-bdifmnopPrtuvBCLPRST?] [-s suf] [-IX wildcarded path] dir1 dir2

DESCRIPTION
The dsync command is a link to the cp command. When you run cp as dsync, it attempts to synchronize
the contents of two directories. The default behavior of dsync is equivalent to making a conditional copy
with the cp command.
$ dsync dir1 dir2
is equivalent to:
$ cp -fpru dir1 dir2
This does a copy of all files and directories in the directory dir1 to directory dir2 only if the file size or date
of last modification are different, while preserving the file ownerships, permissions, and access times. If
the target directory dir2 does not exist, then it will be created.

OPTIONS
The dsync command has the same options as the cp command with the addition of the -d option. All
options are described here.
-d

Use this option with care, because it deletes any files/directories in the target (dir2) directory that
are not in the source (dir1) directory. This lets you make sure that there are no extra files in the
target directory and is conceptually equivalent to first removing the target directory and then recreating it from the source directory.

-m

Synchronize file permissions for files that do not need to be updated. By default, if dsync finds a
file that does not need to be updated, it leaves it alone. This option however does a further check
on the files permissions and makes sure that the target file has the same permissions as the source
file, changing the target files permissions if necessary.
Be careful about using this option when you are copying between UNIX and Windows type systems, because the security models for file permissions may differ.

-o

Synchronize file ownerships for files that do not need to be updated. By default, if dsync finds a
file that does not need to be updated, it leaves it alone. This option however does a further check
on the files ownership (UID and GID) and (if necessary) updates the destination files user/group
ownerships to match the source files user/group ownerships.
The ownership comparisons are based on the respective numeric UID and GID and not the
respective user/group name that a particular UID/GID may be mapped to on a particular system.
Note that you need root permissions to change file ownerships. Also, be careful about using this
option when you are copying between UNIX and Windows type systems, because the security
models for file ownerships may differ.

The following options are the common options between cp and dsync with dsync having, by default,
turned on the following options: -r, -p, -f, and -u. (The -P option is not turned on by default, however when
running dsync, it has same behavior as if -P had been turned on).
-b

Backup the target file, if it exists, before copying over the new source file. By default, cp appends
the target file name with the suffix "". You can use the -s suf option to specify a different suffix.

-i

If a target file already exists, then cp will prompt the user to see if the user wants cp to overwrite
the file. If the user confirms with an entry beginning with the letter y, then cp overwrites the file.
See UNIVERSE BEHAVIOR for details on how this option interacts with the -f option.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

dsync(1)

dsync(1)

-f

By default, if the target file already exists, it will retain its current file permissions after cp overwrites it. This option deletes the target file before the copy begins, so that the target file inherits
the same file permissions as the source file.

-n

Dont actually make any changes. This option automatically turns on the verbose option -v and
just lists the copies that cp would make if you had not turned on the -n option. cp does not create
or remove any files or directories. This option is useful when you are performing a conditional
copy and you just want to see what files would be copied if you were doing a real copy. This
option turns off the -i option.

-p

With this option, cp will attempt to give the target file the same ownerships (UID/GID), permissions, and access and modification times as the source file. This also applies to new directories
being created.

-r

With this option, if one of the files to be copied is a directory, then cp recursively copies all files
and sub-directories from the directory into the target directory. If the target directory does not
already exist, then cp will create the directory as required. If the target directory does already
exist, then cp will create the new target directory within the (existing) target directory.

-s suf

Set the suffix for backup files to suf. The default suffix for files being backed up is "" (foo.c
becomes foo.c)

-t

Make a textual copy of the file. This option is useful when copying text files to or from a Windows based system. This option will ensure proper handling of the <CR><LF> issues.

-u

There are three options you can use to perform conditional copies. They are -T, -S and -C. The
-u option is equivalent to using the -T and -S options. These options cause the target file to be
overwritten only if either the file sizes differ or if the source file has a newer modification date
than the target file.

-v

Output a message for each file being copied. Useful for monitoring progress in a recursive copy.

-B

Like -b except that if the backup version of the file already exists then the backup will not be
overwritten.

-C

Conditional copy. cp will overwrite the target file only if its content differs from the source file.
This option implies the -S option. If the file sizes are the same, cp will perform a byte for byte
analysis of the source and target file to determine if a difference exists. This option can be very
resource intensive, especially on a large file.

-I (wildcarded path)
This option includes the specified files/directories in the sync operation.
-L

When recursing through directories, follow symbolic links.

-P

This is the no parent option. This option is useful when (recursively) copying the content of one
directory to another existing directory. The default action would be to re-create the source directory in the destination directory. With the -P option, the content of the source directory is re-created in the target directory essentially overlaying the source directory on to the destination instead
of creating the subdirectory.

-R

This option is the same as the -r option, except that newly created directories automatically get
the user permissions read, write, and execute. If you use this option with the -p option, then the
-R option is treated as a -r option.

-S

Conditional copy. This option tells cp to overwrite target files only if source and target file sizes
differ. See the -u option.

-T

Conditional copy. This option tells cp to overwrite target files only if the modification date of the
source file is newer than the modification date of the target file. See the -u option.

-X (wildcarded path)
This option excludes the specified files/directories from the sync operation.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

dsync(1)

-?

dsync(1)

Output a brief summary of available options and then exit with a zero status without copying any
files.

EXAMPLE
The first example synchronizes the content of the www directory with the www directory on the machine
webserver. The second example does the same as the first, but it gives verbose output and it deletes any
files and directories on the webserver which do not exist in the local www directory.
$ dsync www //webserver/www
$ dsync -vd www //webserver/www

DIAGNOSTICS
dsync: Target directory (dirname) not found
When copying multiple files to a directory, this message will appear if dsync is unable to access
the target directory (last argument).
dsync: Target file (filename) must be a directory
When copying multiple files to a directory, this message will appear if the target directory (last
argument) is not a directory.
dsync: Unable to create directory dirname
When dsync is recursively copying a directory, it may need to create new directories in the target
directory tree. If dsync is not able to create one of these directories, it outputs this message.
dsync: Unable to access directory dirname
When dsync is recursively copying a directory, it traverses the source directory hierarchy. If
dsync has a problem accessing a directory, it outputs this message.
dsync: file filename is a directory (not copied)
If one of the files to be copied is a directory and you did not specify the recursive option (-r), then
dsync outputs this message, indicating that it cannot copy directories.
dsync: Unable to access file filename
dsync: Unable to read file filename
If dsync is unable to access the source file filename, it will output this message, along with the
possible reason as to why it was not able to access the file.
dsync: Unable to create file filename
If dsync cannot create the new target file, it will output this message, along with the possible reason as to why it could not create the file filename.
dsync: Error writing to file filename
If an error occurs while copying a file into the new target file, dsync outputs this message, indicating that the copy may not be complete.

EXIT CODES
0

No errors detected.

Unknown option or missing file argument.

dsync was unable to copy all files requested.

255

Unable to get a license to use the software.

UNIVERSE BEHAVIOR
If you specify both the -i and -f options, then with the P_BSD variable set (Berkeley behavior), the -i option
will override the -f option. With the P_ATT variable set, the -f option will override the -i option.

ORIGIN
dsync was written by Thomas Kraus.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

dsync(1)

dsync(1)

SEE ALSO
cp(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

du(1)

du(1)

NAME
du Display disk usage information for files

SYNOPSIS
du -[adfkosrux?] [filename ...]

DESCRIPTION
du calculates the number of blocks that the file system has allocated for all named files and directories. du
searches directories recursively, and outputs a sub-total for all sub-directories. If you do not specify any
files or directories, du displays disk usage information for the current directory.
du counts files with multiple links only once.

OPTIONS
-a

Output a disk usage statement for each file encountered in the directory hierarchy. (By default, du
outputs a disk usage statement for directories only.)

-d

If, while traversing a directory, du comes across a directory that is not in the same partition as the
source directory, then do not include the contents of that directory in the disk usage summary.

-f

Same as -d.

-k

Report disk usage totals in KB instead of blocks. This option has meaning only when the P_ATT
variable is set. When the P_BSD variable is set, findings are already reported in KB.

-o

This option tells du not to count the disk usage of sub-directories when calculating the disk usage
of a directory. This effectively causes du to count only the disk usage of files in the directory. du
ignores this option if you also specify the -s option.

-S

Display a grand total at the end of all computations.

-s

Instead of outputting a disk usage statement for each directory encountered, output only a summary for all directories searched. This gives you a grand total of disk usage for the named directories. du ignores this option if you also specify the -a option.

-r

Report the directories that du cannot search. See the UNIVERSE BEHAVIOR section for information on how du handles this option.

-u

By default, du counts linked files only once. With this option, du ignores all files with more than
one link.

-x

Same as -d.

-?

Output a brief summary of available options and then exit with a zero status without doing disk
usage summarizing.

EXAMPLE
The first example will output the amount of disk usage of the directory src giving sub-totals of all its subdirectories. The second example will give the total amount of disk usage of the root partition on host vilnius in KB.
$ du src
$ du -fsk //vilnius/

DIAGNOSTICS
du: Unable to access directory dirname
Unable to descend into the directory dirname to determine its size.
du: Unable to access file filename
Unable to determine the status (size) of file filename.

EXIT CODES
0

No errors detected.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

du(1)

You specified an unknown option.

du was unable to access to access a directory or determine the size of a file.

255

Unable to get a license to use the software.

du(1)

UNIVERSE BEHAVIOR
With the P_BSD variable set (Berkeley behavior), du automatically reports any errors encountered while
trying to access a directory. With the P_ATT variable set, du does not report errors, unless you specify the
-r option.
Furthermore, the universe flag determines the size of a block. With the P_BSD variable set (Berkeley
behavior), du assumes that a block is 1K large. With the P_ATT variable set, du assumes that a block is
512 bytes large.

ORIGIN
du was written by Thomas Kraus.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

echo(1)

echo(1)

NAME
echo Echo arguments

SYNOPSIS
echo [-?] [-n] [arg ...]

DESCRIPTION
echo outputs each of its arguments separated by a space and then outputs a new-line character. If echo
finds a backslash \ in an argument, then it looks at the next character and interprets it as follows:
b

Backspace (OCT 010, DEC 8, HEX 8).

Do not output a new-line at the end.

Form feed (OCT 014, DEC 12, HEX C).

new line (OCT 012, DEC 10, HEX A).

carriage return (OCT 015, DEC 13, HEX D).

tab (OCT 011, DEC 9, HEX 9).

vertical tab (OCT 013, DEC 11, HEX B).

backslash (OCT 0134, DEC 92, HEX 5C).

The main advantage of using echo over the built in echo command in the sh(1) is that it understands file
wildcarding on remote hosts. File wildcards interpreted by sh(1) are for local files only. Notice the different
outputs when accessing remote files.
$ echo //stockholm/etc/pa*
//stockholm/etc/p*
$ echo //stockholm/etc/pa*
//stockholm/etc/password //stockholm/etc/password.old

OPTIONS
-n

Output a line without a new-line character.

-?

Output a brief summary of available options and then exit with a zero status without echoing any
arguments.

arg

Argument to be echoed.

EXAMPLE
$ echo "Hello world\c"
$ echo //stockholm/etc/p*

EXIT CODES
0

No errors detected.

You specified an unknown option.

255

Unable to get a license to use the software.

ORIGIN
echo was written by Thomas Kraus.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

expand(1)

expand(1)

NAME
expand, unexpand - expand tabs to spaces, and vice versa

SYNOPSIS
expand [-tabstop] [-tab1,tab2,...,tabn] file ...
unexpand [-a] file ...

DESCRIPTION
Expand processes the named files or the standard input writing the standard output with tabs changed into
blanks. Backspace characters are preserved into the output and decrement the column count for tab calculations. Expand is useful for pre-processing character files (before sorting, looking at specific columns,
etc.) that contain tabs.
If a single tabstop argument is given, then tabs are set tabstop spaces apart instead of the default 8. If multiple tabstops are given then the tabs are set at those specific columns.
Unexpand puts tabs back into the data from the standard input or the named files and writes the result on
the standard output.
Option (with unexpand only):
-a

By default, only leading blanks and tabs are reconverted to maximal strings of tabs. If the -a
option is given, then tabs are inserted whenever they would compress the resultant file by replacing two or more characters.

ORIGIN
Expand and unexpand includes software developed by the University of California, Berkeley and its contributors. Please see the intro section for complete acknowledgements.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

fields(1)

fields(1)

NAME
fields extracts specified fields from a data row

SYNOPSIS
fields [-d c | -D c] <field#>

DESCRIPTION
The fields command extracts specified fields from a data row. A field separator distinguishes the fields in
each row.
If you specify a positive field number, such as 5, the fifth field from the start of the data row is extracted. If
you specify a negative field number, such as -2, the second field from the end of the data row is extracted.
If the field number is 0, the entire data row is extracted.

OPTIONS
-d or -D Specifies the separator character used to distinguish the individual fields. If this option is not provided, the space character ( ) is used as the default separator.

EXAMPLES
Consider the following input file. It contains fields separated by the : character.
% cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/bin/bash
daemon:x:2:2:Daemon:/sbin:/bin/bash
lp:x:4:7:Printing daemon:/var/spool/lpd:/bin/bash
mail:x:8:12:Mailer daemon:/var/spool/clientmqueue:/bin/false
games:x:12:100:Games account:/var/games:/bin/bash
wwwrun:x:30:8:WWW daemon apache:/var/lib/wwwrun:/bin/false
ftp:x:40:49:FTP account:/srv/ftp:/bin/bash
nobody:x:65534:65533:nobody:/var/lib/nobody:/bin/bash
ldap:x:76:70:User for OpenLDAP:/var/lib/ldap:/bin/bash
sshd:x:71:65:SSH daemon:/var/lib/sshd:/bin/false
ntp:x:74:65534:NTP daemon:/var/lib/ntp:/bin/false
postfix:x:51:51:Postfix Daemon:/var/spool/postfix:/bin/false
at:x:25:25:Batch jobs daemon:/var/spool/atjobs:/bin/bash
blade:x:1000:100::/home/blade:/bin/bash
smbguest:x:4000:4000::/dev/null:/bin/false
man:x:13:62:Manual pages viewer:/var/cache/man:/bin/bash
news:x:9:13:News system:/etc/news:/bin/bash
uucp:x:10:14:Unix-to-Unix CoPy system:/etc/uucp:/bin/bash
+::::::
% fields -d : 1 5 6 -1 < /etc/passwd
root root /root /bin/bash
bin bin /bin /bin/bash
daemon Daemon /sbin /bin/bash
lp Printing daemon /var/spool/lpd /bin/bash
mail Mailer daemon /var/spool/clientmqueue /bin/false
games Games account /var/games /bin/bash
wwwrun WWW daemon apache /var/lib/wwwrun /bin/false
ftp FTP account /srv/ftp /bin/bash
nobody nobody /var/lib/nobody /bin/bash
ldap User for OpenLDAP /var/lib/ldap /bin/bash
sshd SSH daemon /var/lib/sshd /bin/false
ntp NTP daemon /var/lib/ntp /bin/false
postfix Postfix Daemon /var/spool/postfix /bin/false

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

fields(1)

fields(1)

at Batch jobs daemon /var/spool/atjobs /bin/bash


blade /home/blade /bin/bash /bin/bash
smbguest /dev/null /bin/false /bin/false
man Manual pages viewer /var/cache/man /bin/bash
news News system /etc/news /bin/bash
uucp Unix-to-Unix CoPy system /etc/uucp /bin/bash
+ +

ORIGIN
fields was developed by BladeLogic, Inc.

NSH

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

FILE (1)

FILE (1)

NAME
file determine file type
SYNOPSIS
file [ bckLNnrsvz] [ F separator] [ f namefile] [ m magicfiles] file . . .
file [ m magicfiles] C
DESCRIPTION
The file utility tests each argument in an attempt to classify it. There are three sets of tests, performed in
this order: filesystem tests, magic number tests, and language tests. The first test that succeeds causes the file
type to be printed.
The type printed will usually contain one of the words text (the file contains only ASCII characters and is
probably safe to read on an ASCII terminal), executable (the file contains the result of compiling a program
in a form understandable to some UNIX kernel or another), or data meaning anything else (data is usually
binary or non-printable).
Exceptions are well-known file formats (core files, tar archives) that are known to contain binary data. When
modifying the file /etc/magic or the program itself, preserve these keywords.
People depend on knowing that all the readable files in a directory have the word text printed. Dont do as
Berkeley did; change shell commands text to shell script.
The filesystem tests are based on examining the return from a stat(2) system call. The program checks to
see if the file is empty, or if its some sort of special file. Any known file types appropriate to the system you
are running on (sockets, symbolic links, or named pipes (FIFOs) on those systems that implement them) are
intuited if they are defined in the system header file sys/stat.h.
The magic number tests are used to check for files with data in particular fixed formats. The canonical example of this is a binary executable (compiled program) a.out file, whose format is defined in a.out.h
and possibly exec.h in the standard include directory and is explained in a.out(5). These files have a
magic number stored in a particular place near the beginning of the file that tells the UNIX operating system that the file is a binary executable, and which of several types thereof.
The concept of magic number has been applied by extension to data files. Any file with some invariant identifier at a small fixed offset into the file can usually be described in this way. The information in these files is
read from the magic file /etc/magic.
If an argument appears to be an ASCII file, file attempts to guess its language. The language tests look for
particular strings (cf names.h) that can appear anywhere in the first few blocks of a file. For example, the
keyword .br indicates that the file is most likely a troff(1) input file, just as the keyword struct indicates a C program. These tests are less reliable than the previous two groups, so they are performed last.
The language test routines also test for some miscellany (such as tar(1) archives) and determine whether an
unknown file should be labelled as ASCII text or data.
The options are as follows:

BSD

Do not prepend filenames to output lines (brief mode).

For each magic number file, write a magic.mgc output file that contains a preparsed (compiled)
version of it.

Cause a checking printout of the parsed form of the magic file. This is usually used in conjunction
with m to debug a new magic file before installing it.

December 4, 2004

FILE (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

FILE (1)

F separator
Use the specified string as the separator between the filename and the file result returned. Defaults
to :.
f namefile
Read the names of the files to be examined from namefile (one per line) before the argument list.
Either namefile or at least one filename argument must be present; to test the standard input, use
- as a filename argument.
k

Dont stop at the first match, keep going.

Cause symlinks to be followed, as the like-named option in ls(1) (on systems that support symbolic
links).

m magiclist
Specify an alternate list, magiclist, of files containing magic numbers. This can be a single file
or a colon-separated list of files. If a compiled magic file is found alongside, it will be used instead.
N

Dont pad filenames so that they align in the output.

Force stdout to be flushed after checking each file. This is only useful if checking a list of files. It is
intended to be used by programs that want filetype output from a pipe.

Dont translate unprintable characters to \ooo. Normally file translates unprintable characters to
their octal representation (raw mode).

Normally, file only attempts to read and determine the type of argument files which stat(2)
reports are ordinary files. This prevents problems, because reading special files may have peculiar
consequences. Specifying the s option causes file to also read argument files which are block
or character special files. This is useful for determining the filesystem types of the data in raw disk
partitions, which are block special files. This option also causes file to disregard the file size as
reported by stat(2), since on some systems it reports a zero size for raw disk partitions.

Print the version of the program and exit.

Try to look inside files that have been run through compress(1).

ENVIRONMENT
MAGIC Default magic number files, separated by colon characters. file adds .mgc to the value of this
variable as appropriate.
FILES
/etc/magic default list of magic numbers
SEE ALSO
compress(1), hexdump(1), ls(1), od(1), strings(1), a.out(5), magic(5)
STANDARDS CONFORMANCE
This program is believed to exceed the System V Interface Definition of FILE(CMD), as near as one can
determine from the vague language contained therein. Its behaviour is mostly compatible with the System V
program of the same name. This version knows more magic, however, so it will produce different (albeit
more accurate) output in many cases.
The one significant difference between this version and System V is that this version treats any white space
as a delimiter, so that spaces in pattern strings must be escaped. For example,

BSD

December 4, 2004

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

FILE (1)

>10

string language impress

FILE (1)

(imPRESS data)

in an existing magic file would have to be changed to


>10

string language\ impress

(imPRESS data)

In addition, in this version, if a pattern string contains a backslash, it must be escaped. For example
0

string

\begindata

Andrew Toolkit document

in an existing magic file would have to be changed to


0

string

\\begindata Andrew Toolkit document

SunOS releases 3.2 and later from Sun Microsystems include a file command derived from the System V
one, but with some extensions. My version differs from Suns only in minor ways. It includes the extension
of the & operator, used as, for example,
>16

long&0x7fffffff >0

not stripped

MAGIC DIRECTORY
The magic file entries have been collected from various sources, mainly USENET, and contributed by various authors. Christos Zoulas (address below) will collect additional or corrected magic file entries. A consolidation of magic file entries will be distributed periodically. The order of entries in the magic file is significant. Depending on what system you are using, the order that they are put together may be incorrect. If
your old file command uses a magic file, keep the old magic file around for comparison purposes (rename
it to /etc/magic.orig).
HISTORY
There has been a file command in every UNIX since at least Research Version 4 (man page dated November, 1973). The System V version introduced one significant major change: the external list of magic number
types. This slowed the program down slightly but made it a lot more flexible.
This program, based on the System V version, was written by Ian F. Darwin ian@darwinisys.com without
looking at anybody elses source code.
John Gilmore revised the code extensively, making it better than the first version. Geoff Collyer found several inadequacies and provided some magic file entries. Contributions to the & operator by Rob McMahon
cudcv@warwick.ac.uk, 1989.
Guy Harris guy@auspex.com made many changes from 1993 to the present.
Primary development and maintenence from 1990 to the present by Christos Zoulas christos@zoulas.com.
Altered by Chris Lowth chris@lowth.com, 2000: Handle the i option to output mime type strings and
using an alternative magic file and internal logic.
Altered by Eric Fischer enf@pobox.com, July, 2000, to identify character codes and attempt to identify the
languages of non-ASCII files.
The list of contributors to the magdir directory (source for the /etc/magic file) is too long to include
here. You know who you are; thank you.
LEGAL NOTICE
Copyright (c) Ian F. Darwin, Toronto, Canada, 1986-1999. Covered by the standard Berkeley Software Distribution copyright; see the file LEGAL.NOTICE in the distribution.
The files tar.h and is_tar.c were written by John Gilmore from his public-domain tar program, and
are not covered by the above license.

BSD

December 4, 2004

FILE (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

FILE (1)

BUGS
There must be a better way to automate the construction of the Magic file from all the glop in Magdir. What
is it? Better yet, the magic file should be compiled into binary (say, ndbm(3) or, better yet, fixed-length
ASCII strings for use in heterogenous network environments) for faster startup. Then the program would run
as fast as the Version 7 program of the same name, with the flexibility of the System V version.
file uses several algorithms that favor speed over accuracy; thus it can be misled about the contents of
ASCII files.
The support for ASCII files (primarily for programming languages) is simplistic, inefficient and requires
recompilation to update.
There should be an else clause to follow a series of continuation lines.
The magic file and keywords should have regular expression support. Their use of ASCII TAB as a field
delimiter is ugly and makes it hard to edit the files, but is entrenched.
It might be advisable to allow upper-case letters in keywords for e.g., troff(1) commands vs man page
macros. Regular expression support would make this easy.
The program doesnt grok FORTRAN. It should be able to figure FORTRAN by seeing some keywords which
appear indented at the start of line. Regular expression support would make this easy.
The list of keywords in ascmagic probably belongs in the Magic file. This could be done by using some
keyword like for the offset value.
Another optimization would be to sort the magic file so that we can just run down all the tests for the first
byte, first word, first long, etc, once we have fetched it. Complain about conflicts in the magic file entries.
Make a rule that the magic entries sort based on file offset rather than position within the magic file?
The program should provide a way to give an estimate of how good a guess is. We end up removing
guesses (e.g., From as first 5 chars of file) because they are not as good as other guesses (e.g.,
Newsgroups: versus "Return-Path:"). Still, if the others dont pan out, it should be possible to use the first
guess.
This program is slower than some vendors file commands.
This manual page, and particularly this section, is too long.
AVAILABILITY
You can obtain the original authors latest version by anonymous FTP on ftp.astron.com in the directory
/pub/file/file-X.YY.tar.gz.

BSD

December 4, 2004

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

FIND (1)

FIND (1)

NAME
find walk a file hierarchy
SYNOPSIS
find [ dHhLWXx] [ f path] path ... [expression]
DESCRIPTION
find recursively descends the directory tree for each path listed, evaluating an expression (composed
of the primaries and operands listed below) in terms of each file in the tree. In the absence of an expression, -print is assumed.
The options are as follows:
d

Causes find to visit directories in post-order i.e. all entries in a directory will be acted on before
the directory itself. By default, find visits directories in pre-order i.e. before their contents.

f path
Specifies a file hierarchy for find to traverse. File hierarchies may also be specified as the
operands immediately following the options.
H

Causes the file information and file type (see stat(2)) returned for each symbolic link encountered
on the command line to be those of the file referenced by the link, not the link itself. If the referenced file does not exist, the file information and type will be for the link itself. File information of
all symbolic links not on the command line is that of the link itself.

An alias for the L option. This option exists for backwards compatibility.

Causes the file information and file type (see stat(2)) returned for each symbolic link to be those
of the file referenced by the link, not the link itself. If the referenced file does not exist, the file
information and type will be for the link itself.

Permit find to be safely used in conjunction with xargs(1). If a file name contains any of the
delimiting characters used by xargs, a diagnostic message is displayed on standard error, and the
file is skipped. The delimiting characters include single ( ) and double ( " ) quotes, backslash
( \ ) , space, tab, and newline ( \n ) characters. Alternatively, the print0 primary may be
used in conjunction with the 0 option to xargs(1), allowing all file names to be processed safely.

Prevents find from descending into directories that have a device number different than that of the
file from which the descent began.

PRIMARIES
-amin n
True if the difference between the file last access time and the time find was started, rounded up to
the next full minute, is n minutes.
-anewer file
True if the current file has a more recent last access time than file.
-atime n
True if the difference between the file last access time and the time find was started, rounded up to
the next full 24-hour period, is n 24-hour periods.
-cmin n
True if the difference between the time of last change of file status information and the time find
was started, rounded up to the next full minute, is n minutes.

BSD

December 4, 1999

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

FIND (1)

FIND (1)

-cnewer file
True if the current file has a more recent last change time than file.
-ctime n
True if the difference between the time of last change of file status information and the time find
was started, rounded up to the next full 24-hour period, is n 24-hour periods.
-empty
True if the current file or directory is empty.
-exec utility [argument . . .];
True if the program named utility returns a zero value as its exit status. Optional arguments
may be passed to the utility. The expression must be terminated by a semicolon ( ; ) . If the string
"{}" appears anywhere in the utility name or the arguments it is replaced by the pathname of the
current file. utility will be executed from the directory from which find was executed.
-execdir utility [argument . . .];
Identical to the -exec primary with the exception that utility will be executed from the directory that holds the current file. The filename substituted for the string "{}" is not qualified.
-follow
Follow symbolic links.
-fstype type
True if the file is contained in a file system of type type. Two special file system types are recognized: local and rdonly. These do not describe actual file system types; the former matches any
file system physically mounted on the system where find is being executed whereas the latter
matches any file system which is mounted read-only.
-group gname
True if the file belongs to the group gname. If gname is numeric and there is no such group name,
then gname is treated as a group ID.
-iname pattern
True if the last component of the pathname being examined matches pattern. Case insensitive.
-inum n
True if the file has inode number n.
-links n
True if the file has n links.
-ls

This primary always evaluates to true. The following information for the current file is written to
standard output: its inode number, size in 512-byte blocks, file permissions, number of hard links,
owner, group, size in bytes, last modification time, and pathname. If the file is a block or character
special file, the major and minor numbers will be displayed instead of the size in bytes. If the file is
a symbolic link, the pathname of the linked-to file will be displayed preceded by >. The format
is identical to that produced by ls dgils.

-maxdepth n
True if the current search depth is less than or equal to what is specified in n.
-mindepth n
True if the current search depth is at least what is specified in n.
-mmin n
True if the difference between the file last modification time and the time find was started,
rounded up to the next full minute, is n minutes.

BSD

December 4, 1999

FIND (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

FIND (1)

-mtime n
True if the difference between the file last modification time and the time find was started,
rounded up to the next full 24-hour period, is n 24-hour periods.
-name pattern
True if the last component of the pathname being examined matches pattern. Special shell pattern matching characters ([, ], , and ?) may be used as part of pattern. These characters
may be matched explicitly by escaping them with a backslash ( \ ) .
-newer file
True if the current file has a more recent last modification time than file.
-nogroup
True if the file belongs to an unknown group.
-nouser
True if the file belongs to an unknown user.
-ok utility [argument . . .];
Identical to the -exec primary with the exception that find requests user affirmation for the
execution of utility by printing a message to the terminal and reading a response. If the
response is other than y the command is not executed and the value of the ok expression is false.
-path pattern
True if the pathname being examined matches pattern. Special shell pattern matching characters
([, ], , and ?) may be used as part of pattern. These characters may be matched explicitly by escaping them with a backslash ( \ ) . Slashes ( / ) are treated as normal characters and
do not have to be matched explicitly.
-perm [ ] mode
The mode may be either symbolic (see chmod(1)) or an octal number. If the mode is symbolic, a
starting value of zero is assumed and the mode sets or clears permissions without regard to the processs file mode creation mask. If the mode is octal, only bits 07777 (S_ISUID | S_ISGID |
S_ISTXT | S_IRWXU | S_IRWXG | S_IRWXO) of the files mode bits participate in the comparison.
If the mode is preceded by a dash ( ) , this primary evaluates to true if at least all of the bits in the
mode are set in the files mode bits. If the mode is not preceded by a dash, this primary evaluates to
true if the bits in the mode exactly match the files mode bits. Note, the first character of a symbolic
mode may not be a dash.
-print
This primary always evaluates to true. It prints the pathname of the current file to standard output,
followed by a newline ( \n ) character. If neither -exec, -ls, -ok, nor -print0 is specified,
the given expression shall be effectively replaced by (given expression) -print.
-print0
This primary always evaluates to true. It prints the pathname of the current file to standard output,
followed by a null character.
-prune
This primary always evaluates to true. It causes find to not descend into the current file. Note, the
-prune primary has no effect if the d option was specified.
-size n[c]
True if the files size, rounded up, in 512-byte blocks is n. If n is followed by a c, then the primary is true if the files size is n bytes.

BSD

December 4, 1999

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

FIND (1)

FIND (1)

-type t
True if the file is of the specified type. Possible file types are as follows:
b
c
d
f
l
p
s

block special
character special
directory
regular file
symbolic link
FIFO
socket

-user uname
True if the file belongs to the user uname. If uname is numeric and there is no such user name,
then uname is treated as a user ID.
All primaries which take a numeric argument allow the number to be preceded by a plus sign ( + ) or a
minus sign ( ) . A preceding plus sign means more than n, a preceding minus sign means less than n,
and neither means exactly n.
OPERATORS
The primaries may be combined using the following operators. The operators are listed in order of decreasing precedence.
(expression) This evaluates to true if the parenthesized expression evaluates to true.
!expression

This is the unary NOT operator. It evaluates to true if the expression is false.

expression -and expression


expression expression
The -and operator is the logical AND operator. As it is implied by the juxtaposition of
two expressions it does not have to be specified. The expression evaluates to true if both
expressions are true. The second expression is not evaluated if the first expression is
false.
expression -or expression
The -or operator is the logical OR operator. The expression evaluates to true if either the
first or the second expression is true. The second expression is not evaluated if the first
expression is true.
All operands and primaries must be separate arguments to find. Primaries which themselves take arguments expect each argument to be a separate argument to find.
EXAMPLES
Print out a list of all the files whose names do not end in .c:
$ find / \! -name .c -print
Print out a list of all the files owned by user wnj that are newer than the file ttt:
$ find / -newer ttt -user wnj -print
Print out a list of all the files which are not both newer than ttt and owned by wnj:
$ find / \! \( -newer ttt -user wnj \) -print
Print out a list of all the files that are either owned by wnj or that are newer than ttt:

BSD

December 4, 1999

FIND (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

FIND (1)

$ find / \( -newer ttt -or -user wnj \) -print


Print out a list of all core files on local file systems:
$ find / \! -fstype local -prune -or -name .core -print
Find all files in /usr/src ending in a dot and single digit, but skip directory /usr/src/gnu:
$ find /usr/src -path /usr/src/gnu -prune -or -name \\.[0-9]
SEE ALSO
chflags(1), chmod(1), locate(1), whereis(1), which(1), xargs(1), stat(2), fts(3),
getgrent(3), getpwent(3), strmode(3), symlink(7)
STANDARDS
The find utility syntax is a superset of the syntax specified by the IEEE Std 1003.2 (POSIX.2) standard.
The options and primaries -amin, -cmin, -empty, -follow, -fstype, -iname, -inum, -links,
-ls, -mmin, -maxdepth, -mindepth, -execdir, and -print0 are extensions to IEEE Std 1003.2
(POSIX.2). The -iname option was inspired by GNU find.
Historically, the d, H, and x options were implemented using the primaries -depth, -follow, and
-xdev. These primaries always evaluated to true. As they were really global variables that took effect
before the traversal began, some legal expressions could have unexpected results. An example is the expression print o depth. As print always evaluates to true, the standard order of evaluation implies that
depth would never be evaluated. This is not the case.
The operator -or was implemented as o, and the operator -and was implemented as a.
Historic implementations of the -exec and -ok primaries did not replace the string "{}" in the utility name
or the utility arguments if it had preceding or following non-whitespace characters. This version replaces it
no matter where in the utility name or arguments it appears.
HISTORY
A find command appeared in Version 1 AT&T UNIX.
BUGS
The special characters used by find are also special characters to many shell programs. In particular, the
characters , [, ], ?, (, ), !, \, and ; may have to be escaped from the shell.
As there is no delimiter separating options and file names or file names and the expression, it is difficult
to specify files named -xdev or !. These problems are handled by the f option and the getopt(3)
construct.

BSD

December 4, 1999

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

fold ( 1 )

NAME

fold - fold long lines for finite width output device


SYNOPSIS

fold [-w width] file ...


DESCRIPTION

Fold is a filter which folds the contents of the specified files, or the standard input if no files are specified,
breaking the lines to have maximum of 80 characters.
OPTIONS

The options are as follows:


-w

Specifies a line width to use instead of the default 80 characters. Width should be a multiple of 8
if tabs are present, or the tabs should be expanded using expand(1) before using fold.

SEE ALSO

expand(1)
BUGS

If underlining is present it may be messed up by folding.


ORIGIN

Fold includes software developed by the University of California, Berkeley and its contributors. Please see
the intro section for complete acknowledgements.

SunOS 5.8

Last change: NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

fqdn(1)

fqdn(1)

NAME
fqdn print fully qualified domain name of the current or specified host

SYNOPSIS
fqdn [ [ -u ] | [ -a ] [ <hostname> ] ]

DESCRIPTION
fqdn prints out the fully qualified domain name (fqdn) of the current or specified host. This command typically determines the hosts corresponding fqdn by querying the name resolution database entries specified
along the hosts stanza of the nsswitch.conf like file on the operating system.
If multiple hostnames are specified, only the first hostname from the left in the given hostname list is considered.

OPTIONS
-u

Print usage.

No Argument
Print the first fqdn resolved name of the current hostname resolved by any one of the name resolution database specified along the hosts stanza of the nsswitch.conf like file, in that particular
sequence.
-a

Print fqdn of the current hostname resolved using all the name resolution databases specified
along the hosts stanza of the nsswitch.conf like file.

-a <hostname>
Print fqdn of <hostname> resolved using all the name resolution databases specified along the
hosts stanza of the nsswitch.conf like file.
<hostname>
Print the first fqdn resolved name of <hostname> resolved using any one of the name resolution
databases specified along the hosts stanza of the nsswitch.conf like file, in that particular
sequence.

EXAMPLES
Example 1
[host1] $ fqdn host1
host1.domaincomponent1.domaincomponent2.com

The following example shows host2 being resolved from host3s local name resolution database
(/etc/hosts), DNS, and NIS. Empty sections signify either absence of the hostname in the name resolution
database or unavailability of the database.
Example 2
[host3] $ fqdn -a host2
<local> ... <local> ... <local> ... <local>

<dns> ... <dns> ... <dns> ... <dns>


host2.domaincomponent1.domaincomponent2.com

<nis> ... <nis> ... <nis> ... <nis>

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

fqdn(1)

fqdn(1)

Example 3
[host4] $ fqdn -a
<local> ... <local> ... <local> ... <local>
host4 host4.domaincomponent1.domaincomponent2.com loghost

<dns> ... <dns> ... <dns> ... <dns>


host4.domaincomponent1.domaincomponent2.com
host4.domaincomponent3.domaincomponent2.com

ORIGIN
fqdn was written by Jaswinder Bhamra.

SEE ALSO
hostname(1).

NSH

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

FUNZIP ( 1L )

NAME

funzip filter for extracting from a ZIP archive in a pipe


SYNOPSIS

[. . .] funzip [password] [. . .]
funzip [password] input.zip [. . .] funzip [password] input.gz [. . .]
ARGUMENTS

[password]
Optional password to be used if ZIP archive is encrypted. Decryption may not be supported at
some sites. See DESCRIPTION for more details.
DESCRIPTION

funzip acts as a filter; that is, it assumes that a ZIP archive (or a gzipd(1) file) is being piped into standard
input, and it extracts the first member from the archive to stdout. If there is an argument, then the input
comes from the specified file instead of from stdin. A password for encrypted zip files can be specified on
the command line (preceding the file name, if any) by prefixing the password with a dash. Note that this
constitutes a security risk on many systems; currently running processes are often visible via simple commands (e.g., ps(1) under Unix), and command-line histories can be read. If the first entry of the zip file is
encrypted and no password is specified on the command line, then the user is prompted for a password and
the password is not echoed on the console.
Given the limitation on single-member extraction, funzip is most useful in conjunction with a secondary
archiver program such as tar(1). The following section includes an example illustrating this usage in the
case of disk backups to tape.
EXAMPLES

To use funzip to extract the first member file of the archive test.zip and to pipe it into more(1):
funzip test.zip | more
To use funzip to test the first member file of test.zip (any errors will be reported on standard error):
funzip test.zip > /dev/null
To use zip and funzip in place of compress(1) and zcat(1) (or gzip(1L) and gzcat(1L)) for tape backups:
tar cf . | zip 7 | dd of=/dev/nrst0 obs=8k
dd if=/dev/nrst0 ibs=8k | funzip | tar xf
(where, for example, nrst0 is a SCSI tape drive).
BUGS

When piping an encrypted file into more and allowing funzip to prompt for password, the terminal may
sometimes be reset to a non-echo mode. This is apparently due to a race condition between the two programs; funzip changes the terminal mode to non-echo before more reads its state, and more then restores
the terminal to this mode before exiting. To recover, run funzip on the same file but redirect to /dev/null
rather than piping into more; after prompting again for the password, funzip will reset the terminal properly.
There is presently no way to extract any member but the first from a ZIP archive. This would be useful in
the case where a ZIP archive is included within another archive. In the case where the first member is a
directory, funzip simply creates the directory and exits.
The functionality of funzip should be incorporated into unzip itself (future release).
SEE ALSO

gzip(1L), unzip(1L), unzipsfx(1L), zip(1L), zipcloak(1L), zipinfo(1L), zipnote(1L), zipsplit(1L)


URL

The Info-ZIP home page is currently at h t t p : / / www. i n f o - z i p . o r g / p u b / i n f o z i p /


f t p: / / f t p. i nf o- z i p. or g/ pub/ i nf oz i p/ .

Info-ZIP

Last change: 14 January 2001 (v3.93)

or

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

FUNZIP ( 1L )

Last change: 14 January 2001 (v3.93)

AUTHOR

Mark Adler (Info-ZIP)

Info-ZIP

Property of BladeLogic, Inc.


Strictly confidential and proprietary

getlic(1)

getlic(1)

NAME
getlic Get remote license data from agents

SYNOPSIS
getlic [-luenxv] [-f file] [host1 ... hostn]

DESCRIPTION
The getlic command is meant to be used in conjunction with the putlic command. The basic idea is to let
you remotely license multiple servers.
The getlic command gathers necessary license data from each remote host, and writes this data to a file
called license.raw. BladeLogics licensing web page takes this file and generates a file called
license.dat. The putlic command uses license.dat to license the remote agents.
The license.dat file can contain multiple entries, one entry per line. Each entry consists of a hostname,
a product code, a license key, and an optional expiration key. putlic sends this data to each remote host
specified in the first (hostname) field of each entry. putlic creates an appropriate license based on the data.

OPTIONS
The following four options let you select a subset of hosts based on their current license status. You can
specify multiple options. If you do not specify any of these four options, getlic gets license data from all the
hosts you specify, regardless of license status.
-l

Get license data from hosts that currently have a valid permanent license.

-u

Get license data from hosts that are currently un-licensed.

-e

Get license data from hosts that currently have a valid evaluation (timed) license.

-x

Get license data from hosts that currently have an expired evaluation license.

Other options include:


-n

Do not create a license.raw file. This is useful when you just want to get an overview of your
licensing situation. See the -v option for more details.

-v

Verbose output. Displays the status of each host.

-f filename
Instead of listing your hosts one at a time on the command line as arguments, you can use this
option to point to a file containing a list of hosts (one per line) from which you want to obtain
license information.
host1 ... hostn
List of hosts whose license information you want to retrieve.

USAGE
host $ getlic -n -v bombay madras bagalore
Host bombay is not licensed
Host madras has a valid evaluation license
Host bagalore has a valid permanent license
host $ getlic bombay madras
host $ cat license.raw
bombay
1
AF23B1C9
madras
1
2F23B1C4

CAVEATS
This command works even if the remote agent is currently not licensed.

ORIGIN
getlic was written by Thomas Kraus

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

grep(1)

grep(1)

NAME
grep, egrep, fgrep - file pattern searcher

SYNOPSIS
grep [-AB num] [-CEFGHILPRSUVabchilnoqsvwx] [-e pattern] [-f file]
[pattern] [file ...]

DESCRIPTION
The grep utilities search the given input files, selecting lines that match one or more patterns. By default, an
input line matches a pattern if any regular expression (RE) in the pattern matches the input line without its
trailing newline. An empty expression matches every line. Each input line that matches at least one of the
patterns is written to the standard output.
The grep utility is used for simple patterns and ex(1) or ed(1) style regular expressions. The egrep utility
can handle extended regular expressions and multi-line patterns. The fgrep utility is quick but can handle
only fixed patterns consisting of one or more lines, allowing any of the pattern lines to match a portion of
the input.

OPTIONS
-A num Print num lines of trailing context after each match.
-B num Print num lines of leading context before each match.
-C

Print two lines of leading context and two lines of trailing context after each match. Equivalent to
-A 2 -B 2.

-E

Force grep to behave as egrep.

-F

Force grep to behave as fgrep.

-G

Force grep to behave as grep.

-H

If you specified -R, follow symbolic links only if they were explicitly listed on the command line.

-I

Ignore binary files.

-L

Select the input files that do NOT contain lines that match the pattern(s), and write the names of
these files to standard output. List the pathname for each file. If grep searched the standard
input, it writes the pathname -.

-P

If you specified the -R option, grep does not follow symbolic links.

-R

Recursively search the subdirectories you specify.

-S

If you specified the -R option, follow all symbolic links.

-U

Search binary files, but do not attempt to print them.

-V

Display version information.

-a

Treat all files as text.

-b

When displaying a matching line, display the offset in bytes of the matching pattern, in front of
the matching line.

-c

Write only a count of matching lines.

-e expression
Specify a pattern to use to search the input. You can specify multiple -e options to specify multiple patterns. grep selects an input line if it matches any of the specified patterns.
-f pattern_file
Read one or more newline separated patterns from pattern_file. Newlines are not considered
part of a pattern.
-h

Never print filename headers with output lines.

-i

Perform case insensitive matching.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

grep(1)

grep(1)

-l

Select the input files that contain lines that match the pattern(s), and write the names of these files
to standard output. List the pathname for each file. If grep searched the standard input, it writes
the pathname -.

-n

Precede each output line with its relative line number in the file. The first line of each file is 1.
grep resets the line number counter for each file it processes. grep ignores this option if you
specify -c, -l, or -q.

-o

Always print filename headers with output lines.

-q

Suppress normal output.

-s

Silent mode. Ignore nonexistent and unreadable files.

-v

Select lines that do not match any of the specified patterns.

-w

Search for the expression as a word (as if surrounded by [[:<:]] and [[:>:]]).

-x

Only input lines selected against an entire fixed string or regular expression are considered to be
matching lines.

If you do not specify any file arguments, grep uses the standard input.

RETURN VALUES
grep exits with one of the following values:
0

One or more lines were selected.

No lines were selected.

>1

An error occurred.

EXTENDED REGULAR EXPRESSIONS


The following characters are interpreted by egrep:
$

Align the match from the end of the line.

Align the match from the beginning of the line.

Add another pattern (see example below).

Match 1 or less sequential repetitions of the pattern.

Match 1 or more sequential repetitions of the pattern.

Match 0 or more sequential repetitions of the pattern.

{}

Match specified number of sequential repetitions of the pattern.

[]

Match any single character or range of characters enclosed in the brackets.

Escape special characters that have meaning to egrep.


$.[]|?+*{}()\.

These special characters are:

EXAMPLES
To find all occurrences of the word patricia in a file:
grep patricia myfile
To find all occurrences of the pattern .Pp at the beginning of a line:
grep\.Pp
The apostrophes ensure the entire expression is evaluated by grep instead of by your shell. The caret
matches the null string at the beginning of a line, and the \ escapes the . which would otherwise match
any character.
To find all lines in a file that do not contain the words foo or bar:

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

grep(1)

grep(1)

$ grep -v -e foo -e bar myfile


A simple example of an extended regular expression:
$ egrep 19|20|25 calendar
Peruses the file calendar looking for either 19, 20 or 25.

HISTORY
The grep command appeared in Version 6 AT&T UNIX.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

head(1)

head(1)

NAME
head Display first few lines of a file

SYNOPSIS
head [-?] [-l | -c | -n count | -n] [file ...]

DESCRIPTION
head displays the first few lines (by default, 10 lines) from the named file(s) to the standard output. If you
do not specify any files, head displays the first few lines from the standard input.

OPTIONS
-B

On Windows systems, the head command by default reads lines of text in TEXTUAL mode,
meaning that lines of text are terminated with a <LF> rather than the Windows standard
<CR><LF>. When you specify the -B option, head outputs the file "as is," meaning <CR><LF>
remains <CR><LF>.

-c

Instead of displaying count number of lines, display count number of characters.

-l

Measure quantities in lines. This is the default.

-n count Set the number of lines to be output (or characters to be output, if you are using the -c option) to
be count.
-n

Set the number of lines to be output (or characters to be output, if you are using the -c option) to
be n.

-?

Output a brief summary of available options and then exit with a zero status without doing any
viewing.

file

File whose first few lines you want to display. If you do not specify any file names, head displays the first few lines from the standard input.

EXAMPLE
The first example views the first 20 lines of all .c files. The second example views the first 1024 characters in the password file on the host vienna.
$ head -20 *.c
$ head -c -n 1024 //vienna/etc/passwd

DIAGNOSTICS
head: Cannot open file filename
This message is output if head is unable to access the file filename.

EXIT CODES
0

No errors detected.

You specified an unknown option.

One of the files you want to view was not accessible.

255

Unable to get a license to use the software.

CAVEATS
There are two ways in which to define the number of lines/characters to be output. This is done for compatibility purposes.

ORIGIN
head was written by Thomas Kraus

SEE ALSO
tail(1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

hexdump(1)

hexdump(1)

NAME
hexdump, od, xd - ascii, decimal, hexadecimal, octal dump

SYNOPSIS
hexdump [-bcdovx] [-e format_string] [-f format_file] [-n length] [-s skip] file ...

DESCRIPTION
The hexdump utility is a filter which displays the specified files, or the standard input, if no files are specified, in a user specified format.
For each input file, hexdump sequentially copies the input to standard output, transforming the data according to the format strings specified by the -e and -f options, in the order that they were specified.

OPTIONS
The options are as follows:
-b

One-byte octal display. Display the input offset in hexadecimal, followed by sixteen space-separated, three column, zero-filled, bytes of input data, in octal, per line.

-c

One-byte character display. Display the input offset in hexadecimal, followed by sixteen spaceseparated, three column, space-filled, characters of input data per line.

-d

Two-byte decimal display. Display the input offset in hexadecimal, followed by eight space-separated, five column, zero-filled, two-byte units of input data, in unsigned decimal, per line.

-e format_string
Specify a format string to be used for displaying data.
-f format_file
Specify a file that contains one or more newline separated format strings. Empty lines and lines
whose first non-blank character is a hash mark (#) are ignored.
-n length
Interpret only length bytes of input.
-o

Two-byte octal display. Display the input offset in hexadecimal, followed by eight space-separated, six column, zero-filled, two byte quantities of input data, in octal, per line.

-s offset Skip offset bytes from the beginning of the input. By default, offset is interpreted as a decimal
number. With a leading 0x or 0X, offset is interpreted as a hexadecimal number, otherwise, with
a leading 0, offset is interpreted as an octal number. Appending the character b, k, or m to offset
causes it to be interpreted as a multiple of 512, 1024, or 1048576, respectively.
-v

The -v option causes hexdump to display all input data. Without the -v option, any number of
groups of output lines, which would be identical to the immediately preceding group of output
lines (except for the input offsets), are replaced with a line comprised of a single asterisk.

-x

Two-byte hexadecimal display. Display the input offset in hexadecimal, followed by eight, space
separated, four column, zero-filled, two-byte quantities of input data, in hexadecimal, per line.

FORMATS
A format string contains any number of format units, separated by whitespace. A format unit contains up
to three items: an iteration count, a byte count, and a format.
The iteration count is an optional positive integer, which defaults to one. Each format is applied iteration
count times.
The byte count is an optional positive integer. If specified it defines the number of bytes to be interpreted
by each iteration of the format.
If an iteration count and/or a byte count is specified, a single slash must be placed after the iteration count
and/or before the byte count to disambiguate them. Any whitespace before or after the slash is ignored.
The format is required and must be surrounded by double quote (" ") marks. It is interpreted as a fprintfstyle format string (see fprintf(3)), with the following exceptions:

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

hexdump(1)

hexdump(1)

An asterisk (*) may not be used as a field width or precision.

A byte count or field precision is required for each s conversion character (unlike the fprintf(3)
default which prints the entire string if the precision is unspecified).

The conversion characters h, l, n, p and q are not supported.

The single character escape sequences described in the C standard are supported:
NUL
\0
<alert character> \a
<backspace>
\b
<form-feed>
\f
<newline>
\n
<carriage return> \r
<tab>
\t
<vertical tab>
\v

Hexdump also supports the the following additional conversion strings:


_a[dox] Display the input offset, cumulative across input files, of the next byte to be displayed. The
appended characters d, o, and x specify the display base as decimal, octal or hexadecimal respectively.
_A[dox] Identical to the _a conversion string except that it is only performed once, when all of the input
data has been processed.
_c

Output characters in the default character set. Nonprinting characters are displayed in three character, zero-padded octal, except for those representable by standard escape notation (see above),
which are displayed as two character strings.

_p

Output characters in the default character set. Nonprinting characters are displayed as a single
..

_u

Output US ASCII characters, with the exception that control characters are displayed using the
following, lower-case, names. Characters greater than 0xff, hexadecimal, are displayed as hexadecimal strings.
000 nul 001 soh 002 stx 003 etx 004 eot 005 enq
006 ack 007 bel 008 bs 009 ht 00A lf 00B vt
00C ff 00D cr 00E so 00F si 010 dle 011 dc1
012 dc2 013 dc3 014 dc4 015 nak 016 syn 017 etb
018 can 019 em 01A sub 01B esc 01C fs 01D gs
01E rs 01F us 0FF del

The default and supported byte counts for the conversion characters are as follows:
%_c, %_p, %_u, %c

One byte counts only.

%d, %i, %o, %u, %X, %x

Four byte default, one, two and four byte counts supported.

%E, %e, %f, %G, %g

Eight byte default, four byte counts supported.

The amount of data interpreted by each format string is the sum of the data required by each format unit,
which is the iteration count times the byte count, or the iteration count times the number of bytes required
by the format if the byte count is not specified.
The input is manipulated in blocks, where a block is defined as the largest amount of data specified by
any format string. Format strings interpreting less than an input blocks worth of data, whose last format
unit both interprets some number of bytes and does not have a specified iteration count, have the iteration
count incremented until the entire input block has been processed or there is not enough data remaining in

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

hexdump(1)

hexdump(1)

the block to satisfy the format string.


If, either as a result of user specification or hexdump modifying the iteration count as described above, an
iteration count is greater than one, no trailing whitespace characters are output during the last iteration.
It is an error to specify a byte count as well as multiple conversion characters or strings unless all but one of
the conversion characters or strings is _a or _A.
If, as a result of the specification of the -n option or end-of-file being reached, input data only partially satisfies a format string, the input block is zero-padded sufficiently to display all available data (i.e. any format
units overlapping the end of data will display some number of the zero bytes).
Further output by such format strings is replaced by an equivalent number of spaces. An equivalent number
of spaces is defined as the number of spaces output by an s conversion character with the same field width
and precision as the original conversion character or conversion string but with any +, , # conversion flag characters removed, and referencing a NULL string.
If no format strings are specified, the default display is equivalent to specifying the -x option.
hexdump exits 0 on success and >0 if an error occurred.

EXAMPLES
Display the input in perusal format:
"%06.6_ao " 12/1 "%3_u "
"\t\t" "%_p "
"\n"
Implement the -x option:
"%07.7_Ax\n"
"%07.7_ax " 8/2 "%04x " "\n"
Hexdump includes software developed by the University of California, Berkeley and its contributors. Please
see the intro section for complete acknowledgements.

SEE ALSO
od(1)

NSH

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

HGREP ( 1 )

NAME

hgrep - highlight results of a grep


SYNOPSIS

hgrep <grep args>

DESCRIPTION

Hgrep is a trivial, but cute, front-end for grep. It takes the results of the grep and highlights the word that
was searched for.
SEE ALSO

grep(1)
BUGS

Meta-characters are not handled. Quoting is not handled.

SunOS 5.8

Last change: 23 October 1988

hostname(1)

Property of BladeLogic, Inc.


Strictly confidential and proprietary

hostname(1)

NAME
hostname print name of current host

SYNOPSIS
hostname

DESCRIPTION
hostname prints out the name of the host on which your current directory resides. This command does
NOT let you set the name of the current host.

OPTIONS
hostname has no options.

ORIGIN
hostname was written by Thomas Kraus

SEE ALSO
uname(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

join(1)

join(1)

NAME
join - relational database operator

SYNOPSIS
join [-a file_number | -v file_number] [-e string] [-j file_number field] [-o list] [-t char] [-1 field] [-2 field]
file1 file2

DESCRIPTION
The join utility performs an equality join on the specified files and writes the result to the standard output. The join field is the field in each file by which the files are compared. The first field in each line is
used by default. There is one line in the output for each pair of lines in file1 and file2 that have identical
join fields. Each output line consists of the join field, the remaining fields from file1 and then the remaining
fields from file2.
The default input field separators are tab and space characters. Multiple tabs and spaces count as a single
field separator, and leading tabs and spaces are ignored. The default output field separator is a single space
character.
Many of the options use file and field numbers. Both file numbers and field numbers are 1 based, meaning
the first file on the command line is file number 1 and the first field is field number 1.

OPTIONS
-a file_number
In addition to the default output, produce a line for each unpairable line in file file_number.
-e string Replace empty output fields with string.
-o list

The -o option specifies the fields that will be output from each file for each line with matching
join fields. Each element of the list has the form file_number.field, where file_number is a file
number and field is a field number. The elements of list must be either comma (,) or whitespace separated. (The latter requires quoting to protect it from the shell. A a simpler approach is
to use multiple -o options.)

-t char

Use character char as a field delimiter for both input and output. Every occurrence of char in a
line is significant.

-v file_number
Do not display the default output, but display a line for each unpairable line in file file_number.
You can specify options -v 1 and -v 2 at the same time.
-1 field

In file 1, join on the field specified by field. For example, -1 3 means join on the third field in file
1.

-2 field

In file 2, join on the field specified by field. For example, -2 3 means join on the third field in file
2.

When you are using the default field delimiter characters, you should order the files you are joining in the
collating sequence of sort(1),using the -b option, on the fields on which they are to be joined. Otherwise,
join may not report all field matches. When you specify the field delimiter characters with the -t option,
the collating sequence should be the same as sort without the -b option.
If one of the arguments file1 or file2 is -, join uses the standard input.
The join utility exits 0 on success, and >0 if an error occurs.

COMPATIBILITY
For compatibility with historic versions of join, the following options are available:
-a

In addition to the default output, produce a line for each unpairable line in both file 1 and file 2.

-j1 field In file 1, join on the field specified by field. For example, -j1 3 means join on the third field in file
1.
-j2 field In file 2, join on the field specified by field. For example, -j2 3 means join on the third field in file
2.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

join(1)

-j field

join(1)

In both file 1 and file 2, join on the field specified by field.

-o list ... Historical implementations of join permitted multiple arguments to the -o option. These arguments were of the form file_number.field_number as described for the current -o option. This
has obvious difficulties in the presence of files named 1.2.
These options are available only so historic shellscripts do not require modification. In general, do not use
these options.

ORIGIN
join includes software developed by the University of California, Berkeley and its contributors.

SEE ALSO
awk(1), comm(1), paste(1), sort(1), uniq(1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

lam ( 1 )

NAME

lam laminate files


SYNOPSIS

lam [ [fp] min.max ] [ s sepstring ] [ t c ] file ...


DESCRIPTION

Lam copies the named files side by side onto the standard output. The n-th input lines from the input files
are considered fragments of the single long n-th output line into which they are assembled. The name
means the standard input, and may be repeated.
Normally, each option affects only the file after it. If the option letter is capitalized it affects all subsequent
files until it appears again uncapitalized. The options are described below.
f min.max
Print line fragments according to the format string min.max, where min is the minimum field width
and max the maximum field width. If min begins with a zero, zeros will be added to make up the
field width, and if it begins with a , the fragment will be left-adjusted within the field.
p min.max
Like f, but pad this files field when end-of-file is reached and other files are still active.
s sepstring
Print sepstring before printing line fragments from the next file. This option may appear after the
last file.
t c

The input line terminator is c instead of a newline. The newline normally appended to each output
line is omitted.

To print files simultaneously for easy viewing use pr(1).


EXAMPLES

The command
lam file1 file2 file3 file4
joins 4 files together along each line. To merge the lines from four different files use
lam file1 S " \
" file2 file3 file4
Every 2 lines of a file may be joined on one line with
lam < file
and a form letter with substitutions keyed by @ can be done with
lam t @ letter changes
ORIGIN

Lam includes software developed by the University of California, Berkeley and its contributors. Please see
the intro section for complete acknowledgements.
SEE ALSO

join(1), pr(1).

SunOS 5.8

Last change: NSH

LESS (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

NAME
less, more view files on a CRT
SYNOPSIS
less
more
less
more
less
more
less
more
less
more

|
?
|
-help
|
V
|
-version
|
[ [+]aBcCdeEfFgGiIJLmMnNqQrRsSuUVwWX] [ b space] [ h lines] [ j line]
[ k keyfile] [ o | O logfile] [ p pattern] [ P prompt] [ t tag]
[ T tagsfile] [ x tab,...] [ y lines] [ [z] lines] [ # shift] [+[+] cmd]
[ ] [filename . . .]

DESCRIPTION
less is a program similar to the traditional more(1), but which allows backward movement in the file as
well as forward movement. Also, less does not have to read the entire input file before starting, so with
large input files it starts up faster than text editors like vi(1). less uses termcap (or terminfo on some systems), so it can run on a variety of terminals. There is even limited support for hardcopy terminals. (On a
hardcopy terminal, lines which should be printed at the top of the screen are prefixed with a caret.)
This version of less also acts as more(1) if it is called as more. In this mode, the differences are in the
prompt and that more exits by default when it gets to the end of the file. Commands are based on both traditional more and vi(1). Commands may be preceded by a decimal number, called N in the descriptions
below. The number is used by some commands, as indicated.
COMMANDS
In the following descriptions, X means control-X. ESC stands for the ESCAPE key; for example ESC-v
means the two character sequence "ESCAPE", then "v".
h | H

Help: display a summary of these commands. If you forget all the other commands, remember this
one.

SPACE | V | f | F
Scroll forward N lines, default one window (see option -z below). If N is more than the screen size,
only the final screenful is displayed. Warning: some systems use V as a special literalization character.
z

Like SPACE, but if N is specified, it becomes the new window size.

ESC-SPACE
Like SPACE, but scrolls a full screensful, even if it reaches end-of-file in the process.
RETURN | N | e | E | j | J
Scroll forward N lines, default 1. The entire N lines are displayed, even if N is more than the screen
size.
d | D
Scroll forward N lines, default one half of the screen size. If N is specified, it becomes the new
default for subsequent d and u commands.

BSD

January 17, 2003

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

LESS (1)

b | B | ESC-v
Scroll backward N lines, default one window (see option -z below). If N is more than the screen size,
only the final screenful is displayed.
w

Like ESC-v, but if N is specified, it becomes the new window size.

y | Y | P | k | K
Scroll backward N lines, default 1. The entire N lines are displayed, even if N is more than the screen
size. Warning: some systems use Y as a special job control character.
u | U
Scroll backward N lines, default one half of the screen size. If N is specified, it becomes the new
default for subsequent d and u commands.
ESC-) | RIGHTARROW
Scroll horizontally right N characters, default half the screen width (see the -# option). If a number N
is specified, it becomes the default for future RIGHTARROW and LEFTARROW commands. While
the text is scrolled, it acts as though the -S option (chop lines) were in effect.
ESC-( | LEFTARROW
Scroll horizontally left N characters, default half the screen width (see the -# option). If a number N
is specified, it becomes the default for future RIGHTARROW and LEFTARROW commands.
r | R | L
Repaint the screen.
R

Repaint the screen, discarding any buffered input. Useful if the file is changing while it is being
viewed.

Scroll forward, and keep trying to read when the end of file is reached. Normally this command
would be used when already at the end of the file. It is a way to monitor the tail of a file which is
growing while it is being viewed. (The behavior is similar to the "tail -f" command.)

g | < | ESC-<
Go to line N in the file, default 1 (beginning of file). (Warning: this may be slow if N is large.)
G | > | ESC->
Go to line N in the file, default the end of the file. (Warning: this may be slow if N is large, or if N is
not specified and standard input, rather than a file, is being read.)
p | %

BSD

Go to a position N percent into the file. N should be between 0 and 100.

If a left curly bracket appears in the top line displayed on the screen, the { command will go to the
matching right curly bracket. The matching right curly bracket is positioned on the bottom line of the
screen. If there is more than one left curly bracket on the top line, a number N may be used to specify
the N-th bracket on the line.

If a right curly bracket appears in the bottom line displayed on the screen, the } command will go to
the matching left curly bracket. The matching left curly bracket is positioned on the top line of the
screen. If there is more than one right curly bracket on the top line, a number N may be used to specify the N-th bracket on the line.

Like {, but applies to parentheses rather than curly brackets.

Like }, but applies to parentheses rather than curly brackets.

January 17, 2003

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

Like {, but applies to square brackets rather than curly brackets.

Like }, but applies to square brackets rather than curly brackets.

LESS (1)

ESC-F
Followed by two characters, acts like {, but uses the two characters as open and close brackets,
respectively. For example, "ESC F < >" could be used to go forward to the > which matches the < in
the top displayed line.
ESC-B
Followed by two characters, acts like }, but uses the two characters as open and close brackets,
respectively. For example, "ESC B < >" could be used to go backward to the < which matches the >
in the bottom displayed line.
m

Followed by any lowercase letter, marks the current position with that letter.

(Single quote.) Followed by any lowercase letter, returns to the position which was previously
marked with that letter. Followed by another single quote, returns to the position at which the last
"large" movement command was executed. Followed by a or $, jumps to the beginning or end of the
file respectively. Marks are preserved when a new file is examined, so the command can be used to
switch between input files.

XX Same as single quote.


/pattern
Search forward in the file for the N-th line containing the pattern. N defaults to 1. The pattern is a
regular expression, as recognized by ed(1). The search starts at the second line displayed (but see the
-a and -j options, which change this).
Certain characters are special if entered at the beginning of the pattern; they modify the type of search
rather than become part of the pattern:
N | !
E |

F | @

Search for lines which do NOT match the pattern.


Search multiple files. That is, if the search reaches the END of the current file without finding a match, the search continues in the next file in the command line list.
Begin the search at the first line of the FIRST file in the command line list, regardless of
what is currently displayed on the screen or the settings of the -a or -j options.

Highlight any text which matches the pattern on the current screen, but dont move to the
first match (KEEP current position).

Dont interpret regular expression metacharacters; that is, do a simple textual comparison.

?pattern
Search backward in the file for the N-th line containing the pattern. The search starts at the line
immediately before the top line displayed.
Certain characters are special, as in the / command:
N | !
E |

BSD

Search for lines which do NOT match the pattern.


Search multiple files. That is, if the search reaches the beginning of the current file without
finding a match, the search continues in the previous file in the command line list.

January 17, 2003

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

F | @

LESS (1)

Begin the search at the last line of the last file in the command line list, regardless of what is
currently displayed on the screen or the settings of the -a or -j options.

As in forward searches.

As in forward searches.

ESC-/pattern
Same as "/".
ESC-?pattern
Same as "?".
n

Repeat previous search, for N-th line containing the last pattern. If the previous search was modified
by N, the search is made for the N-th line NOT containing the pattern. If the previous search was
modified by E, the search continues in the next (or previous) file if not satisfied in the current file. If
the previous search was modified by R, the search is done without using regular expressions. There
is no effect if the previous search was modified by F or K.

Repeat previous search, but in the reverse direction.

ESC-n
Repeat previous search, but crossing file boundaries. The effect is as if the previous search were
modified by .
ESC-N
Repeat previous search, but in the reverse direction and crossing file boundaries.
ESC-u
Undo search highlighting. Turn off highlighting of strings matching the current search pattern. If
highlighting is already off because of a previous ESC-u command, turn highlighting back on. Any
search command will also turn highlighting back on. (Highlighting can also be disabled by toggling
the -G option; in that case search commands do not turn highlighting back on.)
:e [filename]
Examine a new file. If the filename is missing, the "current" file (see the :n and :p commands below)
from the list of files in the command line is re-examined. A percent sign (%) in the filename is
replaced by the name of the current file. A pound sign (#) is replaced by the name of the previously
examined file. However, two consecutive percent signs are simply replaced with a single percent
sign. This allows you to enter a filename that contains a percent sign in the name. Similarly, two
consecutive pound signs are replaced with a single pound sign. The filename is inserted into the command line list of files so that it can be seen by subsequent :n and :p commands. If the filename consists of several files, they are all inserted into the list of files and the first one is examined. If the filename contains one or more spaces, the entire filename should be enclosed in double quotes (also see
the -" option).
XV | E
Same as :e. Warning: some systems use V as a special literalization character. On such systems, you
may not be able to use V.

BSD

:n

Examine the next file (from the list of files given in the command line). If a number N is specified,
the N-th next file is examined.

:p

Examine the previous file in the command line list. If a number N is specified, the N-th previous file
is examined.

January 17, 2003

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

LESS (1)

:t

Go to the specified tag.

:x

Examine the first file in the command line list. If a number N is specified, the N-th file in the list is
examined.

:d

Remove the current file from the list of files.

Go to the next tag, if there were more than one matches for the current tag. See the t option for
more details about tags.

Go to the previous tag, if there were more than one matches for the current tag.

= | G | :f
Prints some information about the file being viewed, including its name and the line number and byte
offset of the bottom line being displayed. If possible, it also prints the length of the file, the number
of lines in the file and the percent of the file above the last displayed line.

Followed by one of the command line option letters (see OPTIONS below), this will change the setting of that option and print a message describing the new setting. If a P (CONTROL-P) is entered
immediately after the dash, the setting of the option is changed but no message is printed. If the
option letter has a numeric value (such as -b or -h), or a string value (such as -P or -t), a new value
may be entered after the option letter. If no new value is entered, a message describing the current
setting is printed and nothing is changed.

Like the command, but takes a long option name (see OPTIONS below) rather than a single option
letter. You must press RETURN after typing the option name. A P immediately after the second
dash suppresses printing of a message describing the new setting, as in the command.

Followed by one of the command line option letters this will reset the option to its default setting and
print a message describing the new setting. (The "+X" command does the same thing as "+X" on
the command line.) This does not work for string-valued options.

Like the + command, but takes a long option name rather than a single option letter.

Followed by one of the command line option letters, this will reset the option to the "opposite" of its
default setting and print a message describing the new setting. This does not work for numeric or
string-valued options.

Like the ! command, but takes a long option name rather than a single option letter.

(Underscore.) Followed by one of the command line option letters, this will print a message describing the current setting of that option. The setting of the option is not changed.

__

(Double underscore.) Like the _ (underscore) command, but takes a long option name rather than a
single option letter. You must press RETURN after typing the option name.

+cmd Causes the specified cmd to be executed each time a new file is examined. For example, +G causes
less to initially display each file starting at the end rather than the beginning.
V

Prints the version number of less being run.

q | Q | :q | :Q | ZZ
Exits less.
The following four commands may or may not be valid, depending on your particular installation.
v

BSD

Invokes an editor to edit the current file being viewed. The editor is taken from the environment variable VISUAL, if defined, or EDITOR if VISUAL is not defined, or defaults to "vi" if neither VISUAL
nor EDITOR is defined. See also the discussion of LESSEDIT under the section on PROMPTS
below.

January 17, 2003

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

LESS (1)

! shell-command
Invokes a shell to run the shell-command given. A percent sign (%) in the command is replaced by
the name of the current file. A pound sign (#) is replaced by the name of the previously examined
file. "!!" repeats the last shell command. "!" with no shell command simply invokes a shell. The
shell is taken from the environment variable SHELL, or defaults to "sh".
| <m> shell-command
<m> represents any mark letter. Pipes a section of the input file to the given shell command. The
section of the file to be piped is between the first line on the current screen and the position marked by
the letter. <m> may also be or $ to indicate beginning or end of file respectively. If <m> is . or
newline, the current screen is piped.
s filename
Save the input to a file. This only works if the input is a pipe, not an ordinary file.
OPTIONS
Command line options are described below. Most options may be changed while less is running, via the
"" command.
Most options may be given in one of two forms: either a dash followed by a single letter, or two dashes followed by a long option name. A long option name may be abbreviated as long as the abbreviation is unambiguous. For example, --quit-at-eof may be abbreviated --quit, but not --qui, since both --quit-at-eof and
--quiet begin with --qui. Some long option names are in uppercase, such as --QUIT-AT-EOF, as distinct from
--quit-at-eof. Such option names need only have their first letter capitalized; the remainder of the name may
be in either case. For example, --Quit-at-eof is equivalent to --QUIT-AT-EOF.
Options are also taken from the environment variable LESS if the command is less, or from the environment variable MORE if the command is more. For example, to avoid typing "less -options ..." each time
less is invoked, you might tell csh(1):
setenv LESS -options
or if you use sh(1):
LESS="-options"; export LESS
The environment variable is parsed before the command line, so command line options override the LESS
environment variable. If an option appears in the LESS variable, it can be reset to its default value on the
command line by beginning the command line option with "+".
For options like -P which take a following string, a dollar sign ($) must be used to signal the end of the
string. For example, to separate a prompt value from any other options with dollar sign between them:
LESS="-Ps--More--$-C -e"
? | -help
This option displays a summary of the commands accepted by less (the same as the h command).
(Depending on how your shell interprets the question mark, it may be necessary to quote the question
mark, thus: "-\?".)
a | -search-skip-screen
Causes searches to start after the last line displayed on the screen, thus skipping all lines displayed on
the screen. By default, searches start at the second line on the screen (or after the last found line; see
the -j option).
bn | -buffers=n
Specifies the amount of buffer space less will use for each file, in units of kilobytes (1024 bytes).
By default 64K of buffer space is used for each file (unless the file is a pipe; see the -B option). The

BSD

January 17, 2003

LESS (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

-b option specifies instead that n kilobytes of buffer space should be used for each file. If n is -1,
buffer space is unlimited; that is, the entire file is read into memory.
B | -auto-buffers
By default, when data is read from a pipe, buffers are allocated automatically as needed. If a large
amount of data is read from the pipe, this can cause a large amount of memory to be allocated. The
-B option disables this automatic allocation of buffers for pipes, so that only 64K (or the amount of
space specified by the -b option) is used for the pipe. Warning: use of -B can result in erroneous display, since only the most recently viewed part of the file is kept in memory; any earlier data is lost.
c | -clear-screen
Causes full screen repaints to be painted from the top line down. By default, full screen repaints are
done by scrolling from the bottom of the screen.
C | -CLEAR-SCREEN
The -C option is like -c, but the screen is cleared before it is repainted.
d | -dumb (less only)
The -d option suppresses the error message normally displayed if the terminal is dumb; that is, lacks
some important capability, such as the ability to clear the screen or scroll backward. The -d option
does not otherwise change the behavior of less on a dumb terminal. This option is on by default
when invoked as more.
d (more only)
The -d option causes the default prompt to include the basic directions [Press space to continue, q
to quit.]. The -d option also causes the message [Press h for instructions.] to be displayed when
an invalid command is entered (normally, the bell is rung). This option is useful in environments
where users may not be experienced with pagers.
e | -quit-at-eof
Causes less to automatically exit the second time it reaches end-of-file. By default, the only way to
exit less is via the "q" command.
E | -QUIT-AT-EOF
Causes less to automatically exit the first time it reaches end-of-file.
f | -force
Forces non-regular files to be opened. (A non-regular file is a directory or a device special file.) Also
suppresses the warning message when a binary file is opened. By default, less will refuse to open
non-regular files.
F | -quit-if-one-screen
Causes less to automatically exit if the entire file can be displayed on the first screen.
g | -hilite-search
Normally, less will highlight ALL strings which match the last search command. The -g option
changes this behavior to highlight only the particular string which was found by the last search command. This can cause less to run somewhat faster than the default.
G | -HILITE-SEARCH
The -G option suppresses all highlighting of strings found by search commands.
hn | -max-back-scroll=n
Specifies a maximum number of lines to scroll backward. If it is necessary to scroll backward more
than n lines, the screen is repainted in a forward direction instead. (If the terminal does not have the
ability to scroll backward, -h0 is implied.)

BSD

January 17, 2003

LESS (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

i | -ignore-case
Causes searches to ignore case; that is, uppercase and lowercase are considered identical. This option
is ignored if any uppercase letters appear in the search pattern; in other words, if a pattern contains
uppercase letters, then that search does not ignore case.
I | -IGNORE-CASE
Like -i, but searches ignore case even if the pattern contains uppercase letters.
jn | -jump-target=n
Specifies a line on the screen where the "target" line is to be positioned. A target line is the object of
a text search, tag search, jump to a line number, jump to a file percentage, or jump to a marked position. The screen line is specified by a number: the top line on the screen is 1, the next is 2, and so on.
The number may be negative to specify a line relative to the bottom of the screen: the bottom line on
the screen is -1, the second to the bottom is -2, and so on. If the -j option is used, searches begin at
the line immediately after the target line. For example, if "-j4" is used, the target line is the fourth line
on the screen, so searches begin at the fifth line on the screen.
J | -status-column
Displays a status column at the left edge of the screen. The status column shows the lines that
matched the current search. The status column is also used if the -w or -W option is in effect.
kfilename | -lesskey-file=filename
Causes less to open and interpret the named file as a lesskey(1) file. Multiple -k options may be
specified. If the LESSKEY or LESSKEY_SYSTEM environment variable is set, or if a lesskey file is
found in a standard place (see KEY BINDINGS), it is also used as a lesskey file.
L | -no-lessopen
Ignore the LESSOPEN environment variable (see the INPUT PREPROCESSOR section below).
This option can be set from within less, but it will apply only to files opened subsequently, not to
the file which is currently open. When invoked as more, the LESSOPEN environment variable is
ignored by default.
m | -long-prompt
Causes less to prompt verbosely (like more), with the percent into the file. By default, less
prompts with a colon.
M | -LONG-PROMPT
Causes less to prompt even more verbosely than more.
n | -line-numbers
Suppresses line numbers. The default (to use line numbers) may cause less to run more slowly in
some cases, especially with a very large input file. Suppressing line numbers with the -n option will
avoid this problem. Using line numbers means: the line number will be displayed in the verbose
prompt and in the = command, and the v command will pass the current line number to the editor (see
also the discussion of LESSEDIT in PROMPTS below).
N | -LINE-NUMBERS
Causes a line number to be displayed at the beginning of each line in the display.
ofilename | -log-file=filename
Causes less to copy its input to the named file as it is being viewed. This applies only when the
input file is a pipe, not an ordinary file. If the file already exists, less will ask for confirmation
before overwriting it.
Ofilename | -LOG-FILE=filename
The -O option is like -o, but it will overwrite an existing file without asking for confirmation.

BSD

January 17, 2003

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

LESS (1)

If no log file has been specified, the -o and -O options can be used from within less to specify a log
file. Without a file name, they will simply report the name of the log file. The "s" command is equivalent to specifying -o from within less.
ppattern | -pattern=pattern
The -p option on the command line is equivalent to specifying +/pattern; that is, it tells less to start
at the first occurrence of pattern in the file.
Pprompt | -prompt=prompt
Provides a way to tailor the three prompt styles to your own preference. This option would normally
be put in the LESS environment variable, rather than being typed in with each less command. Such
an option must either be the last option in the LESS variable, or be terminated by a dollar sign. -Ps
followed by a string changes the default (short) prompt to that string. -Pm changes the medium (-m)
prompt. -PM changes the long (-M) prompt. -Ph changes the prompt for the help screen. -P=
changes the message printed by the = command. -Pw changes the message printed while waiting for
data (in the F command). All prompt strings consist of a sequence of letters and special escape
sequences. See the section on PROMPTS for more details.
q | -quiet | -silent
Causes moderately "quiet" operation: the terminal bell is not rung if an attempt is made to scroll past
the end of the file or before the beginning of the file. If the terminal has a "visual bell", it is used
instead. The bell will be rung on certain other errors, such as typing an invalid character. The default
is to ring the terminal bell in all such cases.
Q | -QUIET | -SILENT
Causes totally "quiet" operation: the terminal bell is never rung.
r | -raw-control-chars
Causes "raw" control characters to be displayed. The default is to display control characters using the
caret notation; for example, a control-A (octal 001) is displayed as "A". Warning: when the -r option
is used, less cannot keep track of the actual appearance of the screen (since this depends on how the
screen responds to each type of control character). Thus, various display problems may result, such
as long lines being split in the wrong place.
R | -RAW-CONTROL-CHARS
Like -r, but tries to keep track of the screen appearance where possible. This works only if the input
consists of normal text and possibly some ANSI "color" escape sequences, which are sequences of
the form:
ESC [ ... m
where the "..." is zero or more characters other than "m". For the purpose of keeping track of screen
appearance, all control characters and all ANSI color escape sequences are assumed to not move the
cursor. You can make less think that characters other than "m" can end ANSI color escape
sequences by setting the environment variable LESSANSIENDCHARS to the list of characters which
can end a color escape sequence.
s | -squeeze-blank-lines
Causes consecutive blank lines to be squeezed into a single blank line. This is useful when viewing
nroff(1) output.
S | -chop-long-lines
Causes lines longer than the screen width to be chopped rather than folded. That is, the portion of a
long line that does not fit in the screen width is not shown. The default is to fold long lines; that is,
display the remainder on the next line.

BSD

January 17, 2003

LESS (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

ttag | -tag=tag
The -t option, followed immediately by a TAG, will edit the file containing that tag. For this to work,
tag information must be available; for example, there may be a file in the current directory called
"tags", which was previously built by ctags(1) or an equivalent command. If the environment variable LESSGLOBALTAGS is set, it is taken to be the name of a command compatible with global,
and that command is executed to find the tag. (See http://www.gnu.org/software/global/global.html).
The -t option may also be specified from within less (using the command) as a way of examining
a new file. The command ":t" is equivalent to specifying -t from within less.
Ttagsfile | -tag-file=tagsfile
Specifies a tags file to be used instead of "tags".
u | -underline-special
Causes backspaces and carriage returns to be treated as printable characters; that is, they are sent to
the terminal when they appear in the input.
U | -UNDERLINE-SPECIAL
Causes backspaces, tabs and carriage returns to be treated as control characters; that is, they are handled as specified by the -r option.
By default, if neither -u nor -U is given, backspaces which appear adjacent to an underscore character
are treated specially: the underlined text is displayed using the terminals hardware underlining capability. Also, backspaces which appear between two identical characters are treated specially: the
overstruck text is printed using the terminals hardware boldface capability. Other backspaces are
deleted, along with the preceding character. Carriage returns immediately followed by a newline are
deleted. Other carriage returns are handled as specified by the -r option. Text which is overstruck or
underlined can be searched for if neither -u nor -U is in effect.
V | -version
Displays the version number of less.
w | -hilite-unread
Temporarily highlights the first "new" line after a forward movement of a full page. The first "new"
line is the line immediately following the line previously at the bottom of the screen. Also highlights
the target line after a g or p command. The highlight is removed at the next command which causes
movement. The entire line is highlighted, unless the -J option is in effect, in which case only the status column is highlighted.
W | -HILITE-UNREAD
Like -w, but temporarily highlights the first new line after any forward movement command larger
than one line.
xn,... | -tabs=n,...
Sets tab stops. If only one n is specified, tab stops are set at multiples of n. If multiple values separated by commas are specified, tab stops are set at those positions, and then continue with the same
spacing as the last two. For example, -x9,17 will set tabs at positions 9, 17, 25, 33, etc. The default
for n is 8.
X | -no-init
Disables sending the termcap initialization and deinitialization strings to the terminal. This is sometimes desirable if the deinitialization string does something unnecessary, like clearing the screen.
-no-keypad
Disables sending the keypad initialization and deinitialization strings to the terminal. This is sometimes useful if the keypad strings make the numeric keypad behave in an undesirable manner.

BSD

January 17, 2003

10

LESS (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

yn | -max-forw-scroll=n
Specifies a maximum number of lines to scroll forward. If it is necessary to scroll forward more than
n lines, the screen is repainted instead. The -c or -C option may be used to repaint from the top of the
screen if desired. By default, any forward movement causes scrolling.
[z]n | -window=n
Changes the default scrolling window size to n lines. The default is one screenful. The z and w commands can also be used to change the window size. The "z" may be omitted for compatibility with
more. If the number n is negative, it indicates n lines less than the current screen size. For example,
if the screen is 24 lines, -z-4 sets the scrolling window to 20 lines. If the screen is resized to 40 lines,
the scrolling window automatically changes to 36 lines.
-cc | -quotes=cc
Changes the filename quoting character. This may be necessary if you are trying to name a file which
contains both spaces and quote characters. Followed by a single character, this changes the quote
character to that character. Filenames containing a space should then be surrounded by that character
rather than by double quotes. Followed by two characters, changes the open quote to the first character, and the close quote to the second character. Filenames containing a space should then be preceded by the open quote character and followed by the close quote character. Note that even after the
quote characters are changed, this option remains -" (a dash followed by a double quote).
| -tilde
Normally lines after end of file are displayed as a single tilde (). This option causes lines after end of
file to be displayed as blank lines.
# | -shift
Specifies the default number of positions to scroll horizontally in the RIGHTARROW and LEFTARROW commands. If the number specified is zero, it sets the default number of positions to one half of
the screen width.

A command line argument of "--" marks the end of option arguments. Any arguments following this
are interpreted as filenames. This can be useful when viewing a file whose name begins with a "-" or
"+".

If a command line option begins with +, the remainder of that option is taken to be an initial command to less. For example, +G tells less to start at the end of the file rather than the beginning,
and +/xyz tells it to start at the first occurrence of "xyz" in the file. As a special case, +<number> acts
like +<number>g; that is, it starts the display at the specified line number (however, see the caveat
under the "g" command above). If the option starts with ++, the initial command applies to every file
being viewed, not just the first one. The + command described previously may also be used to set (or
change) an initial command for every file.

LINE EDITING
When entering command line at the bottom of the screen (for example, a filename for the :e command, or the
pattern for a search command), certain keys can be used to manipulate the command line. Most commands
have an alternate form in [ brackets ] which can be used if a key does not exist on a particular keyboard. Any
of these special keys may be entered literally by preceding it with the "literal" character, either V or A. A
backslash itself may also be entered literally by entering two backslashes.
LEFTARROW [ESC-h]
Move the cursor one space to the left.
RIGHTARROW [ESC-l]
Move the cursor one space to the right.

BSD

January 17, 2003

11

LESS (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

LEFTARROW [ESC-b or ESC-LEFTARROW]


(That is, CONTROL and LEFTARROW simultaneously.) Move the cursor one word to the left.
RIGHTARROW [ESC-w or ESC-RIGHTARROW]
(That is, CONTROL and RIGHTARROW simultaneously.) Move the cursor one word to the right.
HOME [ESC-0]
Move the cursor to the beginning of the line.
END [ESC-$]
Move the cursor to the end of the line.
BACKSPACE
Delete the character to the left of the cursor, or cancel the command if the command line is empty.
DELETE or [ESC-x]
Delete the character under the cursor.
BACKSPACE [ESC-BACKSPACE]
(That is, CONTROL and BACKSPACE simultaneously.) Delete the word to the left of the cursor.
DELETE [ESC-X or ESC-DELETE]
(That is, CONTROL and DELETE simultaneously.) Delete the word under the cursor.
UPARROW [ESC-k]
Retrieve the previous command line.
DOWNARROW [ESC-j]
Retrieve the next command line.
TAB

Complete the partial filename to the left of the cursor. If it matches more than one filename, the first
match is entered into the command line. Repeated TABs will cycle through the other matching filenames. If the completed filename is a directory, a "/" is appended to the filename. The environment
variable LESSSEPARATOR can be used to specify a different character to append to a directory
name.

BACKTAB [ESC-TAB]
Like TAB, but cycles in the reverse direction through the matching filenames.
L

Complete the partial filename to the left of the cursor. If it matches more than one filename, all
matches are entered into the command line (if they fit).

Delete the entire command line, or cancel the command if the command line is empty. If you have
changed your line-kill character to something other than U, that character is used instead of U.

KEY BINDINGS
You may define your own less commands by using the program lesskey(1) to create a lesskey file. This
file specifies a set of command keys and an action associated with each key. You may also use lesskey to
change the line-editing keys (see LINE EDITING), and to set environment variables. If the environment
variable LESSKEY is set, less uses that as the name of the lesskey file. Otherwise, less looks for a
lesskey file called "$HOME/.less". See the lesskey(1) manual page for more details.
A system-wide lesskey file may also be set up to provide key bindings. If a key is defined in both a local
lesskey file and in the system-wide file, key bindings in the local file take precedence over those in the system-wide file. If the environment variable LESSKEY_SYSTEM is set, less uses that as the name of the
system-wide lesskey file. Otherwise, less looks in a standard place for the system-wide lesskey file: On
OpenBSD, the system-wide lesskey file is /etc/sysless.

BSD

January 17, 2003

12

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

LESS (1)

INPUT PREPROCESSOR
You may define an "input preprocessor" for less. Before less opens a file, it first gives your input preprocessor a chance to modify the way the contents of the file are displayed. An input preprocessor is simply an
executable program (or shell script), which writes the contents of the file to a different file, called the replacement file. The contents of the replacement file are then displayed in place of the contents of the original file.
However, it will appear to the user as if the original file is opened; that is, less will display the original filename as the name of the current file.
An input preprocessor receives one command line argument, the original filename, as entered by the user. It
should create the replacement file, and when finished print the name of the replacement file to its standard
output. If the input preprocessor does not output a replacement filename, less uses the original file, as normal. The input preprocessor is not called when viewing standard input. To set up an input preprocessor, set
the LESSOPEN environment variable to a command line which will invoke your input preprocessor. This
command line should include one occurrence of the string "%s", which will be replaced by the filename
when the input preprocessor command is invoked.
When less closes a file opened in such a way, it will call another program, called the input postprocessor,
which may perform any desired clean-up action (such as deleting the replacement file created by
LESSOPEN). This program receives two command line arguments, the original filename as entered by the
user, and the name of the replacement file. To set up an input postprocessor, set the LESSCLOSE environment variable to a command line which will invoke your input postprocessor. It may include two occurrences of the string "%s"; the first is replaced with the original name of the file and the second with the name
of the replacement file, which was output by LESSOPEN.
For example, these two scripts will allow you to keep files in compressed format, but still let less view
them directly:
lessopen.sh:
#! /bin/sh
case "$1" in
.Z)
uncompress -c $1 >/tmp/less.$$
if [ -s /tmp/less.$$ ]; then
echo /tmp/less.$$
else
rm -f /tmp/less.$$
fi
;;
esac

2>/dev/null

lessclose.sh:
#! /bin/sh
rm $2
To use these scripts, put them both where they can be executed and set LESSOPEN="lessopen.sh %s", and
LESSCLOSE="lessclose.sh %s %s". More complex LESSOPEN and LESSCLOSE scripts may be written
to accept other types of compressed files, and so on.
It is also possible to set up an input preprocessor to pipe the file data directly to less, rather than putting the
data into a replacement file. This avoids the need to decompress the entire file before starting to view it. An
input preprocessor that works this way is called an input pipe. An input pipe, instead of writing the name of
a replacement file on its standard output, writes the entire contents of the replacement file on its standard output. If the input pipe does not write any characters on its standard output, then there is no replacement file
and less uses the original file, as normal. To use an input pipe, make the first character in the LESSOPEN
environment variable a vertical bar (|) to signify that the input preprocessor is an input pipe.

BSD

January 17, 2003

13

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

LESS (1)

For example, this script will work like the previous example scripts:
lesspipe.sh:
#! /bin/sh
case "$1" in
.Z)
uncompress -c $1
;;
esac

2>/dev/null

To use this script, put it where it can be executed and set LESSOPEN="|lesspipe.sh %s". When an input pipe
is used, a LESSCLOSE postprocessor can be used, but it is usually not necessary since there is no replacement file to clean up. In this case, the replacement file name passed to the LESSCLOSE postprocessor is "-".
NATIONAL CHARACTER SETS
There are three types of characters in the input file:
normal characters

Can be displayed directly to the screen.

control characters

Should not be displayed directly, but are expected to be found in ordinary text
files (such as backspace and tab).

binary characters

Should not be displayed directly and are not expected to be found in text files.

A "character set" is simply a description of which characters are to be considered normal, control, and binary.
The LESSCHARSET environment variable may be used to select a character set. Possible values for
LESSCHARSET are:
ascii

BS, TAB, NL, CR, and formfeed are control characters, all chars with values between 32 and
126 are normal, and all others are binary.

iso8859

Selects an ISO 8859 character set. This is the same as ASCII, except characters between 160
and 255 are treated as normal characters.

latin1

Same as iso8859.

latin9

Same as iso8859.

dos

Selects a character set appropriate for MS-DOS.

ebcdic

Selects an EBCDIC character set.

IBM-1047

Selects an EBCDIC character set used by OS/390 Unix Services. This is the EBCDIC analogue
of latin1. You get similar results by setting either LESSCHARSET=IBM-1047 or
LC_CTYPE=en_US in your environment.

koi8-r

Selects a Russian character set.

next

Selects a character set appropriate for NeXT computers.

utf-8

Selects the UTF-8 encoding of the ISO 10646 character set.

In special cases, it may be desired to tailor less to use a character set other than the ones definable by
LESSCHARSET. In this case, the environment variable LESSCHARDEF can be used to define a character
set. It should be set to a string where each character in the string represents one character in the character
set. The character "." is used for a normal character, "c" for control, and "b" for binary. A decimal number
may be used for repetition. For example, "bccc4b." would mean character 0 is binary, 1, 2 and 3 are control,
4, 5, 6 and 7 are binary, and 8 is normal. All characters after the last are taken to be the same as the last, so
characters 9 through 255 would be normal. (This is an example, and does not necessarily represent any real
character set.)

BSD

January 17, 2003

14

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

LESS (1)

This table shows the value of LESSCHARDEF which is equivalent to each of the possible values for LESSCHARSET:
ascii
dos
ebcdic
IBM-1047
iso8859
koi8-r
latin1
next

8bcccbcc18b95.b
8bcccbcc12bc5b95.b.
5bc6bcc7bcc41b.9b7.9b5.b..8b6.10b6.b9.7b
9.8b8.17b3.3b9.7b9.8b8.6b10.b.b.b.
4cbcbc3b9cbccbccbb4c6bcc5b3cbbc4bc4bccbc
191.b
8bcccbcc18b95.33b.
8bcccbcc18b95.b128.
8bcccbcc18b95.33b.
8bcccbcc18b95.bb125.bb

If neither LESSCHARSET nor LESSCHARDEF is set, but the string "UTF-8" is found in the LC_ALL,
LC_TYPE or LANG environment variables, then the default character set is utf-8.
If that string is not found, but your system supports the setlocale interface, less will use setlocale to determine the character set. setlocale is controlled by setting the LANG or LC_CTYPE environment variables.
Finally, if the setlocale interface is also not available, the default character set is latin1.
Control and binary characters are displayed in standout (reverse video). Each such character is displayed in
caret notation if possible (e.g. A for control-A). Caret notation is used only if inverting the 0100 bit results
in a normal printable character. Otherwise, the character is displayed as a hex number in angle brackets.
This format can be changed by setting the LESSBINFMT environment variable. LESSBINFMT may begin
with a "" and one character to select the display attribute: "k" is blinking, "d" is bold, "u" is underlined,
"s" is standout, and "n" is normal. If LESSBINFMT does not begin with a "", normal attribute is
assumed. The remainder of LESSBINFMT is a string which may include one printf-style escape sequence (a
% followed by x, X, o, d, etc.). For example, if LESSBINFMT is "u[%x]", binary characters are displayed
in underlined hexadecimal surrounded by brackets. The default if no LESSBINFMT is specified is
"s<%X>".
PROMPTS
The -P option allows you to tailor the prompt to your preference. The string given to the -P option replaces
the specified prompt string. Certain characters in the string are interpreted specially. The prompt mechanism
is rather complicated to provide flexibility, but the ordinary user need not understand the details of constructing personalized prompt strings.
A percent sign followed by a single character is expanded according to what the following character is:

BSD

%bX

Replaced by the byte offset into the current input file. The b is followed by a single character
(shown as X above) which specifies the line whose byte offset is to be used. If the character is a "t",
the byte offset of the top line in the display is used, an "m" means use the middle line, a "b" means
use the bottom line, a "B" means use the line just after the bottom line, and a "j" means use the "target" line, as specified by the -j option.

%B

Replaced by the size of the current input file.

%c

Replaced by the column number of the text appearing in the first column of the screen.

%dX

Replaced by the page number of a line in the input file. The line to be used is determined by the X,
as with the %b option.

%D

Replaced by the number of pages in the input file, or equivalently, the page number of the last line in
the input file.

January 17, 2003

15

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

LESS (1)

%E

Replaced by the name of the editor (from the VISUAL environment variable, or the EDITOR environment variable if VISUAL is not defined). See the discussion of the LESSEDIT feature below.

%f

Replaced by the name of the current input file.

%i

Replaced by the index of the current file in the list of input files.

%lX

Replaced by the line number of a line in the input file. The line to be used is determined by the X, as
with the %b option.

%L

Replaced by the line number of the last line in the input file.

%m

Replaced by the total number of input files.

%pX

Replaced by the percent into the current input file, based on byte offsets. The line used is determined by the X, as with the %b option.

%PX

Replaced by the percent into the current input file, based on line numbers. The line used is determined by the X, as with the %b option.

%s

Same as %B.

%t

Causes any trailing spaces to be removed. Usually used at the end of the string, but may appear anywhere.

%x

Replaced by the name of the next input file in the list.

If any item is unknown (for example, the file size if input is a pipe), a question mark is printed instead.
The format of the prompt string can be changed depending on certain conditions. A question mark followed
by a single character acts like an "IF": depending on the following character, a condition is evaluated. If the
condition is true, any characters following the question mark and condition character, up to a period, are
included in the prompt. If the condition is false, such characters are not included. A colon appearing
between the question mark and the period can be used to establish an "ELSE": any characters between the
colon and the period are included in the string, if and only if the IF condition is false. Condition characters
(which follow a question mark) may be:

BSD

?a

True if any characters have been included in the prompt so far.

?bX

True if the byte offset of the specified line is known.

?B

True if the size of the current input file is known.

?c

True if the text is horizontally shifted (%c is not zero).

?dX

True if the page number of the specified line is known.

?e

True if at end-of-file.

?f

True if there is an input filename (that is, if input is not a pipe).

?lX

True if the line number of the specified line is known.

?L

True if the line number of the last line in the file is known.

?m

True if there is more than one input file.

?n

True if this is the first prompt in a new input file.

?pX

True if the percent into the current input file, based on byte offsets, of the specified line is known.

?PX

True if the percent into the current input file, based on line numbers, of the specified line is known.

January 17, 2003

16

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

?s

Same as "?B".

?x

True if there is a next input file (that is, if the current input file is not the last one).

LESS (1)

Any characters other than the special ones (question mark, colon, period, percent, and backslash) become literally part of the prompt. Any of the special characters may be included in the prompt literally by preceding
it with a backslash.
Some examples:
?f%f:Standard input.
This prompt prints the filename, if known; otherwise the string "Standard input".
?f%f .?ltLine %lt:?pt%pt\%:?btByte %bt:-...
This prompt would print the filename, if known. The filename is followed by the line number, if known, otherwise the percent if known, otherwise the byte offset if known. Otherwise, a dash is printed. Notice how
each question mark has a matching period, and how the % after the %pt is included literally by escaping it
with a backslash.
?n?f%f .?m(file %i of %m) ..?e(END) ?x- Next\: %x..%t
This prints the filename if this is the first prompt in a file, followed by the "file N of N" message if there is
more than one input file. Then, if we are at end-of-file, the string "(END)" is printed followed by the name
of the next file, if there is one. Finally, any trailing spaces are truncated. This is the default prompt. For reference, here are the defaults for the other two prompts (-m and -M respectively). Each is broken into two
lines here for readability only.
?n?f%f .?m(file %i of %m) ..?e(END) ?x- Next\: %x.:
?pB%pB\%:byte %bB?s/%s...%t
?f%f .?n?m(file %i of %m) ..?ltlines %lt-%lb?L/%L. :
byte %bB?s/%s. .?e(END) ?x- Next\: %x.:?pB%pB\%..%t
And here is the default message produced by the = command:
?f%f .?m(file %i of %m) .?ltlines %lt-%lb?L/%L. .
byte %bB?s/%s. ?e(END) :?pB%pB\%..%t
The prompt expansion features are also used for another purpose: if an environment variable LESSEDIT is
defined, it is used as the command to be executed when the v command is invoked. The LESSEDIT string is
expanded in the same way as the prompt strings. The default value for LESSEDIT is:
%E ?lm+%lm. %f
Note that this expands to the editor name, followed by a + and the line number, followed by the file name. If
your editor does not accept the "+linenumber" syntax, or has other differences in invocation syntax, the
LESSEDIT variable can be changed to modify this default.
SECURITY
When the environment variable LESSSECURE is set to 1, less runs in a "secure" mode. This means these
features are disabled:

BSD

The shell command.

The pipe command.

January 17, 2003

17

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

:e

The examine command.

The editing command.

s -o

Log files.

-k

Use of lesskey files.

-t

Use of tags files.

LESS (1)

Metacharacters in filenames, such as "".


Filename completion (TAB, L).
Less can also be compiled to be permanently in "secure" mode.
ENVIRONMENT
Environment variables may be specified either in the system environment as usual, or in a lesskey(1) file.
If environment variables are defined in more than one place, variables defined in a local lesskey file take
precedence over variables defined in the system environment, which take precedence over variables defined
in the system-wide lesskey file.
COLUMNS
Sets the number of columns on the screen. Takes precedence over the number of columns specified
by the TERM variable. (But if you have a windowing system which supports TIOCGWINSZ or
WIOCGETD, the window systems idea of the screen size takes precedence over the LINES and
COLUMNS environment variables.)
EDITOR
The name of the editor (used for the v command).
HOME

Name of the users home directory (used to find a lesskey file).

LANG

Language for determining the character set.

LC_CTYPE
Language for determining the character set.
LESS

Options which are passed to less automatically.

LESSANSIENDCHARS
Characters which are assumed to end an ANSI color escape sequence (default "m").
LESSBINFMT
Format for displaying non-printable, non-control characters.
LESSCHARDEF
Defines a character set.
LESSCHARSET
Selects a predefined character set.
LESSCLOSE
Command line to invoke the (optional) input-postprocessor.
LESSEDIT
Editor prototype string (used for the v command). See discussion under PROMPTS.
LESSGLOBALTAGS
Name of the command used by the -t option to find global tags. Normally should be set to "global"
if your system has the global command. If not set, global tags are not used.

BSD

January 17, 2003

18

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

LESS (1)

LESSKEY
Name of the default lesskey(1) file.
LESSKEY_SYSTEM
Name of the default system-wide lesskey(1) file.
LESSMETACHARS
List of characters which are considered "metacharacters" by the shell.
LESSMETAESCAPE
Prefix which less will add before each metacharacter in a command sent to the shell. If LESSMETAESCAPE is an empty string, commands containing metacharacters will not be passed to the
shell.
LESSOPEN
Command line to invoke the (optional) input-preprocessor.
LESSSECURE
Runs less in "secure" mode. See discussion under SECURITY.
LESSSEPARATOR
String to be appended to a directory name in filename completion.
LINES Sets the number of lines on the screen. Takes precedence over the number of lines specified by the
TERM variable. (But if you have a windowing system which supports TIOCGWINSZ or
WIOCGETD, the window systems idea of the screen size takes precedence over the LINES and
COLUMNS environment variables.)
SHELL The shell used to execute the ! command, as well as to expand filenames.
TERM

The type of terminal on which less is being run.

VISUAL
The name of the editor (used for the v command).
SEE ALSO
lesskey(1)
AUTHORS
Mark Nudelman markn@greenwoodsoftware.com
Send bug reports or comments to the above address or to bugless@gnu.org.
For more information, see the less homepage at http://www.greenwoodsoftware.com/less.
CAVEATS
The = command and prompts (unless changed by -P) report the line numbers of the lines at the top and bottom of the screen, but the byte and percent of the line after the one at the bottom of the screen.
If the :e command is used to name more than one file, and one of the named files has been viewed previously,
the new files may be entered into the list in an unexpected order.
On certain older terminals (the so-called "magic cookie" terminals), search highlighting will cause an erroneous display. On such terminals, search highlighting is disabled by default to avoid possible problems.
In certain cases, when search highlighting is enabled and a search pattern begins with a , more text than the
matching string may be highlighted. (This problem does not occur when less is compiled to use the
POSIX regular expression package.)

BSD

January 17, 2003

19

LESS (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

LESS (1)

When viewing text containing ANSI color escape sequences using the -R option, searching will not find text
containing an embedded escape sequence. Also, search highlighting may change the color of some of the
text which follows the highlighted text.
On some systems, setlocale claims that ASCII characters 0 through 31 are control characters rather than
binary characters. This causes less to treat some binary files as ordinary, non-binary files. To workaround
this problem, set the environment variable LESSCHARSET to "ascii" (or whatever character set is appropriate).
See http://www.greenwoodsoftware.com/less for the latest list of known bugs in this version of
less.

BSD

January 17, 2003

20

LESSKEY(1)

LESSKEY(1)

NAME
lesskey specify key bindings for less

SYNOPSIS
lesskey [ o output | output = output ] [ input ]
lesskey -V | --version

DESCRIPTION
lesskey is used to specify a set of key bindings to be used by less(1). The input file is a text file which
describes the key bindings. If the input file is -, standard input is read. If no input file is specified, a standard filename is used as the name of the input file; by default $HOME/.lesskey . The output file is a binary
file which is used by less(1). If no output file is specified, and the environment variable LESSKEY is set,
the value of LESSKEY is used as the name of the output file. Otherwise, a standard filename is used as the
name of the output file; by default $HOME/.less is used. If the output file already exists, lesskey will overwrite it.
A system-wide lesskey file may also be set up to provide key bindings. If a key is defined in both a local
lesskey file and in the system-wide file, key bindings in the local file take precedence over those in the system-wide file. If the environment variable LESSKEY_SYSTEM is set, less(1) uses that as the name of the
system-wide lesskey file. Otherwise, less(1) looks in a standard place for the system-wide lesskey file: On
NSH the system-wide lesskey file is /etc/sysless .
The V or version option causes lesskey to print its version number and immediately exit. If V or
version is present, other options and arguments are ignored.
The input file consists of one or more sections. Each section starts with a line that identifies the type of section. Possible sections are:
#command
Defines new command keys.
#line-edit
Defines new line-editing keys.
#env
Defines environment variables.
Blank lines and lines which start with a pound sign (#) are ignored, except for the special section header
lines.

COMMAND SECTION
The command section begins with the line
#command
If the command section is the first section in the file, this line may be omitted. The command section consists of lines of the form: string <whitespace> action [extra-string] <newline>
Whitespace is any sequence of one or more spaces and/or tabs. The string is the command key(s) which
invoke the action. The string may be a single command key, or a sequence of up to 15 keys. The action is
the name of the less action, from the list below. The characters in the string may appear literally, or be prefixed by a caret to indicate a control key. A backslash followed by one to three octal digits may be used to
specify a character by its octal value. A backslash followed by certain characters specifies input characters
as follows:
\b
\e
\n
\r
\t
\ku
\kd
\kr

BACKSPACE
ESCAPE
NEWLINE
RETURN
TAB
UP ARROW
DOWN ARROW
RIGHT ARROW

NSH

LESSKEY(1)

LESSKEY(1)
\kl
\kU
\kD
\kh
\ke
\kx

LEFT ARROW
PAGE UP
PAGE DOWN
HOME
END
DELETE

A backslash followed by any other character indicates that character is to be taken literally. Characters
which must be preceded by backslash include caret, space, tab and the backslash itself.
An action may be followed by an "extra" string. When such a command is entered while running less, the
action is performed, and then the extra string is parsed, just as if it were typed in to less. This feature can
be used in certain cases to extend the functionality of a command. For example, see the { and :t commands in the example below. The extra string has a special meaning for the "quit" action: when less quits,
first character of the extra string is used as its exit status.
The following input file describes the set of default command keys used by less:
#command
\r
forw-line
\n
forw-line
e
forw-line
j
forw-line
\kd
forw-line
E
forw-line
N
forw-line
k
back-line
y
back-line
Y
back-line
K
back-line
P
back-line
J
forw-line-force
K
back-line-force
Y
back-line-force
d
forw-scroll
D
forw-scroll
u
back-scroll
U
back-scroll
\40
forw-screen
f
forw-screen
F
forw-screen
V
forw-screen
\kD
forw-screen
b
back-screen
B
back-screen
\ev
back-screen
\kU
back-screen
z
forw-window
w
back-window
\e\40
forw-screen-force
F
forw-forever
R
repaint-flush
r
repaint
R
repaint
L
repaint
\eu
undo-hilite
g
goto-line

NSH

LESSKEY(1)

LESSKEY(1)
\kh
<
\e<
p
%
\e[
\e]
\e(
\e)
{
}
(
)
[
]
\eF
\eB
G
\e>
>
\ke
=
G
:f
/
?
\e/
\e?
n
\en
N
\eN
m

XX
E
:e
XV
:n
:p
t
T
:x
:d
:t
s
_
|
v
!
+
H
h

goto-line
goto-line
goto-line
percent
percent
left-scroll
right-scroll
left-scroll
right-scroll
forw-bracket {}
back-bracket {}
forw-bracket ()
back-bracket ()
forw-bracket []
back-bracket []
forw-bracket
back-bracket
goto-end
goto-end
goto-end
goto-end
status
status
status
forw-search
back-search
forw-search *
back-search *
repeat-search
repeat-search-all
reverse-search
reverse-search-all
set-mark
goto-mark
goto-mark
examine
examine
examine
next-file
prev-file
next-tag
prev-tag
index-file
remove-file
toggle-option
toggle-option t
toggle-option o
display-option
pipe
visual
shell
firstcmd
help
help

NSH

LESSKEY(1)

LESSKEY(1)
V
0
1
2
3
4
5
6
7
8
9
q
Q
:q
:Q
ZZ

version
digit
digit
digit
digit
digit
digit
digit
digit
digit
digit
quit
quit
quit
quit
quit

PRECEDENCE
Commands specified by lesskey take precedence over the default commands. A default command key may
be disabled by including it in the input file with the action "invalid". Alternatively, a key may be defined to
do nothing by using the action "noaction". "noaction" is similar to "invalid" but less will give an error beep
for an "incalid" command, but not for a "noaction" command. In addition, ALL default commands may be
disabled by adding this control line to the input file:
#stop
This will cause all default commands to be ignored. The #stop line should be the last line in that section of
the file.
Be aware that #stop can be dangerous. Since all default commands are disabled, you must provide sufficient commands before the #stop line to enable all necessary actions. For example, failure to provide a
"quit" command can lead to frustration.

LINE EDITING SECTION


The line-editing section begins with the line:
#line-edit
This section specifies new key bindings for the line editing commands, in a manner similar to the way key
bindings for ordinary commands are specified in the #command section. The line-editing section consists
of a list of keys and actions, one per line as in the example below.
The following input file describes the set of default line-editing keys used by less:
#line-edit
\t
forw-complete
\17
back-complete
\e\t
back-complete
L
expand
V
literal
A
literal
\el
right
\kr
right
\eh
left
\kl
left
\eb
word-left
\e\kl
word-left
\ew
word-right
\e\kr
word-right

NSH

LESSKEY(1)

LESSKEY(1)
\ei
\ex
\kx
\eX
\ekx
\e\b
\e0
\kh
\e$
\ke
\ek
\ku
\ej

insert
delete
delete
word-delete
word-delete
word-backspace
home
home
end
end
up
up
down

ENVIRONMENT SECTION
The environment variable section begins with the line
#env
Following this line is a list of environment variable assignments. Each line consists of an environment variable name, an equals sign (=) and the value to be assigned to the environment variable. Whitespace
before and after the equals sign is ignored. Variables assigned in this way are visible only to less. If environment variables are defined in more than one place, variables defined in a local lesskey file take precedence over variables defined in the system environment, which take precedence over variables defined in
the system-wide lesskey file. Although the lesskey file can be used to override variables set in the environment, the main purpose of assigning variables in the lesskey file is simply to have all less configuration
information stored in one file.
The following input file sets the -i option whenever less is run, and specifies the character set to be "latin1"
:
#env
LESS = -i
LESSCHARSET = latin1

ENVIRONMENT
LESSKEY
Name of the default lesskey file.
LESSKEY_SYSTEM
Name of the default system-wide lesskey file.

FILES
$HOME/.less
Default lesskey file.
$HOME/.lesskey
Default lesskey input file.
/etc/sysless
Default system-wide lesskey file.

SEE ALSO
less(1)

CAVEATS
It is not possible to specify special keys, such as uparrow, in a keyboard-independent manner. The only
way to specify such keys is to specify the escape sequence which a particular keyboard sends when such a
key is pressed.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

link(1)

link(1)

NAME
link Create a link to a file

SYNOPSIS
link [-?] file1 file2

DESCRIPTION
The link command creates a link from the existing file file1 to the file file2 which will be newly created.
file2 must be on the same disk partition as file1.
The link command creates file2 without doing any type of error checking.
Links to directories, links to files on different partitions, and links across hosts will not work. Errors of any
kind in creating the link are silently ignored.
We strongly suggest that you use the ln command instead of the link command, since improper use may
adversely affect the consistency of the file systems.

OPTIONS
link has only one option.
-?

Output a brief summary of available options and then exit with a zero status without linking any
files.

file1

Existing file to be linked.

file2

Newly created link file.

EXAMPLE
The first example links the file foo to the file bar. The second example creates a new file
/u1/data/yourdata which is linked to the file /u1/data/mydata on the host reykjavik.
$ link foo bar
$ link //reykjavik/u1/data/mydata //reykjavik/u1/data/yourdata

DIAGNOSTICS
Since link errors are ignored, there are no diagnostic messages to be output except for network and licensing messages.

EXIT CODES
0

Besides license problems, link always exits with an exit code of 0.

255

Unable to get a license to use the software.

CAVEATS
Since link does not perform any error checking, do not use it except in exceptional cases. Normally, you
should use the ln command instead.

SEE ALSO
ln(1)

ORIGIN
link was written by Thomas Kraus

NOTES
On some systems, only the super user can use the link command. This is not the default for link. If you
want this behavior, change the ownership of the file to root and the mode to 500.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ln(1)

ln(1)

NAME
ln Create a link to a file

SYNOPSIS
ln [-?fins] file1 file2
ln [-?fins] file1 [file2 ...] directory

DESCRIPTION
In the first case, the ln command creates a link from the existing file file1 to the file file2 which will be
newly created. In the second case, links to the named (existing) files are made in the named directory.
ln creates either hard links (the default) or symbolic links. You can create hard links only between files (not
directories) residing on the same disk partition. Symbolic links however, consist of a special file, containing
the name of the file to which it is linked. This allows you to create symbolic links to directories and
between files on different disk partitions. You cannot create hard links or symbolic links between files on
different hosts.

OPTIONS
-f

By default, if the target file already exists, and it does not have appropriate write permissions, ln
will ask for confirmation to unlink the file. With this option, ln does not ask for this confirmation.
It simply deletes the current version of the target file.

-i

With this option, if the target file of a link already exists, then ln will first ask for confirmation to
overwrite the file. If you use the -f option with the -i option, ln will not ask for confirmation
before overwriting the target file.

-n

With this option, if the target file already exists, then ln will NOT create the link which would
have overwritten the current target file.

-s

Create symbolic links instead of hard links. The advantage of symbolic links over hard links is
that symbolic links can cross disk partitions, and you can make symbolic links to directories. Furthermore, the name of the file to which the symbolic link points does not need to exist at the time
that you create the link.
You cannot create a symbolic link if the file (symbolic link to be created) already exists.

-?

Output a brief summary of available options and then exit with a zero status without linking any
files.

file1

Existing file to be linked.

file2

Newly created link file.

EXAMPLE
The first example links the file foo to the file bar. In the output of the ls command, notice that both files
have the same inode number and have two links to them (first and third column). The second example creates the symbolic link /u1/file2 which points to the file /u1/file1 on the host belgrade.
$ ln foo bar
$ ln -s //belgrade/u1/file1 //belgrade/u1/file2
$ ls -li foo bar //belgrade/u1/file2
total 3
113380 -rw-r--r-- 2 tmk
328 Nov 7 14:43 foo
113380 -rw-r--r-- 2 tmk
328 Nov 7 14:43 bar
385299 lrwxrwxrwx 1 tmk
3 Nov 7 14:43 //belgrade/u1/file2 -> /u1/file1

DIAGNOSTICS
ln: Target directory (dirname) not found
When linking more than one file, then the target file must be a directory. The named directory
(last argument) does not seem to exist.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ln(1)

ln(1)

ln: Target file (filename) must be a directory


When linking more than one file, then the target file must be a directory. The target file is not a
directory.
ln: Unable to create symbolic link to file filename
An error occurred while trying to create a symbolic link to the file filename. This message is followed my an appropriate system error message.
ln: Unable to create link to file filename
An error occurred while trying to create a hard link to the file filename. This message is followed
my an appropriate system error message.
ln: Unable to link files across hosts
You tried to create a link to a file that is not on the same host as the file to which the link should
be created. This is not possible to do.
ln: Will not create link file filename: File exists
You used the -n option, and the target file already exists. The -n option causes ln not to overwrite
existing target files.

EXIT CODES
0

No errors detected.

An unknown option was given.

One of the files to be removed was not removable.

255

Unable to get a license to use the software.

CAVEATS
Since link does not perform any error checking, avoid using it except in exceptional cases. You should normally use the ln command.

SEE ALSO
link(1).

ORIGIN
ln was written by Thomas Kraus

NOTES
With regards to the available options for the ln command, it has many varying implementations on the supported platforms. This implementation was selected to closely resemble System V.4 and also to be behave
in a similar way as other NSH commands.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ls(1)

ls(1)

NAME
ls, l, lc, lf, lr, lx List the contents of a directory

SYNOPSIS
ls [-1aAbcCdfFgilLmnopqrRstux?] [filename ...]

DESCRIPTION
The ls program family outputs listings of the named files. ls is the standard program. The remaining programs are derivatives of ls. Each derivative has a specific option turned on.
l

Automatically turns on the option -l

lc

Automatically turns on the option -C

lf

Automatically turns on the options -C and -F

lr

Automatically turns on the options -C and -R

lx

Automatically turns on the option -x

For each directory argument, ls displays the contents of the directory. For each file argument, ls displays the
name of the file itself along with any other requested information. If you do not specify any file arguments,
then ls uses the current directory (.).
Before ls displays a listing, it sorts the listing (by default) alphabetically. The output format of the listing
can also be in the form of a long listing (see the -l, -o, and -g options), a multi-column listing (see the -C,
-x, and -1 options), or a stream listing (see the -m option).
If you do not specify an output format, then the default format depends on two things. If the output is not
going to a terminal (for example, if it is being redirected or piped), then ls outputs the listing in a single column. If the output is going to a terminal, then the default universe behavior determines the output format.
With the P_BSD variable set, ls uses a multi-column output (like with the -x option). With the P_ATT variable set, ls uses a single column output (like with the -1 option).
When using a multi-column output, ls tries to determine the width of the screen by looking at the value of
the COLUMNS variable. If the COLUMNS variable is not set, or if it has a value less than 20, then ls will
try to determine the width of the screen by using the value of the TERM variable to consult the terminfo or
termcap database (depending on the type of system the command is running on). If ls is still not able to
determine the width of the screen, it uses the default value of 80.

OPTIONS
-1

This option tells ls to produce a single column output instead of a multi-column output. This may
be the default, depending on the universe setting.

-a

By default, ls does not display files beginning with a period (.). This often includes the directories
"." (current directory) and ".." (parent directory). This option tells ls to include all files beginning
with a period.

-A

This option is similar to the -a option, however it does not include the directories "." and "..".

-b

By default, ls outputs the name of the files as it finds them. Consequently, if a file contains special
characters in the name, the output may look jumbled and/or unreadable. With this option, ls will
output all non-printable characters in the form \nnn where nnn is the octal value of the unprintable character (also see the -q option).

-c

If you use the -c option with the -t option (sort the listing by time), then ls sorts the listing by date
of last modification. (This is the default behavior.) If you use the -c option with the -l option (or
other options that produce a long listing), then ls includes the date of last modification in the listing.

-C

This option tells ls to output the a multi-column listing sorted by column. See UNIVERSE
BEHAVIOR for details on how this option works.

-d

If one of the file arguments to ls is a directory, then ls usually will list the contents of that directory. With this option, ls will output a listing for the directory itself and not its contents.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ls(1)

ls(1)

-f

With this option, ls treats each file argument as a directory, with the contents of each directory
being listed as found (no sorting). With this option turned on, the options -l, -t, -s, and -r are
turned off, while the -a option is turned on.

-F

This option causes ls to mark certain file types with an identifying character after the file name.
Directories are marked with a /, files with the user execute bit set are marked with a *, symbolic links are marked with a @, and sockets are marked with a =.

-g

This option tells ls to output a long listing. With the P_BSD variable set, ls also displays the
owner name/ID field. With the P_ATT variable set, ls does not display the owner name/ID field.

-i

For each file found, ls will output the files inode number in a separate field before the name of
the file.

-l

This option tells ls to output a long listing. A long listing consists of a single line for each file.
Each line contains detailed information about the file.

-L

By default, when an argument is a symbolic link, ls treats it as such and does not follow it. This
option tells ls to dereference (follow) arguments that are symbolic links.

-m

This option causes ls to output the files in a stream format. A stream format means that ls will
display as many file names as it can fit on a line, putting a comma and a space between file
names.

-M

Include the md5 checksum of the file as a field in the output. The checksum of a symlink is the
checksum of its target. ls produces blank output for otherwise non-regular files (directories,
block/character special, ... etc.)

-n

When outputting a long listing, use the numeric values of the UID and GID instead of their associated names.

-o

This option is similar to the -l option, except that ls does not display the group name/ID.

-p

This option causes ls to put a slash (/) after each file that is a directory. This makes it easy to
identify directories.

-q

By default, ls outputs the name of the files as it finds them. Consequently, if a file contains special
characters in the name, the output may look jumbled and/or unreadable. With this option, ls will
output all non-printable characters as question marks (?).

-r

When used with the -t option, does a reverse sort by time stamp. When used with the -u option,
does a reverse sort by user name. See the -t option and the -u option for more information.

-R

If ls comes across a directory, then ls will recursively descend the directory and produce a listing
for that directory.

-s

For each file found, ls will output the files size in blocks in a separate field before the name of
the file. The block size can either be 1024 (P_BSD) or 512 (P_ATT) depending on the universe
setting.

-S

By default, ls sorts the listing by file name. With this option, ls sorts the listing by file size.

-t

By default, ls sorts the listing by file name. With this option, ls sorts the listing by time stamp.
The default time stamp is date of last modification. See the options -c and -u for more information.

-u

If sorting the listing by time with the -t option, then sort the listing by the date of last access
instead of the date of last modification. When used with the -l option (or other options producing
a long listing), tells ls to output the date of last access instead of the date of last modification.

-v

This option is like the -F option, but instead of marking directories with a slash (/), ls surrounds
directories with square brackets ([ and ]).

-x

This option tells ls to output the a multi-column listing sorted by rows. See UNIVERSE BEHAVIOR for details on how this option works.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ls(1)

-?

ls(1)

Output a brief summary of available options and then exit with a zero status without doing any
listing.

EXAMPLE
The first example outputs a multi-column listing of the current directory. Any directories found in the current directory have a / appended to their names. The second example produces a long listing sorted in
reverse by time of last modifications of all files/directories beginning with the letter a in the directory bin
on the host berlin.
$ ls -pC
$ ls -lrt //berlin/bin/a*

DIAGNOSTICS
ls: filename <system error message>
Ls was unable to determine detailed information about the file filename.
ls: %s: Unable to access directory dirname
Ls was unable to access the directory dirname to determine its contents.

EXIT CODES
0

No errors detected

An unknown option was given

One of the files to be listed was not accessible

255

Unable to get a license to use the software.

ls ignores column settings less than 20. Instead, ls uses the default screen width of 80.
There are 25 options for this command.

UNIVERSE BEHAVIOR
Because of the large number of options for this command, there are several option conflicts.
Multi-column listings are presented differently depending on your universe setting. With the P_BSD variable set, ls aligns columns to the nearest 8 character interval with columns separated by TAB characters.
With the P_ATT variable set, ls calculates column widths based on the longest file name with an interval of
two spaces between columns.
The -g flag has two very different meanings depending on your universe setting. With the P_BSD variable
set, the group name field is also included in long listings. With the P_ATT variable set, a long listing is
automatically made with the group name file not shown.
When using the -s option to display file sizes in blocks, then with the P_BSD variable set, ls assumes block
sizes to be 1024 bytes large. With the P_ATT variable set ls assumes block sizes to be 512 bytes large.
If a long listing is being output, then with the P_BSD variable set the default behavior is not to output the
group name field. With the P_ATT variable set, the default behavior is to output the group name field.
If a long listing is not being produced, and the user has not selected an output format (-1, -C, or -x options),
then with the P_BSD variable set ls will default to a multi-column output equivalent to the -x option. With
the P_ATT variable set ls defaults to a single column output equivalent to the -1 option.

ORIGIN
ls was written by Thomas Kraus

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

man(1)

man(1)

NAME
man Get man pages from remote host

SYNOPSIS
man [-h host] man_options

DESCRIPTION
man invokes a man page on a selected remote host. man displays the output of the remote man command,
thus letting you effectively access the man page on the remote host.
Normally, you specify the name of the host that contains the man page, using the -h host option. If you do
not specify this option, man will check the shell variable P_MANHOST for the name of a host.

OPTIONS
-h

The name of the host that contains the man page.

-?

Output a brief summary of available options and then exit with a zero status without displaying
any man pages.

EXAMPLE
The first example prints the man page for the command man which is found on the host dublin. The second example prints the man page for the command wait in section 2 of the man pages, found on the host
dublin (as defined by the P_MANHOST variable).
$ man -h dublin man
$ P_MANHOST=dublin
$ export P_MANHOST
$ man -s 2 wait

DIAGNOSTICS
man: Do not know on which host to look for man pages on
This message is output if you did not specify the -h option and the P_MANHOST variable was not
set. Because of this, man was unable to determine where to look for the man page.
man: Error in starting remote program
This error message is output when no data was received back from the remote host when executing the man command on it.

EXIT CODES
0

No errors detected.

man does not know on which host to look for man pages.

No data was returned from the remote host.

255

Unable to get a license to use the software.

CAVEATS
Some versions of man automatically redirect their output to the more command for easier browsing. This
version of man does not.
The available options for the man command differ from system to system. You must use the command
syntax for the host from which you are retrieving the man page.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

md5sum(1)

md5sum(1)

NAME
md5sum Calculate MD5 checksum of files

SYNOPSIS
md5sum [-bltf] [-o offset] [-s size] [file ...]

DESCRIPTION
The md5sum command calculates the MD5 checksum of each file you specify as an argument. If you do
not specify any files, md5sum takes its input from stdin. If you specify a file on a remote host, the remote
RSCD agent calculates the MD5 checksum, so as not to have to pull the whole file across the network.

OPTIONS
-b

This option tells the md5sum command to read the file in binary mode (as opposed to textual
mode). This is the default behavior.

-l

Light mode. Only read (up to) the first 512 bytes (same as -s 512).

-t

This option tells the md5sum command to read the file in textual mode (as opposed to binary
mode). This option is useful when dealing with textual files on a Windows system, where you do
not want to have the different end of line characters (which differ between UNIX and Windows)
affect the calculation.

-f

Do not output warning messages.

-o offset This option tells md5sum what offset in bytes to start calculating from. You can use this option
in conjunction with the -s option to checksum subsets of the file. If the offset value ends with a
k md5sum will interpret the value as a KB value. If the offset value ends with an m md5sum
will interpret the value as a MB value.
-s size

This option tells md5sum the number of bytes to use in the calculation. You can use this option
in conjunction with the -o option to checksum subsets of the file. If the size value ends with a k
md5sum will interpret the value as a KB value. If the size value ends with an m md5sum will
interpret the value as a MB value.

AUTHOR
md5sum was written by Thomas Kraus

SEE ALSO
ls (-M option)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

mkdir(1)

mkdir(1)

NAME
mkdir Create directories

SYNOPSIS
mkdir [-m mode] [-p] [-?] dirname ...

DESCRIPTION
mkdir creates new directories. By default, mkdir creates directories with the mode 0777. (This may be
altered by the value of current umask.) Parent directories for the new directory must already exist unless
you use the -p option (see below).

OPTIONS
-m mode
Set the file permissions of all created directories to mode, where mode is an octal value. By
default the mode of the newly created directories is calculated to be:
0777 minus <current umask of local host>
-p

By default the parent of the directory must already exist. With this option, mkdir will create parent directories as required.

-u user

Set the initial user ownership to user. On Windows this must be numeric and you must have
appropriate permissions on the file. Otherwise a warning message appears.

-g group Set the initial group ownership to group. On Windows this must be numeric and you must have
appropriate permissions on the file. Otherwise a warning message appears.
-?

Output a brief summary of available options and then exit with a zero status without creating any
directories.

dirname The name of the directory you want to create.

EXAMPLE
The first example creates the directory newdir in the local directory. The second example first makes sure
the directories /u2 and /u2/newdir exist. If either directory does not exist, mkdir creates the missing
directory. Second, mkdir creates the directory /u2/newdir/src. Each of the created directories will
have their permissions set to mode.
$ mkdir newdir
$ mkdir -p -m 0755 //andorra/u2/newdir/src //madrid/u2/newdir/src

DIAGNOSTICS
mkdir: Error creating directories dirname
An error was encountered while creating the directory dirname. This message is followed by a
system error message indicating the possible problem.
mkdir: Invalid mode (mode)
The mode the directory should be set to must be in octal (digits 0-7). If the mode contains non
octal digits, then this error message will appear.

EXIT CODES
0

No errors detected.

An unknown option was given.

mkdir was unable to create one of the named directories.

255

Unable to get a license to use the software.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

mkdir(1)

mkdir(1)

ORIGIN
mkdir was written by Thomas Kraus

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

mkfifo(1)

mkfifo(1)

NAME
mkfifo Create named pipe (FIFO)

SYNOPSIS
mkfifo name ...

DESCRIPTION
mkfifo creates a named pipe (FIFO) for each of the named arguments. The mode of the newly created
named pipe is calculated as follows:
0666 minus <current umask of local host>

OPTIONS
name

The name of the named pipe you want to create.

EXAMPLE
The first example creates the named pipe mypipe in the local directory. The second example creates the
named pipes /tmp/pipe1 and /tmp/pipe2 on host montecarlo
$ mkfifo mypipe
$ mkfifo //montecarlo/u2/pipe1 //montecarlo/u2/pipe2

DIAGNOSTICS
mkfifo: Error creating named pipe filename
If an error occurred while creating the named pipe, this error message will appear along with an
appropriate system message.

EXIT CODES
0

No errors detected.

You specified an unknown option or an option was missing.

mkfifo was unable to create the special file.

255

Unable to get a license to use the software.

CAVEATS
You must be a super user to create character and block special files.
You cannot create a special file if a file of that name already exists.

ORIGIN
mkfifo was written by Thomas Kraus

SEE ALSO
mknod(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

mknod(1)

mknod(1)

NAME
mknod Create a special file

SYNOPSIS
mknod name [p] [b | c major minor]

DESCRIPTION
mknod creates a special file. The first argument is the name of the special file. The second argument specifies the type of special file, which can be either a named pipe (FIFO) (p), a character special file (c), or a
block special file (b). If you create a character or block special file, you must also specify the major and
minor number of the device. The mode of the newly created special file is calculated as follows:
0666 minus <current umask of local host>

OPTIONS
name

As the first argument, the name of the special file you want to create.

As the second argument, tells mknod to create a named pipe (FIFO).

As the second argument, tells mknod to create a character special file.

As the second argument, tells mknod to create a block special file.

major

The major number of the character/block special file.

minor

The minor number of the character/block special file.

EXAMPLE
The first example creates the named pipe mypipe in the local directory. The second example creates the
character special file /tmp/null on host tirana
# mknod mypipe -p
# mknod //tirana/tmp/null c 3 2

DIAGNOSTICS
mknod: Error creating special file filename
If an error occurred while creating the special file, this error message will appear along with an
appropriate system message.

EXIT CODES
0

No errors detected.

You specified an unknown option or an option was missing.

mknod was unable to create the special file.

255

Unable to get a license to use the software.

CAVEATS
You must be a super user to create character and block special files.
You cannot create a special file if a file of that name already exists.

ORIGIN
mknod was written by Thomas Kraus.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

mv(1)

mv(1)

NAME
mv Move or rename files

SYNOPSIS
mv [-fi?] file1 file2
mv [-fi?] file ... dir

DESCRIPTION
mv works in two forms. First, you can use it to rename files. Second, you can use it to move files/directories from one directory into another.
The last argument given to mv is the destination file/directory (target). If there are two or more files to be
moved to the target, then the target must be a directory.

OPTIONS
-i

With this option, if a target file already exists, then mv will ask for confirmation to overwrite the
target file. If the user confirms with an entry beginning with the letter y, then mv overwrites the
file. See UNIVERSE BEHAVIOR for details on how this option interacts with the -f option.

-f

This option tells mv not to check for potential overwrite problems in the target files mode. By
default, mv checks to see if the target file already exists, and makes sure that the file has appropriate write permissions allowing it to be overwritten. If the file exists and does not have appropriate
permissions, mv prompts you to see if it should overwrite the file anyway. With the -f option, mv
does not display this prompt. It simply overwrites the file.

-?

Output a brief summary of available options and then exit with a zero status without moving any
files.

file1

Source file.

file2

Destination file or directory.

EXAMPLE
The first example renames the file foo.bar to foobar. The second examples moves all .c files from
the directory /u1/src from host bucharest to the local directory new_src.
$ mv foo.bar foobar
$ mv //bucharest/u1/src/*.c new_src

EXIT CODES
0

No errors detected.

An unknown option was given.

An error occurred while trying to move a file.

255

Unable to get a license to use the software.

DIAGNOSTICS
mv: Target directory (dirname) not found
When moving more than one file, then the target file must be a directory. The named directory
(last argument) does not seem to exist.
mv: Target file (filename) must be a directory
When moving more than one file, then the target file must be a directory. The target file is not a
directory.
mv: Unable to access file filename
The file to be moved (filename) was not accessible.
mv: Unable to access parent directory dirname
The parent directory of the target file/directory could not be found.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

mv(1)

mv(1)

mv: Unable to create link to new file filename


An error occurred while moving the file filename. The target file could not be created.
mv: Unable to unlink file filename
After the source file has been linked to the target file, the source file is removed. There was an
error removing the source file.
mv: Unable to move directory dirname across partitions or hosts
You can move directories only within a disk partition. See cp for more details on copying directories.
mv: Unable to open file filename
If a cross partition/host move is to be made, the files are actually copied. The source file to be
copied could not be accessed.
mv: Unable to create file filename
If a cross partition/host move is to be made, the files are actually copied. The target file could not
be created.
mv: Error writing to file filename
If a cross partition/host move is to be made, the files are actually copied. There was an error
copying the source file to the target file.
mv: Could not unlink file filename
If a cross partition/host move is to be made, the files are actually copied. After having copied the
source file to the target file, the source must be deleted. There was an error deleting the source
file.
You cannot move directories over partition or host borders.

UNIVERSE BEHAVIOR
If you use both the -i and -f options, then with the P_BSD variable set (Berkeley behavior), the -i option
will override the -f option. With the P_ATT variable set, the -f option will override the -i option.

ORIGIN
mv was written by Thomas Kraus

SEE ALSO
cp(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ncp(1)

ncp(1)

NAME
ncp, ndsync Copy/synchronize multiple sources to multiple destinations

SYNOPSIS
ncp [-bifnprtuvBCLPRST?] [-s suf] source1 ... sourceN
-[hv] [-d dir] [-p n] dest1 ... destN
ndsync [-bifnprtuvBCLPRST?] [-s suf] source1 ... sourceN
-[hv] [-d dir] [-p n] dest1 ... destN

DESCRIPTION
ncp and ndsync are supersets of their respective cp and dsync parents. These commands provide an alternate interface, allowing users to copy/synchronize multiple files and/or directories to multiple destinations.
For full details of how the cp/dsync commands work, see their respective documentation.
These commands are most useful when you want to update multiple remote hosts with the same data.

OPTIONS
The command line arguments are split into multiple sections. The descriptions below apply to both the ncp
and ndsync commands. The sections are:
ncp <cp options> <sources> <ncp options> <destinations>
<cp options>
Since ncp/ndsync are supersets of cp/dsync, these options are the same options supported by the
respective parent command.
<sources>
These are the files and/or directories that you want to copy to the given destinations.
<ncp options>
These options affect the way in which the source files/directories are copied to the destinations.
The available options are:
-

If you are not using any other options, you must include a dash (-) to delimit the start of
your target destination(s).

-h

This indicates that the destinations are actually hostnames or I.P. addresses to which
you want to copy the <sources>. If you use this option, then the <sources> must be
absolute path names, unless you are using the -d option, because the <sources> are
copied to the same location on the destination hosts.

-f file

This option lets you define a list of destinations inside a flat file. If you use this option
with the -h option (above) then the flat file should contain a list of hosts. Otherwise,
the flat file should contain a list of files/directories to which you want to copy the
<sources>.

-d dir

This option can be used in conjunction with the -h option to indicate the (absolute)
directory on the destination host into which you want to copy the <sources>.

-p n

Copy in parallel. This option indicates that for each source/destination pair, a separate
process should be created to perform the copy. A maximum of n processes in parallel
are started at any time. This option is more useful when copying directories than individual files, because the overhead of each fork and subsequent copy of a single file may
outweigh the rewards of doing things in parallel.

-v

This option tell the program to output verbose messages that include percentages of
how far a particular file has been copied.

EXAMPLE
The following example copies a file to multiple destinations
rome $ ncp /etc/hosts - //athens/etc/host //paris/etc/hosts

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ncp(1)

ncp(1)

You could have done the same thing as follows:


rome $ ncp /etc/hosts -h athens paris
Or as follows:
rome $ cd /etc
rome $ ncp hosts -h -d /etc athens paris
Here is an example of using the -f option
rome $ cat hosts
athens
moscow
lisbon
rome $ ncp -v /etc/hosts -h -f hosts -d /tmp
Copy /etc/hosts -> //athens/tmp/hosts ... Done
Copy /etc/hosts -> //moscow/tmp/hosts ... Done
Copy /etc/hosts -> //lisbon/tmp/hosts ... Done
The following example copies a directory to several remote hosts and does so in parallel:
rome $ ncp -rvp /foo/bar -p 3 -h athens paris london -d /foo

DIAGNOSTICS
See DIAGNOSTICS section in cp documentation.

EXIT CODES
See EXIT CODES section in cp documentation.

ORIGIN
The cp command family (cp, dsync, ncp, ndsync) was written by Thomas Kraus.

SEE ALSO
dsync(1), cp(1), uncp(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary
ncpu(1)

ncpu(1)

NAME
ncpu View CPU information from one or more hosts

SYNOPSIS
ncpu [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]
ncpu2 [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]

DESCRIPTION
ncpu displays CPU information in a standardized format independent of the servers operating system.
ncpu displays data in the following columns:
HOSTNAME
The name of the host the entry applies to.
SLOT

Indicates which slot this CPU occupies. ncpu displays the value as a number. ncpu2 can display
the value as a number or a string.

SPEED The estimated CPU speed in MHz. This data is not available on all systems. In addition, some
systems (for example, AIX) require root access to determine CPU speed. Therefore, this data
may not be available for all servers.
STATUS
Indicates whether the CPU is online or offline.
TYPE

The manufacturer and model type of the CPU.

OPTIONS
-c

Output system overview information as a set of comma separated values. This option overrides
the -t option.

-e expr

Show only entries that match the given expression. See the EXPRESSIONS section below for
more details.

-f file

Load the list of servers whose CPU information you want to display. The file should be a flat file
containing either resolvable hostnames or valid I.P. addresses. See the -f option below.

-H

Do not show a header on output.

-h hosts Specify a list of hosts whose CPU information you want to display. The values must be resolvable hostnames or valid I.P. addresses. You can specify multiple space separated hostnames without re-specifying the -h option.
-r

Sort in reverse order. See the -s option below.

-s field

By default ncpu sorts in reverse order (largest to smallest) on the CPU speed. With the -s option
you can specify an alternate field to sort on. The field must be one of the column headers listed
above.

-t

Display data similar to the way the top command displays data. With this option the data display
is truncated by screen size and repeated periodically. The following keyboard commands are
available while in top mode.
<SPACE>

Refresh the data.

Ctrl-L

Refresh screen.

Ctrl-C

Quit application.

Quit application.

Reverse sort order.

Increase wait time between refreshes by 1 second.

Decrease wait time between refreshes by 1 second.

Sort on the specified column. Replace the # character with 1,2,3,4,or 5.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary
ncpu(1)

ncpu(1)

-w

Define an expression to filter the output data. See the EXPRESSIONS


section below for more details.

Switch to disk info view.

Switch to memory info view.

Switch to network info view.

Switch to system info view.

Switch to process info view.

Switch to statistics view.

Switch to process summary view.

Truncate each line of output to the actual screen width.

EXAMPLE
This example shows how to view CPU information for multiple hosts (and operating systems).
host% ncpu -h engsuse8agt1 engsol9agt2
HOSTNAME
SLOT
SPEED
STATUS
engsol9agt2 0
548
Online
engsuse8agt1 0
2800
Online
engsuse8agt1 1
2800
Online

TYPE
sparcv9
GenuineIntel Intel(R) Pentium(R) 4 CPU 2.8
GenuineIntel Intel(R) Pentium(R) 4 CPU 2.8

This example shows how to view non-numeric slot information using ncpu2.
host% ncpu2 engaix43agt2 engaix53lp1
HOSTNAME
SLOT
SPEED
STATUS
engaix53lp1
00-00
1648
Online
engaix43agt2
00-00
0
Online

TYPE
PowerPC_POWER5
PowerPC_604e

EXPRESSIONS
You can use the -e option to define an expression that filters the output data. The expression should be a
single argument surrounded by single quotes. When an expression is used to match a string, wildcards are
supported. Expressions can contain multiple operators and operands, including NOT, AND, and OR. For
full details on expressions, see the man page for blexpr.

CAVEATS
The -t option mimics the top commands behavior, but does not mimic it exactly.

ORIGIN
ncpu was written by Thomas Kraus

SEE ALSO
blexpr(1), nmem(1), ndf(1), nnet(1), nps(1), nstats(1)

NSH

Property
Propertyof
ofBladeLogic,
BladeLogic,Inc.
Inc.
Strictly confidential and proprietary

ndf(1)

ndf(1)

NAME
ndf View disk usage statistics from one or more hosts

SYNOPSIS
ndf [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]

DESCRIPTION
Ndf displays disk usage statistics of one or more servers in a standardized format independent of the
servers operating system. The data it displays is displayed in columns as follows:
HOSTNAME
The name of the host the entry applies to.
FILESYSTEM
The name of the system device associated with the disk partition
KBYTES
The total amount of available disk space in KB
USED

The total amount of used disk space in KB

FREE

The total amount of available disk space in KB

CAPACITY
Amount of disk space used in terms of percentage of total available.
MOUNTED ON
The directory (or drive) associated with the disk partition

OPTIONS
The following options are available to modify the behaviour of ndf.
-c

Output disk usage information as a set of comma separated values. This option overrides the -t
option.

-e expr

Only show entries which match the given expression. Please see the EXPRESSIONS section
below for more details.

-f file

Load the list of servers from which to get disk usage information. The file should be a flat file
containing either resolvable hostnames or valid I.P. addresses. See the -f option below.

-H

Do not show a header on output.

-h hosts Specify the list of hosts from which to get the disk usage information. The values must be resolvable hostnames or valid I.P. addresses. You can specify multiple space separated hostnames without needing to re-specify the -h option.
-r

Sort in reverse order. See the -s option below.

-s field

By default ndf sorts in reverse order (largest to smallest) on the disk usage capacity. With the -i
option you can specify an alternate field to sort on. The field should be one of the column headers
as described above. Comparisons are made case neutral.

-t

Behave top like. With this option the data is displayed such that it is truncated by screen size and
repeated periodically. The following keyboard commands are available while in top mode.
<SPACE>

Refresh the data

Ctrl-L

Refresh screen

Ctrl-C

Quit application

Quit application

Reverse sort order

Increase wait time between refreshes by 1 second

NSH

Property
Propertyof
ofBladeLogic,
BladeLogic,Inc.
Inc.
Strictly confidential and proprietary

ndf(1)

-w

ndf(1)

Decrease wait time between refreshes by 1 second

Sort on column # which is a value of 1,2,3,4,5,6,7,8,9, or 0 (10).

Define an expression used to filter the output data. Please see the
EXPRESSIONS section below for more details.

Switch to disk info view.

Switch to memory info view.

Switch to network info view.

Switch to system info view.

Switch to process info view.

Switch to statistics view.

Switch to process summary view.

Truncate each line of output to the actual screen width.

EXAMPLE
The following illustrates a simple example of getting disk usage information from multiple hosts sorted
(smallest to largest) by the available disk space:
host% ndf -h solarishost linuxhost winhost -s Free

EXPRESSIONS
With the -e option, you can define an expression used to filter the output data. The expression should be a
single argument (i.e., enclose the expression in single quotes). When an expression is used to match a
string, wildcards are supported. Expressions can contain multiple operators and operands, including NOT,
AND, and OR. For full details on expressions, see the man page for blexpr.

CAVEATS
The top like behaviour is not meant to exactly mimic the top command.

ORIGIN
ndf was written by Thomas Kraus

SEE ALSO
blexpr(1), nmem(1), nps(1), nnet(1), nover(1), nstats(1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ndircmp(1)

ndircmp(1)

NAME
ndircmp Compare contents of multiple directories

SYNOPSIS
ndircmp [-aeMmnOoprst] dir1 dir2 ...

DESCRIPTION
The ndircmp utility lets you compare the contents of multiple directories. Not only does it compare the
contents (file names) of the directories (which files exist or do not exist) but it can also optionally compare
file size, file permissions, file ownerships, and date of latest modification.
In its base use, ndircmp outputs a report of the aggregate files in all given directories. Each entry is preceded with a code field indicating what differences exist, with the first given directory taken as a base line
for the remaining directories. The possible codes are:
<

The file is missing from this directory.

The file is equal (the same) based on all of the comparison parameters you specified.
If the file exists, then depending on which options you specified, the following codes may also
appear.
S

The file exists but is of a different size. Will only appear if you specified the -s option.

The file exists but has a different time of last modification. Will only appear if you
specified the -t option.

The file exists but has different file ownerships. Will only appear if you specified the -o
option.

The file exists but has different access permissions. Will only appear if you specified
the -p option.

OPTIONS
-a

Equivalent to specifying the -s, -t, -o, and -p options.

-e

Do not output files if they are equal.

-f file

Use the directories listed in file as arguments for the command.

-M

Also compare the files respective MD5 checksums in the comparison. The calculation of MD5
checksums will significantly increase the amount of time it takes to perform the file/directory
comparisons.

-m

Do not output files if they are equal or missing. If you specify this option without specifying any
additional comparisons (besides existence) then ndircmp will not output a report.

-n

Output file ownerships numerically (UID/GID) instead of by username/groupname.

-O

This option tells ndircmp to calculate the optimal spacing for the generated output based on the
width of the output device. By default, the width is set to 80 characters. You can change the output device width by using the -w option.

-o

Also compare file ownerships. If ndircmp detects a different file ownership, it indicates this ownership difference by including the letter O in the compare code. When you specify the -o option,
each entry for an existing file will include the username/groupname of the file in parentheses.

-p

Also compare file permissions. If ndircmp detects different file permissions, it indicates this permissions difference by including the letter P in the compare code. When you specify the -p
option, each entry for an existing file will include the octal file permissions of the file in parentheses.

-r

Traverse directories recursively.

-s

Also compare file sizes. If ndircmp detects different file sizes, it indicates this size difference by
including the letter S in the compare code. When you specify the -s option, each entry for an

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ndircmp(1)

ndircmp(1)

existing file will include the file size in parentheses.


-t

Also compare dates of last modification. If ndircmp detects different dates of last modification, it
indicates this last modification difference by including the letter T in the compare code. When
you specify the -t option, each entry for an existing file will include the date of last modification
of the file in parentheses.

-w width
When calculating the optimal output, assume the output device width to be width characters. The
default assumption is 80 characters.
-[1-9]

Specify the maximum number of columns to output. By default, ndircmp outputs a table that has
N columns, where N is the number of directories being checked. These options (-1, -2 ... -9) let
you specify how many columns to output with directory results (sets of columns) separated by a
form feed (Ctrl-L) character.

ORIGIN
ndircmp was written by Thomas Kraus.

SEE ALSO
cp(1), dsync(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nexec(1)

nexec(1)

NAME
nexec Engine to interface remote commands.

SYNOPSIS
nexec [-?] [-t term] [-o] [-i] [-l] [-nohup hostname "cmd &"] -e | hostname cmd [args]

DESCRIPTION
The nexec program works in one of two ways. If the program is called explicitly, it uses the syntax nexec
ARG1 ARG2. The first argument is either the name of the host on which the specified command should be
executed or the command option -e, which indicates that the command should be executed on the current
remote host, as determined by the current working directory. The remaining arguments are the name and
arguments of the remote program to be executed.
The other way to call the nexec program is by calling a command that is implicitly linked to the nexec program. Invoking a command that is linked to nexec automatically translates the command from <command>
to nexec <host> <command>, where the host is determined by the programs present working directory.
For the command to be executed directly from /bin/nsh, an entry in the Network Shell remote_cmds configuration file must exist indicating that this command should be treated as a remote command. For more
information, see the NETWORK SHELL UTILITIES section below.
Once the remote program has been started, the nexec command acts as an I/O interface to the remotely running command. Nexec captures all stdin and sends it to the remote command (see -n option), and it displays all stdout/stderr it gets sent by the remote command. On UNIX agents, a pseudo tty is created in
which the program is run while on Windows agents a simple pipe-based I/O mechanism is used to communictae with the command.

COMMAND OPTIONS
-e

Executes the command on the current remote host.

-i

Tells the agent to run in a pure interactive mode, which some interactive programs need (e.g.,
Solaris /bin/vi or AIX smit). If you specify this option, any messages to standard error messages
are indistinguishable from standard output messages. Without this option, the remote stdout/stderr outputs are written to the respective local stdout/stderr.
You should only use this option when the remote interactive program does not behave as expected
on screen.

-l

Simulates a login session. This option attempts to start the remote program in a way that simulates an actual login session. It sets the HOME, LOGNAME, and USER environment variables to
their respective values based on the remote permissions. It sets your initial working directory to
the home directory of the effective remote user. It then invokes the cmd args using the effective
remote users default shell and also sets argv[0] of the executing program (the effective remote
users default shell) to "-". This is a traditional method understood by shells (sh, ksh, bash, etc.)
for indicating that the shell is a login shell and that the shells startup scripts (e.g., .profile)
should be run. Finally, this option creates an appropriate entry in the utmp database for use by
utilities such as who.
Note that this option only applies when the remote server is a UNIX-like machine. In addition,
not all platforms fully support the utmp entry.
Note that if the cmd executed is the effective remote users default shell then nexec will execute
the command directly instead of spawning their shell twice.
The following examples show what exactly gets executed (assuming a default shell of /bin/ksh).
Client sends
nexec -l -e ls -la
Agent executes /bin/ksh -ksh -c "ls -la"
Client sends
nexec -l -e ksh
Agent executes /bin/ksh -ksh

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nexec(1)

-n

nexec(1)

Leave stdin alone (do not read any data from stdin). By default, nexec will read all data it gets
from stdin and sent it to the remote command as standard input (stdin). With this option stdin is
not read and as such should only be used with commands that do not require any input. See
examples below.

-nohup hostname "cmd &"


Executes a command in the background on the specified server. This option is available on agents
running 7.0.3 or later.
-o

Use the legacy version of the nexec protocol. Release 7.0 introduced some synchronization fixes
to the nexec protocol. Use this option to tell nexec not to use the synchronization fixes.

-r

Do not transcode input/output. See INTERNATIONALIZATION ISSUES below for more


details.

-u

With this option nexec will convert all output (stdout/stderr) generated by the command from the
local code page of the target server to UTF8. This assumes that the generated output consists of
proper code page sequences. As such, random binary data may not be converted properly and
invalid and/or unrecognized sequences will be converted to question marks (?).

-t term

Tells nexec to ignore the value of the TERM variable and use term instead as the terminal type.

See the EXAMPLES section below for more information. When using the nexec command to execute a
command on a Windows host, the command to be executed cannot be an interactive command. It must be a
batch (output only) command.

INTERNATIONALIZATION ISSUES
One of the issues a user could run into when dealing with multiple computers is how these computers
meaningfully interact in a mixed code page environment.
Imagine for example, a Windows server localized for Japanese with a code page of CP932 and a Solaris
server also localized for Japanese but with a code page of EUC-JP. Now imagine that from the Windows
server one kicks off a command (via nexec) on the Solaris server that generates Japanese output. The output which would now be displayed on the Windows server will be incorrect as the Windows is looking to
output CP932 code sequences and the Solaris server is providing EUC-JP code sequences. As such the output will be not very useful.
To deal with this nexec will now, by default, automatically transcode data. Output generated by the command is captured by the agent and converted to UTF-8 before being sent back to the nexec client where it is
converted to the local code page before it is output to the terminal/screen. In the same way, input (stdin)
captured by the nexec client is converted to UTF-8 before it is sent to the agent where, before it is passed to
the application, is converted to the local code page.
As this automatic transcoding may not always be desired there is the -r option to have all data dealt with in
raw mode, meaning no auto transcoding.
It should be noted that if there are any transcoding issues, that unrecognized characters are replaced with
question marks (?). If this type of behaviour is not wanted, then one should use the -r (raw) option to
have no transcoding done.

X11 FORWARDING
The nexec utility automatically configures the agent to capture X11 traffic by resetting the DISPLAY variable and tunneling traffic to the server that initiated the nexec call. This allows you to securely tunnel X11
traffic using the same security features as other NSH utilities.

DEFAULT PROGRAMS
The Network Shell provides the following pre-configured links:
arp

Address resolution display and control

finger

Display information about users

ifconfig

Configure and show network interface parameters

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nexec(1)

ipconfig (NT)

Configure and show network interface parameters

mem (NT)

Display memory usage

mount

Mount or show mounted file system

nbtstat (NT)

Show nbt statistics

net (NT)

Interface to net command

netstat

Show network statistics

nfsstat

Display NFS status/statistics

ps

Display process status/statistics

size

Report size of an object file

swap

Display swap space status/statistics on System V type systems

umount

Unmount files system

uptime

Determine how long a system has been up

who

Display who is logged in on a system

xterm

Start a remote xterm displaying on your local screen.

nexec(1)

NETWORK SHELL UTILITIES


To have the Network Shell seamlessly execute remote programs, take the following steps. First, make a link
to the Network Shell utility nexec and then make a corresponding entry in the remote_cmds file to indicate
the program is a remote command. The following example shows how a remote utility called foobar can be
configured for remote execution.
#
#
#
#
#

cd cat /usr/lib/rsc/HOME
cd bin
ln -s nexec foobar
cd ../share
echo "foobar
<path_to_foobar>"

>> remote_cmds

Now from the Network Shell environment you can:


$ /bin/nsh
$ cd //rome/home/foo
$ foobar -now
In the above example, the second field (<path_to_foobar>) is an optional path to the remote executable.
This field is only required if the executable is not found in the PATH of the remote RSCD Agent (daemon)
when the Agent is started. For more information, see the nsh man page.

EXAMPLES
The following example shows typical uses of nexec:
unix% $ nexec winhost net start
unix% $ cd //winhost
winhost% $ nexec -e net start
winhost% $ nexec linux rpm -qai
Notice in the next example the effect of the -n option. In the first instance, the first line of the stdin is read
via the read host command and the remaining entries are gobbled up by nexec and as such only one line of
output is generated. In the second example all entries in the file are handled as nexec is not reading stdin
input.
host% cat hosts

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nexec(1)

nexec(1)

madrid
lisbon
rome
host% cat hosts | while read host
do
echo -n "Hostname for $host is: "
nexec $host hostname
done
Hostname for madrid is: madrid.bletch.com

host% cat hosts | while read host


do
echo -n "Hostname for $host is: "
nexec -n $host hostname
done
Hostname for madrid is: madrid.bletch.com
Hostname for lisbon is: lisbon.bletch.com
Hostname for rome is: rome.bletch.com
In the following example, nexec runs a command named bgCmd in the background on a server named
RemoteHost :
nexec -nohup RemoteHost "bgCmd &"

CAVEATS
Programs/utilities vary between hosts and operating systems. An option may not be universal to all platforms. The best example of this is the ps command. Its options vary drastically between BSD and ATT systems. Similarly, not all commands are available on all hosts.
While the nexec command does support the ability to interface remote interactive commands, this capability is currently limited on Windows machines to simple input/output programs, and programs needing full
Console support may hang or not function as expected.

ORIGIN
nexec was written by Thomas Kraus.

SEE ALSO
rsh(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nlogin(1)

nlogin(1)

NAME
nlogin Secure remote login (through RSCD Agent)

SYNOPSIS
nlogin [-?] [-l user] host

DESCRIPTION
nlogin is a special instance of the nexec utility. It performs a remote login to host. If you do not specify a
username with which to log in to the remote host (by using the -l user option), nlogin will attempt to log
into the remote host using your current login name.
nlogin will prompt you to enter the appropriate remote password. If the remote server successfully authenticates the username and password, the remote users login shell will be started in the remote users HOME
directory.
The login session uses the same encrypted protocol as all other NSH utilities and therefore provides a
secure remote login capability. This capability may be a suitable replacement for utilities such as telnet,
rlogin, and/or ssh.

OPTIONS
-?

Displays a general usage message.

-l user

The user name with which you want to log into the remote host.

host

The name of the remote host you want to log into.

EXAMPLES
host% nlogin santiago
Password for tmk@santiago: *******
$

CAVEATS
You can only nlogin to UNIX style machines.
Utilities such as telnet have a special escape key sequence that lets you exit the protocol and take local
action. nlogin does not have such an escape key sequence.

ORIGIN
nlogin was written by Thomas Kraus.

SEE ALSO
nexec(1), telnet(1).

NSH

Property
Propertyof
ofBladeLogic,
BladeLogic,Inc.
Inc.
Strictly confidential and proprietary

nmem(1)

nmem(1)

NAME
nmem View memory and swap statistics from one or more hosts

SYNOPSIS
nmem [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]

DESCRIPTION
Nmem displays memory and swap statistics of one or more servers in a standardized format independent of
the servers operating system. The data it displays is displayed in columns as follows:
HOSTNAME
The name of the host the entry applies to.
MEMTOTAL
The total amount of physical memory in KB.
MEMUSED
The amount of memory used in KB.
MEMFREE
The amount of free memory available in KB
%MEM Amount of memory used in terms of percentage of total available.
SWAPTOTAL
The total amount of swap space in KB.
SWAPUSED
The amount of swap space used in KB
SWAPFREE
The amount of free swap space available in KB
%SWAP Amount of swap space used in terms of percentage of total available.

OPTIONS
The following options are available to modify the behaviour of nmem.
-c

Output memory information as a set of comma separated values. This option overrides the -t
option.

-e expr

Only show entries which match the given expression. Please see the EXPRESSIONS section
below for more details.

-f file

Load the list of servers from which to get memory information. The file should be a flat file containing either resolvable hostnames or valid I.P. addresses. See the -f option below.

-H

Do not show a header on output.

-h hosts Specify the list of hosts from which to get the memory information. The values must be resolvable hostnames or valid I.P. addresses. You can specify multiple space separated hostnames without needing to re-specify the -h option.
-r

Sort in reverse order. See the -s option below.

-s field

By default nmem sorts in reverse order (largest to smallest) on the swap usage percentage. With
the -i option you can specify an alternate field to sort on. The field should be one of the column
headers as described above. Comparisons are made case neutral.

-t

Behave top like. With this option the data is displayed such that it is truncated by screen size and
repeated periodically. The following keyboard commands are available while in top mode.
<SPACE>

Refresh the data

Ctrl-L

Refresh screen

Ctrl-C

Quit application

NSH

Property
Propertyof
ofBladeLogic,
BladeLogic,Inc.
Inc.
Strictly confidential and proprietary

nmem(1)

-w

nmem(1)

Quit application

Reverse sort order

Increase wait time between refreshes by 1 second

Decrease wait time between refreshes by 1 second

Sort on column # which is a value of 1,2,3,4,5,6,7,8,9, or 0 (10).

Define an expression used to filter the output data. Please see the
EXPRESSIONS section below for more details.

Switch to disk info view.

Switch to memory info view.

Switch to network info view.

Switch to system info view.

Switch to process info view.

Switch to statistics view.

Switch to process summary view.

Truncate each line of output to the actual screen width.

EXAMPLE
The following illustrates a simple example of getting memory and swap information from multiple hosts
sorted (largest to smallest) by total used memory
host% nmem -h solarishost linuxhost winhost -r -s MEMUSED

EXPRESSIONS
With the -e option, you can define an expression used to filter output data. The expression should be a single argument (i.e., enclose the expression in single quotes). When an expression is used to match a string,
wildcards are supported. Expressions can contain multiple operators and operands, including NOT, AND,
and OR. For full details on expressions, see the man page for blexpr.

CAVEATS
The top like behaviour is not meant to exactly mimic the top command.

ORIGIN
nmem was written by Thomas Kraus

SEE ALSO
blexpr(1), ndf(1), nps(1), nnet(1), nover(1), nstats(1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nnet(1)

nnet(1)

NAME
nnet View network adapter configuration data

SYNOPSIS
nnet [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]

DESCRIPTION
nnet displays network adapter configuration data for one or more servers in a standardized format independent of the servers operating system. nnet displays data in the following columns:
HOSTNAME
The name of the host the entry applies to.
NAME

Adapter name.

SPEED NIC speed in Mbit. NIC speed is obtainable only if the user has appropriate permissions. NIC
speed for HP-UX is supported from version 10.2 and beyond.
MAC

Adapter MAC address. Not all adapters have a MAC address. In addition, you might not have the
permissions to gather MAC address data. If there is no MAC address, or if you do not have the
required permissions, the MAC address appears as all zeros.

IP

I.P. address of the adapter.

SUBNET
Subnet mask for the adapter.
BROADCAST
Broadcast address for the adapter.

OPTIONS
-c

Output network adapter configuration information as a set of comma separated values. This
option overrides the -t option.

-e expr

Show only entries that match the given expression. See the EXPRESSIONS section below for
more details.

-f file

Load the list of servers whose network adapter configuration information you want to display.
The file should be a flat file containing either resolvable hostnames or valid I.P. addresses. See the
-f option below.

-H

Do not show a header on output.

-h hosts Specify a list of hosts whose network adapter configuration information you want to display. The
values must be resolvable hostnames or valid I.P. addresses. You can specify multiple space separated hostnames without re-specifying the -h option.
-r

Sort in reverse order. See the -s option below.

-s field

By default, nnet sorts in reverse alphabetical order by host name. With the -s option you can
specify an alternate field to sort on. The field must be one of the column headers listed above.

-t

Display data similar to the way the top command displays data. With this option, the data display
is truncated by screen size and repeated periodically. The following keyboard commands are
available while in top mode.
<SPACE>

Refresh the data.

Ctrl-L

Refresh screen.

Ctrl-C

Quit application.

Quit application.

Reverse sort order.

Increase wait time between refreshes by 1 second.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nnet(1)

-w

nnet(1)

Decrease wait time between refreshes by 1 second.

Sort on the specified column. Replace the # character with 1,2,3,4,5,6, or


7.

Truncate each line of output to the actual screen width.

EXAMPLE
This example shows how to get network adapter configuration information from multiple hosts:
host% nnet -h solarishost linuxhost winhost

EXPRESSIONS
You can use the -e option to define an expression that filters the output data. The expression should be a
single argument surrounded by single quotes. For full details on expressions, see the man page for blexpr.

CAVEATS
The -t option mimics the top commands behavior, but does not mimic it exactly.

ORIGIN
nnet was written by Thomas Kraus

SEE ALSO
blexpr(1), nmem(1), nps(1), nover(1), nstats(1), ndf(1)

NSH

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

NOHUP (1)

NOHUP (1)

NAME
nohup invoke a command immune to hangups
SYNOPSIS
nohup utility [arg . . .]
DESCRIPTION
The nohup utility invokes command with its arguments and at this time sets the signal SIGHUP to be
ignored. If the standard output is a terminal, the standard output is appended to the file nohup.out in the
current directory. If standard error is a terminal, it is directed to the same place as the standard output.
The nohup utility shall exit with one of the following values:
126
127

The utility was found but could not be invoked.


The utility could not be found or an error occurred in nohup.

Otherwise, the exit status of nohup shall be that of utility.


ENVIRONMENT
HOME If the output file nohup.out cannot be created in the current directory, the nohup utility uses the
directory named by HOME to create the file.
SEE ALSO
signal(3)
STANDARDS
The nohup command is expected to be IEEE Std 1003.2 (POSIX.2) compatible.

BSD

June 6, 1993

Property
Propertyof
ofBladeLogic,
BladeLogic,Inc.
Inc.
Strictly confidential and proprietary

nover(1)

nover(1)

NAME
nover View system overview from one or more hosts

SYNOPSIS
nover [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]

DESCRIPTION
Nover displays a system overview in a standardized format independent of the servers operating system.
The data it displays is displayed in columns as follows:
HOSTNAME
The name of the host the entry applies to.
OS

The systems operating system

MAINT The current maintenance release of the OS. This field has different meanings for different operating systems and includes the service pack for Windows, the kernel release for Linux, the release
level for AIX, and as not set for Solaris.
CPUS

The number of system CPUs (online and off).

SPEED The estimated CPU speed in MHz. This data is not available on all systems while some systems
(e.g. AIX) require root access to determine CPU speed and as such this data may not be available
for all servers.
ARCH

The system hardware architecture.

MEMORY
The amount of memory in MB
SWAP

The amount of swap space in MB

DISK

The total amount of local disk space in GB. Windows systems.

OPTIONS
The following options are available to modify the behaviour of nover.
-c

Output system overview information as a set of comma separated values. This option overrides
the -t option.

-e expr

Only show entries which match the given expression. Please see the EXPRESSIONS section
below for more details.

-f file

Load the list of servers from which to get system overview information. The file should be a flat
file containing either resolvable hostnames or valid I.P. addresses. See the -f option below.

-H

Do not show a header on output.

-h hosts Specify the list of hosts from which to get the system overview information. The values must be
resolvable hostnames or valid I.P. addresses. You can specify multiple space separated hostnames
without needing to re-specify the -h option.
-r

Sort in reverse order. See the -s option below.

-s field

By default nover sorts in reverse order (largest to smallest) on the CPU speed. With the -i option
you can specify an alternate field to sort on. The field should be one of the column headers as
described above. Comparisons are made case neutral.

-t

Behave top like. With this option the data is displayed such that it is truncated by screen size and
repeated periodically. The following keyboard commands are available while in top mode.
<SPACE>

Refresh the data

Ctrl-L

Refresh screen

Ctrl-C

Quit application

Quit application

NSH

Property
Propertyof
ofBladeLogic,
BladeLogic,Inc.
Inc.
Strictly confidential and proprietary

nover(1)

-w

nover(1)

Reverse sort order

Increase wait time between refreshes by 1 second

Decrease wait time between refreshes by 1 second

Sort on column # which is a value of 1,2,3,4,5,6,7,8,9, or 0 (10).

Define an expression used to filter the output data. Please see the
EXPRESSIONS section below for more details.

Switch to disk info view.

Switch to memory info view.

Switch to network info view.

Switch to system info view.

Switch to process info view.

Switch to statistics view.

Switch to process summary view.

Truncate each line of output to the actual screen width.

EXAMPLE
The following illustrates a simple example of viewing an overview of multiple hosts (and operating systems).
host% nover -h solaris8 linux
HOSTNAME
OS
MAINT
linux
RedHat ES3
2.4.21-4.EL
solaris8
SunOS 5.8

CPUS
1
1

SPEED
797 MHz
440 MHz

ARCH
i686
sun4u

MEMORY
121 MB
256 MB

SWAP
251 MB
513 MB

EXPRESSIONS
With the -e option, you can define an expression used to filter output data. The expression should be a single argument (i.e., enclose the expression in single quotes). When an expression is used to match a string,
wildcards are supported. Expressions can contain multiple operators and operands, including NOT, AND,
and OR. For full details on expressions, see the man page for blexpr.

CAVEATS
The top like behaviour is not meant to exactly mimic the top command.

ORIGIN
nover was written by Thomas Kraus

SEE ALSO
blexpr(1), nmem(1), ndf(1), nnet(1), nps(1), nstats(1)

NSH

DIS
18 G
17 G

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nprocsum(1)

nprocsum(1)

NAME
nprocsum View process summary from one or more hosts

SYNOPSIS
nprocsum [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]

DESCRIPTION
nprocsum displays process summary for one or more servers in a standardized format independent of the
servers operating system. nprocsum displays data in the following columns:
HOSTNAME
The name of the host the entry applies to.
USER

The username of the owner of the processes on the remote host.

NPROCS
Total number of processes.
VSIZE

The total amount of virtual memory that the processes are using altogether.

RSS

The total amount of real memory that the processes are using altogether.

MEMORY
The percentage of total memory that the processes are using altogether.
TIME

The cumulative amount of CPU that the processes have used altogether.

CPU

The percentage of CPU that the processes have used altogether.Various systems may have different algorithms to determine this value.

OPTIONS
-c

Output process summary information as a set of comma separated values. This option overrides
the -t option.

-e expr

Show only entries that match the given expression. See the EXPRESSIONS section below for
more details.

-f file

Load the list of servers whose process summary information you want to display. The file should
be a flat file containing either resolvable hostnames or valid I.P. addresses. See the -f option
below.

-H

Do not show a header on output.

-h hosts Specify a list of hosts whose process summary information you want to display. The values must
be resolvable hostnames or valid I.P. addresses. You can specify multiple space separated hostnames without re-specifying the -h option.
-r

Sort in reverse order. See the -s option below.

-s field

By default nprocsum sorts in reverse order (largest to smallest) on the total number of processes.
With the -s option you can specify an alternate field to sort on. The field must be one of the column headers listed above.

-t

Display data similar to the way the top command displays data. With this option the data is truncated by screen size and repeated periodically. The following keyboard commands are available
while in top mode.
<SPACE>

Refresh the data.

Ctrl-L

Refresh screen.

Ctrl-C

Quit application.

Quit application.

Reverse sort order.

Increase wait time between refreshes by 1 second.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nprocsum(1)

-w

nprocsum(1)

Decrease wait time between refreshes by 1 second.

Sort on the specified column. Replace the # character with 1,2,3,4,5,6, 7


or 8.

Define an expression to filter the output data. See the EXPRESSIONS


section below for more details.

Switch to disk info view.

Switch to memory info view.

Switch to network info view.

Switch to system info view.

Switch to process info view.

Switch to statistics view.

Switch to process summary view.

Truncate each line of output to the actual screen width.

EXAMPLE
This example shows how to get process summary information from multiple hosts sorted (smallest to
largest) by the available number of processes:
host% nprocsum -h solarishost linuxhost winhost -s NPROCS

EXPRESSIONS
You can use the -e option to define an expression that filters the output data. The expression should be a
single argument surrounded by single quotes. When an expression is used to match a string, wildcards are
supported. Expressions can contain multiple operators and operands, including NOT, AND, and OR. For
full details on expressions, see the man page for blexpr.

CAVEATS
The -t option mimics the top commands behavior, but does not mimic it exactly.

ORIGIN
nprocsum was written by Thomas Kraus

SEE ALSO
blexpr(1), nmem(1), nps(1), nnet(1), nover(1), nstats(1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nps(1)

nps(1)

NAME
nps Displays process information for one or more hosts

SYNOPSIS
nps [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]

DESCRIPTION
nps displays process statistics for the processes running on one or more servers in a standardized format
independent of the servers operating system. nps displays data in the following columns:
HOSTNAME
The name of the host the entry applies to.
USER

The username of the owner of the process on the remote host. All Windows processes are currently owned by root.

PPID

The parent process ID. (This column only appears in the -c output.)

PID

The process ID.

CPU

The percentage of CPU that the process is using. Various systems may have different algorithms
to determine this value.

MEM

The percentage of total memory that the process is using.

VSIZE

The total amount of virtual memory that the process is using.

RSS

The total amount of real memory that the process is using.

PRI

The process priority. The meaning of the value may differ from system type to system type.

START The start time of the process. This field has no relevant value for Windows systems.
TIME

The cumulative amount of CPU that the process has used.

COMMAND
The command name and arguments of the given process.

OPTIONS
-c

Output process information as a set of comma separated values. This option overrides the -t
option.

-e expr

Show only entries that match the given expression. See the EXPRESSIONS section below for
more details.

-f file

Load the list of servers whose process information you want to display. The file should be a flat
file containing either resolvable hostnames or valid IP addresses.

-H

Do not show a header on output.

-h hosts Specify a list of hosts whose process information you want to display. The values must be resolvable hostnames or valid IP addresses. You can specify multiple space separated hostnames without re-specifying the -h option.
-r

Sort in reverse order. See the -s option below.

-s field

By default nps sorts in reverse order (largest to smallest) on the percentage of CPU in use. With
the -s option you can specify an alternate field to sort on. The field must be one of the column
headers listed above.

-t

Display data similar to the way the top command displays data. With this option, the data display
is truncated by screen size and repeated periodically. The following keyboard commands are
available while in top mode.
<SPACE>

Refresh the data.

Ctrl-L

Refresh screen.

NSH

Property
Propertyof
ofBladeLogic,
BladeLogic,Inc.
Inc.
Strictly confidential and proprietary

nps(1)

-w

nps(1)

Quit application.

Reverse sort order.

Increase wait time between refreshes by 1 second.

Decrease wait time between refreshes by 1 second.

Sort on the specified column. Replace the # character with


1,2,3,4,5,6,7,8,9, or 0. 0 indicates column 10.

Define an expression to filter the output data. See the EXPRESSIONS


section below for more details.

Switch to disk info view.

Switch to memory info view.

Switch to network info view.

Switch to system info view.

Switch to process info view.

Switch to statistics view.

Switch to process summary view.

Truncate each line of output to the actual screen width.

EXAMPLE
This example shows how to get process information from multiple hosts, sorted (largest to smallest) by the
amount of real memory the process is using.
host% nps -h solarishost linuxhost winhost -r -s RSS
This second example shows all non root processes.
host% nps -h solarishost linuxhost winhost -e user != "root"
This example searches for non root processes that may be running out of control.
host% nps -h solarishost -e user != "root" & CPU > 5% & mem > 3%

EXPRESSIONS
You can use the -e option to define an expression that filters the output data. The expression should be a
single argument surrounded by single quotes. When an expression is used to match a string, wildcards are
supported. For example, you could create an expression like the following:
host% nps -e COMMAND = "*sbin*"
Expressions can contain multiple operators and operands, including NOT, AND, and OR. For full details
on expressions, see the man page for blexpr.

CAVEATS
The -t option mimics the top commands behavior, but does not mimic it exactly.

ORIGIN
nps was developed by BladeLogic, Inc.

SEE ALSO
blexpr(1), nmem(1), ndf(1), nnet(1), nover(1), nstats(1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nsh(1)

nsh(1)

NAME
nsh Network Shell

SYNOPSIS
This manual page outlines the differences between the Network Shell and a regular shell. It does not provide a detailed description of Network Shell behavior. See the man pages for zsh to obtain detailed information on how the Network Shell works. The Network Shell is a link to a distributed version of zsh.

SHELL PROMPT
The first thing you may notice when you start Network Shell is that the default shell prompt incorporates
the name of the host you are currently on -- assuming the default shell prompt (PS1) has not been previously set. The code generating the prompt replaces the sequence \h with the name of the host you are currently accessing rather than the name of the local host. When you cd to a new host, the \h sequence takes on
a new value, as the following example illustrates.

ACCESSING REMOTE FILES AND HOSTS WITH THE CD COMMAND


The following example shows how to use the cd command to access remote hosts:
beaver $ cd //otter/etc
otter $ pwd
//otter/etc
otter $ uname -a
Linux otter 2.0.34 #1 Fri May 8 16:05:57 EDT 1998 i586 i386
otter $ vi termcap
When you access a remote host, you should also specify a directory. If you do not, the shell connects you
to the // (root) directory.
You can access remote files from the command line:
beaver $ vi //otter/etc/termcap
You can also use the command line to specify files on multiple hosts:
beaver $ diff //otter/etc/termcap //duckbill/etc/termcap

REMOTE WINDOWS DRIVES


When accessing a remote Windows (NT4/2000) machine, you do not have to include the drive letter in the
name. If you have set a root directory, then a drive is irrelevant because the root directory itself is the
highest point you can access on the directory tree. You can never access the root of a drive, such as C:, nor
can you access any other drives.
If you have not set a root directory and you do not provide a drive letter, then the Network Shell environment defaults to the <SYSTEMDRIVE> drive. To access other drives on the computer, explicitly mention
the drive letter as shown in the following examples:
$ /bin/nsh
unix $ cat //windows/c/autoexec.bat
unix $ cd //nt/d
nt $ ls /e/*.EXE
In Network Shell, you should treat the drive letter as a directory even though that differs from how Windows treats drives.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nsh(1)

nsh(1)

THE // DIRECTORY
The Network Shell supports the // directory, which is a virtual directory that contains only hostname entries.
Each entry correspond to another hosts root (/) directory. The // directory allows you to change directories
to another host using relative path names. For example:
host1 $ cd //
host1 $ ls
host1
host2
host1 $ cd host2
host2 $ pwd
//host2/

host3

host4

In another example:
host1 $ pwd
//host1/etc
host1 $ cd ../../host2/etc
host2 $ pwd
//host2/etc
If you have root privileges, you can make entries in the // directory with the mkdir command and remove
them with the rmdir command. You cannot create regular files and other special files in this directory.
Note that you do not need an entry for a remote host in the // directory to access data on that remote host.

EXECUTING A COMMAND
There are three categories of commands you can execute through Network Shell. Native commands, Network Shell equivalents of native commands, or unique Network Shell commands that do not have native
equivalents. This last category is referred to as Network Shell utilities.
When executing a command, you can be in one of two states: on the local host or on a remote host. Network Shell equivalents of native commands are executed by default in either state. For a command for
which there is a native version and a Network Shell equivalent, to execute the native command, enter the
command with a fully qualified path. For example,
Host$ /bin/tar -cvf /tmp/etc.tar /etc
The following section describes the two methods for executing commands on a remote host.
EXECUTING COMMANDS FROM A REMOTE HOST
Network Shell supports two methods for executing commands from a remote host: the default implied
"nexec" method and the remote_cmds file method. The later is supported for backwards compatibility.
When executing a command that has an entry in the remote_cmds file, and the command has a native
equivalent on the remote host with a different path, the version of the command that is executed is the one
pointed to by the path specified in the remote_cmds file.
Implied nexec Execution of Commands on a Remote Host
When your current directory is on a remote host, execution of a native command which is not a Network
Shell command will result in an "nexec" execution of the native command on the remote server. In the following example, the command returns the hostid of host2. The action is equivalent to running "nexec -e
hostid" while being rooted on host2 in Network Shell.
nsh# cd //host2
host2 nsh# hostid

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nsh(1)

nsh(1)

Specifying Remote Commands Using the remote_cmds File


The remote_cmds file contains a list of remote commands that the Network Shell supports. The
remote_cmds file resides in the share directory of the Network Shell install directory. To add a supported
remote command using this method, you must perform two steps. First, in the bin directory of the Network
Shell installation directory, create a soft link to the program nexec. The soft link should have the same
name as the remote command. If, for example, you wanted to run the remote command myapp, you would
create a soft link as follows:
# cd cat /usr/lib/rsc/HOME
# cd bin
# ln -s nexec myapp
Next, create an entry in the remote_cmds file in the share directory relative to the Network Shell installation directory. Each entry consists of up to three white space-delimited fields. (White space can be a TAB
or SPACE.)
command_name command_path max_time
The command_path and max_time fields are optional. By entering a value of -, they can be set to use
default values. For example:
command_name - The command_name field must be the basename of the remote command you want to execute. It should
be a non-interactive program. The command_path should be the absolute path name to the program on the
remote host. If this field is not set, the shell searches for the command in the PATH of the RSCD Agent
(daemon). The max_time field represents the maximum time in seconds that the remote command should
need to execute. The default value is 300 seconds (5 minutes). Adjust this value if you anticipate that the
remote command might take longer than 300 seconds to execute. If the remote command does not finish
after the maximum allocated time, the shell assumes an error has occured and the command is aborted.
To continue with the above example, the second step for the myapp program could look something like
this:
# cd cat /usr/lib/rsc/HOME
# cd share
# echo "myapp
/home/me/bin/myapp

-" >> remote_cmds

When the Network Shell (actually the nexec program) executes a remote command, the shell attempts to
execute the named program on the remote host, capturing both its standard output and standard error.
These remote utilities CANNOT require any terminal input because their standard input is redirected from
/dev/null. Some typical commands in the remote_cmds file are who and ps. Any arguments to these utilities must conform with the remote commands arguments and must be in the PATH of the rscd program.
In addition to regular DOS commands, the RSCD Agent on Windows NT4/2000 machines supports the
built-in commands df, halt, and reboot. Note that by default the Network Shell is not configured to run the
halt and reboot commands. If you want to use Network Shell to run these commands, you must run them
in conjunction with the nexec command.

PATH VARIABLE
When the Network Shell is started, the PATH variable is automatically initialized to include the Network
Shell bin directory as the first element in the PATH. This ensures that all Network Shell utilities are available. This can be unset, but, as described earlier, the Network Shell maps its known utilities to utilities in
the Network Shell bin directory.

REDIRECTION
Redirection in the Network Shell is implemented with pipes rather than the usual dup() or dup2 () system
calls. This is necessary to properly implement redirection to files on remote hosts. There are a few limitations when using redirection. First, only the file descriptors 1 (standard output) and 2 (standard error) are

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nsh(1)

nsh(1)

supported for redirection. Other values may produce unexpected results. Next, the redirection type <>,
which causes the output file to be opened for both read and write, is treated the same as the < redirection
type. The remaining types of redirections work (with the restrictions described above).

THE DISCONNECT COMMAND


The Network Shell dynamically creates network connections to the remote hosts that it accesses. For efficiency reasons, these connections remain open until the user exits the shell or executes the disconnect command. This command closes the network connections of the hosts given to it as arguments. If no arguments
are given, the shell closes all connections. The network connection to the host on which the current directory exists is not closed even if specifically asked to do so.
If the Network Shell again needs access to a remote host, then a new dynamic network connection is created. The Network Shell utilities manage their own network connections and do not affect the shell.
To ensure that you do not exhaust system resources, it is a good idea to call the disconnect command occasionally, especially if you are accessing large numbers of remote hosts. When accessing relatively few
remote hosts, calling the disconnect command is not required.

THE SHELL VARIABLE


The SHELL variable is often used to tell programs the default shell to use when a program needs to run a
shell process. All of the Network Shell utilities ignore this variable and always use /bin/nsh when a shell
process is required.

REMOTE SHELL SCRIPTS


It is possible to execute remote shell scripts. They can be included in your PATH or expressed as an absolute pathname.

STARTUP/SHUTDOWN FILES
See the zsh(1) man page for more information on startup/shutdown files. The NSH differs from ZSH in
that all startup/shutdown files are prepended with nsh instead of z or zsh. For example, instead of using
/etc/zshenv you would use /etc/nshenv instead. The following is a list of valid startup/shutdown files for
NSH.
$ZDOTDIR/.nshenv
$ZDOTDIR/.nshprofile
$ZDOTDIR/.nshrc
$ZDOTDIR/.nshlogin
$ZDOTDIR/.nshlogout
${TMPPREFIX}* (default is /tmp/nsh*)
/etc/nshenv
/etc/nshprofile
/etc/nshrc
/etc/nshlogin
/etc/nshlogout (installationspecific /etc is the default)

USING THE -? OPTION WITHIN THE NSH SHELL


A number of NSH commands let you display brief usage information by specifying the -? option.
For example:
$ agentinfo -?
Usage: agentinfo [-?] [-c] [-H] [-f file] [hostname ...]
-?
Output this message
-c
Output data in CSV format
-f file Load list of host from flat file
-H
Do not output a header line if -c used
If you want to use the -? option when you are WITHIN the NSH shell, you must escape the -? option as
shown below:
agentinfo -\?

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nsh(1)

nsh(1)

SEE ALSO
zsh(1)

NSH

Property of BladeLogic,
Perl Module Inc.
Strictly confidential and proprietary

NSH::(1)

NSH::(1)

NAME
NSH:: - Network Shell Perl module to access and manipulate remote files, processes, and commands.

SYNOPSIS
use NSH;
NSH::...

DESCRIPTION
The NSH Perl Module gives Perl programmers the ability to access remote files and commands. The NSH
module acts as glue between Perl and the Network Shell core technology. The NSH module currently supports 45 calls which interface the corresponding Network Shell distributed API. The NSH calls emulate
their C function counter parts.
All arguments which are file or directory names support UNC syntax which allows the use of a hostname as
part of the filename. If no hostname is included in the argument, then the file on the current host is used.
The following examples will help clarify their use.
use NSH;
$fd = NSH::open ("//hostname/foo/bar", 0, 0) || die "Cant open file: $!\n";
$count = NSH::read ($fd, $buf, 100);
NSH::close($fd);
NSH::chdir ("//hostname/foo/") || die "Cant cd: $!\n";
$fd = NSH::open ("bar", 0, 0) || die "Cant open file: $!\n";
$count = NSH::read ($fd, $buf, 100);
NSH::close($fd);

NSH:: FUNCTIONS
NSH::access (char *path, int mode)
NSH::access() checks the file pointed to by path for accessibility according to the bit pattern contained in mode The values for mode can be the ORing of the following values:
0

(F_OK) Check existence of file

(X_OK) Test for execute or search permission.

(W_OK) Test for write permission.

(R_OK) Test for read permission.

If mode is ommitted it checks for file readability (R_OK).


NSH::chdir (char *dirname)
Change you current directory to dirname. If dirname is a full UNC path (includes a hostname),
then you current host is changed to be that host and all subsequent access to any files which are
not in full UNC (do not include a hosrtname) will be assumed to be on the given host.
NSH::chdir ("//hostname/foo/bar") !! die "Cant cd: $!\n");
NSH::unlink("file");
NSH::chdir ("..");
NSH::rmdir ("bar");
NSH::chmod (char *path, int mode)
Change the mode (protection attributes) of the file path to mode.
NSH::chmod ("//hostname/foo/bar", 0777);
NSH::chdir ("//hostname/foo", 0777);
NSH::chmod ("bar", 0777);

Network Shell Perl Module

NSH::(1)

Property of BladeLogic,
Perl Module Inc.
Strictly confidential and proprietary

NSH::(1)

NSH::chown (char *path, int uid, int gid)


Change the file ownership of the file path to be of owner uid. and group gid.
NSH::chown ("foo", 100, 200);
NSH::close (int fd)
Close the file descriptor fd.
$fd = NSH::open ("/foo/bar") || die "Open failed: $!\n";
NSH::close ($fd);
NSH::closedir (int fd)
Close the file descriptor fd which was returned from a successfull call to NSH::opendir

$fd = NSH::opendir(".") || die "Cant open current directory: $!\n";


while (($filename, $inode) = NSH::readdir($fd))
{
print "FILENAME = $filename\n";
}
NSH::closedir ($fd);
NSH::creat (char *filename, int mode)
Create the file filename with an initial mode (protection attribute) of mode.
$fd = NSH::creat ($filename, 0777) || die "Cant create: $!\n";
NSH::write ($fd, "Hello world\n", 12);
NSH::close ($fd);
NSH::dup (int fd)
Duplicate the open file descriptor fd
NSH::dup2(int fd1, int fd2)
Duplicate the open file descriptor fd1 to filedescriptor fd2
NSH::fchown (int fd, int uid, int gid)
Change the file ownership of the file pointed to by the file descriptor fd to be of owner uid. and
group gid.
$fd = NSH::open("foo") || die "Cant open file: $!\n";
NSH::fchown ($fd, 100, 200);
NSH::close ($fd);
NSH::fchdir (int fd)
Change directory to the pth pointed to by the file descriptor fd.
$fd = NSH::open("//hostname/foo");
NSH::fchdir($fd);
pwd = NSH::getcwd ();
print "PWD = $pwd";
NSH::fgets (char *buffer, int size, int fd)
Read the next line of input from the file descriptor $fd up to a maximum of size bytes.

Network Shell Perl Module

Property of BladeLogic,
Perl Module Inc.
Strictly confidential and proprietary

NSH::(1)

NSH::(1)

$fd = NSH::open ($filename) || die "Cant open $filename: $!\n";


while (NSH::fgets ($buffer, 512, $fd)
{
print "Next line is: $buffer";
}
NSH::close ($fd);
NSH::flock (int fd, int op)
Apply or remove an advisory lock on an open file pointed to by the filedescriptor fd. The argument op determines what operation is to be performed, and can have any of the following values
ORed together.
1

Apply shared lock (LOCK_SH).

Apply exclusive lock (LOCK_SH).

Make operation non-blocking (LOCK_NB).

Remove lock.

NSH::fstat (int fd)


Return information on the file pointed to by the file descriptor fd. Please see the STAT section
below for further information on the stat family of calls.
NSH::ftruncate (int fd, long pos)
Truncate the size of the file pointed to by the file descriptor fd to pos bytes.
NSH::getcwd ()
Return the current NSH:: working directory. The format of the returned value will be a UNC type
name (//hostname/directory) if the current NSH:: directory is on a remote host, or just a regular
path name if the current NSH:: directory is on the local host.
$pwd = NSH::getcwd ();
NSH::getpriority (int which, int who)
Get the scheduling priority for a process, process group or user. Which is one of
0

who is a process identifier (PRIO_PROCESS)

who is a process group identifier (PRIO_PGRP)

who is a user ID (PRIO_USER)

If NSH::getpriority is called with only one argumnet, then it is assumed that the priority for the
given process (PRIO_PROCESS) is desired.
The following examples both get the priority of the process with PID 100.
$prio = NSH::getpriority (0, 100);
$prio = NSH::getpriority (100);
NSH::kill (int pid, int sig)
Send a signal to a process. Pid is the Process ID of the process to receive the signal while sig is
the numberic signal to be sent. If sig is ommitted, then a SIGTERM is sent. Specific signals
may have different values on different OSes. In other words, know what you are doing with the
call.
NSH::kill (100, 9);

Network Shell Perl Module

Property of BladeLogic,
Perl Module Inc.
Strictly confidential and proprietary

NSH::(1)

NSH::(1)

NSH::link (char *existing, char *newname)


Create a hard link called newname to the existing file called existing. Both newname can only
be created on the same host and disk partition as that of the existing file.
NSH::chdir("//hostname/foo");
NSH::link ("file1", file2") || warn ("Link failed: $!\n";
NSH::lseek (int fd, long offset, int whence)
Move the read write pointer of the file descriptor fd as follows:

If whence is 0 (SEEK_SET), the pointer is set to offset bytes.

If whence is 1 (SEEK_CUR), the pointer is set to its current location plus offset bytes.

If whence is 2 (SEEK_END), the pointer is set to size of the file plus offset bytes.

The following example move the read pointer to the end of the file.
$fd = NSH::open ("bar");
NSH::lseek ($fd, 2, 0);
NSH::lstat (char *filename)
Return information on the file filename. NSH::lstat() works like NSH::stat() with the exception
of when the file is a symbolic link, in which case information about the link is returned rather
than the information about the file the link references. Please see the STAT section below for further information on the stat family of calls.
NSH::mkdir (char *dirname, int mode)
Create the new directory dirname with initial permissions set to mode. If mode is ommitted,
mode is assumed to be 0755.
NSH::chdir ("//hostname");
NSH::mkdir ("foo, 0777);
NSH::mkdir ("//hostname/foo/bar");
NSH::mkfifo (char *filename, int mode)
Create the new FIFO special device called filename with initial permissions set to mode. If
mode is ommitted, mode is assumed to be 0755.
NSH::chdir ("//hostname");
NSH::mkdir ("foo, 0777);
NSH::mkdir ("//hostname/foo/bar");
NSH::mknod (char *filename, int mode, int maj, int min)
NSH::open (char *filename, int flags = O_RDONLY, int mode = 0666)
Open a file for reading and/or writing. If only a single argument is given, then the file is opened
for reading in binary mode. For other read options or to write to a file the remaining arguments
must be set. When creating a file, you can determine its file permissions with the third argument.
If none is given, the mode 0666 is used (read/write for all).
The second argument controls how the file is opened. As previously mentioned, if the second
(and third) argument are not given, then the file is opened for reading. The value of the mode
argument can be a ORed value of the following flags.

Network Shell Perl Module

Property of BladeLogic,
Perl Module Inc.
Strictly confidential and proprietary

NSH::(1)

Open for reading

Open for writing only

Open for reading and writing

Non-blocking I/O

Append. Writes guaranteed at the end of file

16

Synchronized file update option

64

Synchronized data update option

96

Non-blocking I/O (POSIX)

256

Open with file create (uses third argument if given)

512

Open with truncation

1024

Exclusive open

2048

Dont allocate controlling tty (POSIX)

32768

Synchronized file update option.

262144

Open file in text mode (Not usefull for UNIX files)

524288

Open file in binary mode (default)

NSH::(1)

NSH::opendir (char *dirname)


Open the directory dirname for reading, returning a file descriptor which can be used in subsequent calls to NSH::readdir() to determine the contents of the given directory.

$fd = NSH::opendir("//hostname/foo") || die "Cant read directory: $!\n


(filename) = NSH::readdir($fd);
NSH::closedir($fd);
NSH::pclose (int fd)
Close a file descriptor returned by a successfull call to NSH::popen().
NSH::popen (char *cmd, char *mode)
Execute the Network Shell command cmd and returns a file descriptor which allows you to either
read or write to the command depending on the value of mode. If the string mode begins with a
r then subsequent NSH::read() will read the standard output of the command while if mode
begins with a w, subsequent NSH::write() will write data to the standard input of the command.
If mode is ommited, it is assumed to be r.
$fd = NSH::popen ("cd //hostname/foo; ls")
while (NSH::read ($fd, $buf, 100))
{
print $buf;
}
NSH::read (int fd, char *buffer, int nbytes)
Read the next nbytes bytes from the file descriptor fd storing the result in buf which will always
be null terminated.
NSH::readdir (int fd)
Read the next directory entry of the directory pointed to by the descriptor fd returned by a successfull call to NSH::opendir(). This function pushes the filename and the filenames inode number on the stack.
$fd = NSH::opendir ("foo") || die "Cant access foo: $!\n";

Network Shell Perl Module

Property of BladeLogic,
Perl Module Inc.
Strictly confidential and proprietary

NSH::(1)

NSH::(1)

while (($filename, $inode) = NSH::readdir($fd))


{
print "FILENAME = $FILENAME INODE = $inode\n";
}
NSH::closedir($fd);
NSH::readlink (char *filename)
Return the value of a symbolic link.
$linkname = NSH::readlink("foobar");
NSH::rename (char *oldname, char *newname)
Rename the file oldname to newname.
NSH::rename ("foo", "bar") || die "Cant rename: $!\n";
NSH::rewinddir (int fd)
Move the read pointer to the start of the directory.
$fd = NSH::opendir ("foo") || die "Cant read directory: $!\n";
($filename) = NSH::readdir ($fd);
NSH::rewinddir ($fd);
NSH::rmdir (char *dirname)
Remove the empty directory dirname.

NSH::rmdir ("//hostname/foo/bar") || warn "Cant remove directory: $!\n"


NSH::seekdir (int fd, int pos)
Move the read pointer of the directory descriptor fd to pos which must be a value returned by a
previous call to NSH::telldir().
$fd = NSH::opendir ("foo") || die "Cant read directory: $!\n";
($filename) = NSH::readdir ($fd);
$pos = NSH::telldir ($fd);
($filename) = NSH::readdir ($fd);
NSH::seekdir ($fd, $pos);
NSH::setpriority (int which, int who, int prio)
Set the scheduling priority for a process, process group or user. Which is one of
0

who is a process identifier (PRIO_PROCESS)

who is a process group identifier (PRIO_PGRP)

who is a user ID (PRIO_USER)

Finally, prio is the new priority to be set. If NSH::setprio() is only called with two arguments,
then they are assumed to be a process ID and its new priority.
NSH::stat (char *filename)
Return information about the file filename. Please see the STAT section below for further information on the stat family of calls.

Network Shell Perl Module

Property of BladeLogic,
Perl Module Inc.
Strictly confidential and proprietary

NSH::(1)

NSH::(1)

NSH::symlink (char *name, char *newname)


Create the symbolic link newname to the file name. In the Network Shell environment, symbolic links may traverse hosts (name -> //hostname/foo/bar). These types of symbolic links however, will not work outside the Network Shell environment.
NSH::system (char *cmd)
Run the Network Shell command cmd and output its standard output and error. In essence, the
following command is generated and executed.
exec /bin/nsh -D <pwd> -c <cmd>
NSH::telldir (int fd)
Return the current location of the directory descriptor fd. The returned value is only of use to the
NSH::seekdir() function and should not be interpreted to be mean anything specific.
NSH::truncate (char *filename, long pos)
Truncate the file filename to be of size pos bytes.
NSH::truncate ("foobar", 200);
NSH::uname ()
This command pushes on the stack information about the host on which the current working NSH
directory is.

foreach $host ("//host1", "//host2", "//host3")


{
nsh::chdir($host);
($sysname, $nodename, $release, $version, $machine) = NSH:uname (
}
NSH::unlink (char *filename)
Unlink (remove) the file filename.
NSH::utime (char *filename, long mtime, long atime)
Adjust the date of last modification and last access of the file filename to mtime and atime
respectively. If either mtime or atime are not given, then the current date of the local host is
used.
NSH::utime ("//hostanme/foo/bar");
NSH::write (int fd, char *buffer, int nbytes)
Write nbytes of data in buffer to the file pointed to by the file descriptor fd.

STAT
This section gives a more detailed outline the return value of the stat family of calls. All three (lstat, stat,
fstat) of these functions return an array of values representing the various properties of the file in question.
The best way to document this is through an example:
use NSH;
@PROPS = NSH::stat ("//hostname/etc/passwd");
printf
printf
printf
printf
printf

("Device ID of parent dir


("File inode number
("File mode/permissions
("Number of links to file
("File UID

Network Shell Perl Module

=
=
=
=
=

%d\n",
%d\n",
%d\n",
%d\n",
%d\n",

@PROPS
@PROPS
@PROPS
@PROPS
@PROPS

[0]);
[1]);
[2]);
[3]);
[4]);

Property of BladeLogic,
Perl Module Inc.
Strictly confidential and proprietary

NSH::(1)

printf
printf
printf
printf
printf
printf
printf
printf

("File
("Rdev
("File
("Time
("Time
("Time
("Size
("Size

GID
(for special files)
size
of last access
of last modification
of last status change
of a block
of file in blocks

Network Shell Perl Module

=
=
=
=
=
=
=
=

%d\n",
%d\n",
%d\n",
%d\n",
%d\n",
%d\n",
%d\n",
%d\n",

NSH::(1)

@PROPS
@PROPS
@PROPS
@PROPS
@PROPS
@PROPS
@PROPS
@PROPS

[5]);
[6]);
[7]);
[8]);
[9]);
[10]);
[11]);
[12]);

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nshopt(1)

nshopt(1)

NSHOPT
nshopt Test different network write buffer sizes

SYNOPSIS
nshopt [-i size] [-k size] [-s bytes] [-b] host1 ...

DESCRIPTION
Depending on the network, using specific write buffer sizes when communicating with remote hosts can
improve the net throughput of data. The default write buffer size is 4480 bytes, but sometimes this value
may not be optimal.
To determine the optimal write buffer size, nshopt writes a 2MB file to a remote host multiple times, each
time using different network write buffer sizes and determining the time it takes to send the file. This lets
you determine the optimal network write buffer size to use when communicating with the given host.
nshopt starts with a write buffer size of 512 bytes and continues to perform the test in 512 byte increments
up to a maximum buffer size of 16384 bytes (16KB). nshopt prints the results of each test to the standard
output for review. (See EXAMPLE.)
Once nshopt has determined an optimal buffer size, use the secadmin command to configure the new
buffer size.

OPTIONS
-i size

Instead of starting with a write buffer size of 512 and using an increment of 512 bytes, start with
a write buffer size and use an increment size of size.

-k size

Instead of transferring a 2 MB (2048 KB) test file as a sample, use a file size KB large.

-s bytes Start off with a buffer size of bytes. By default nshopt starts with a buffer size equivalent to the
increment size (512 bytes).
-b

When writing data to the remote host, perform a bulk write rather than a regular write. The difference between the two is that with a bulk write there is no checking or return code to verify that
the write actually worked. A regular write does perform those checks and therefore will take a little longer. The cp command performs bulk writes when copying a file to a remote host.

EXAMPLE
The following example tests the host hpux. From the data you can see that a buffer size of 1024 bytes is
optimal for transferring data from the local host to the host hpux. This example then uses the command
secadmin to update the configuration file with the desired buffer size.
# nshopt hpux
Trying
512 bytes
Trying 1024 bytes
Trying 1536 bytes
Trying 2048 bytes
Trying 2560 bytes
Trying 3072 bytes
.
.
# secadmin -W hpux

to
to
to
to
to
to

hpux
hpux
hpux
hpux
hpux
hpux

...
...
...
...
...
...

done.
done.
done.
done.
done.

(52.012 seconds for 2048 KB = 39


(3.020 seconds for 2048 KB = 678
(51.173 seconds for 2048 KB = 40
(51.145 seconds for 2048 KB = 40
(51.147 seconds for 2048 KB = 40

1024

CAVEATS
The nshopt command tests how best to send data to a remote host. It does not test how fast it can receive
data. If you anticipate that you will be receiving large amounts of data, then you should be running this test
from the agent server to the client server (where you will need to install an agent to test it properly).

ORIGIN
nshopt was written by Thomas Kraus.

NSH

KB/sec)
KB/sec)
KB/sec)
KB/sec)
KB/sec)

nshopt(1)

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nshopt(1)

SEE ALSO
secadmin(1), secure(1), cp(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nshpath(1)

nshpath(1)

NAME
nshpath show the path where an nsh executable resides on a local and/or remote machine

SYNOPSIS
nshpath [hostname ...]

DESCRIPTION
The nshpath command displays the path where an nsh executable resides on a local or remote machine.
Execution of this command requires an RSCD Agent up and running on the target machine.

OPTIONS
None

EXAMPLE
To determine the path of nsh installed on a remote machine called host2, a user working on machine
host1 would do the following:
host1% nshpath host2
/usr/nsh/bin/nsh
This tells the user that nsh has been installed and that the nsh executable resides at /usr/nsh/bin on the
host2 machine.

ORIGIN
nshpath was developed by BladeLogic, Inc.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nstats(1)

nstats(1)

NAME
nstats View system statistics from one or more hosts

SYNOPSIS
nstats [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]

DESCRIPTION
nstats displays some system statistics in a standardized format independent of the servers operating system. nstats displays data in the following columns:
HOSTNAME
The name of the host the entry applies to.
LOAD

The systems current load average. For UNIX, see uptime (1). For Windows, it shows a CPU
usage percentage.

MEMORY
The percentage of total memory currently being used.
SWAP

The percentage of total swap space currently being used.

PROCS The total number of processes currently running.


TIME

The current time on the system.

UPTIME
The amount of time the system has been running.

OPTIONS
-c

Output system statistics as a set of comma separated values. This option overrides the -t option.

-e expr

Show only entries that match the given expression. See the EXPRESSIONS section below for
more details.

-f file

Load the list of servers from which to get system statistics. The file should be a flat file containing either resolvable hostnames or valid I.P. addresses. See the -f option below.

-H

Do not show a header on output.

-h hosts Specify the list of hosts from which to get the system statistics. The values must be resolvable
hostnames or valid I.P. addresses. You can specify multiple space separated hostnames without
re-specifying the -h option.
-r

Sort in reverse order. See the -s option below.

-s field

By default, nstats sorts in reverse order (largest to smallest) on the current load average. With
the -s option you can specify an alternate field to sort on. The field must be one of the column
headers listed above.

-t

Display data similar to the way the top command displays data. With this option, the data display
is truncated by screen size and repeated periodically. The following keyboard commands are
available while in top mode.
<SPACE>

Refresh the data.

Ctrl-L

Refresh screen.

Ctrl-C

Quit application.

Quit application.

Reverse sort order.

Increase wait time between refreshes by 1 second.

Decrease wait time between refreshes by 1 second.

Sort on the specified column. Replace the # character with 1,2,3,4,5,6, or


7.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nstats(1)

-w

nstats(1)

Define an expression used to filter the output data. See the EXPRESSIONS section below for more details.

Switch to disk info view.

Switch to memory info view.

Switch to network info view.

Switch to system info view.

Switch to process info view.

Switch to statistics view.

Switch to process summary view.

Truncate each line of output to the actual screen width.

EXAMPLE
These examples show how to get an overview of key system statistics.
host% nstats -h solaris8 linux windows
HOSTNAME
LOAD MEMORY SWAP PROCS TIME
windows
0.03
68%
1%
43 16:13
linuxdev
0.00
98%
0%
39 16:12
solaris8dev
0.00
87%
20%
63 16:14

UPTIME
6 days 05:12:48
56 days 04:43:39
88 days 15:04:57

host% nstats -h solaris8 linux windows -e LOAD > 0


windows
0.03
68%
1%
43 16:13
6 days 05:13:52

EXPRESSIONS
You can use the -e option to define an expression that filters the output data. The expression should be a
single argument surrounded by single quotes. When an expression is used to match a string, wildcards are
supported. Expressions can contain multiple operators and operands, including NOT, AND, and OR. For
full details on expressions, see the man page for blexpr.

CAVEATS
The -t option mimics the top commands behavior, but does not mimic it exactly.

ORIGIN
nstats was written by Thomas Kraus

SEE ALSO
uptime(1), blexpr(1), nmem(1), ndf(1), nnet(1), nps(1), nover(1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ntop(1)

ntop(1)

NAME
ndf, nmem, nover, nps, nstats A collection of commands used to view information and statistics for one or
more servers

SYNOPSIS
ndf [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]
nmem [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]
nover [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]
nps [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]
nstats [-c] [-e expr] [-f file] [-H] [-h host ...] [-r] [-s field] [-t]

DESCRIPTION
Ntop is a family of commands that can be used to view information and statistics about one or more servers.
For more information, please read the individual man page for each command.

SEE ALSO
blexpr(1), blquery(1), nmem(1), nps(1), nover(1), nstats(1), ndf(1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nukecert(1)

nukecert(1)

NAME
nukecert remove certificates from servers

SYNOPSIS
nukecert user_name server1 [<server2> <server2>]

DESCRIPTION
The nukecert command removes user certificates from servers that you specify.

OPTIONS
user_name
The user for whom certificates should be removed.
server1 [<server2> <server2>]
A space-delimited list of the names or IP addresses of the servers from which certificates should
be removed.

EXAMPLE
nukecert johnk linuxBuild solarisQA

ORIGIN
nukecert was developed by BladeLogic, Inc.

SEE ALSO
putcert(NSH)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

nunzip1(NSH)

nunzip1(NSH)

NAME
nunzip, gunzip, gzcat, gzip decompress or compress files

SYNOPSIS
nunzip [-cv] [--no-name] [--quiet] [--verbose] file

DESCRIPTION
The nunzip command takes a list of files and decompresses or compresses each file whose name ends with
.gz, .GZ, .TGZ, or .tgz, provided that the file has the correct header. The resulting file is an uncompressed
(or compressed) file without the original extension. For example, when config.tar.gz is uncompressed, the name of the resulting uncompressed file is config.tar.

OPTIONS
-c

Uncompress to stdout.

-v

Verbose output. Display the name and percentage reduction for each file compressed or decompressed.

--no-name
When decompressing, do not restore the original file name if one is present (remove only the gzip
suffix from the compressed file name) and do not restore the original time stamp if one is present.
Instead, copy the time stamp from the compressed file. This option is the default when decompressing.
--quiet

Suppress all warnings.

--verbose
Same as -v.
--help

Display a help screen and quit.

file

File or files to be compressed or decompressed.

EXAMPLES
gzip -c file1 > foo.gz
gzip -c file2 >> foo.gz
nunzip foo.gz
nunzip --verbose foo.gz

ORIGIN
nunzip was developed by BladeLogic, Inc.

Property of BladeLogic, Inc.


Strictly confidential and proprietary

order(1)

order(1)

NAME
order sort a list of strings (or lines) in a specified order

SYNOPSIS
order s|r [-u] [order-style]

DESCRIPTION
The order command is used to sort a list of strings (or lines) in an order specified by the user. Sorting is
alphabetical.
Each entry in the list of strings that are input must have the following syntax:
(<tag>) <character string or line>.
In the syntax shown above, the tag field is optional. If you provide a tag field, it must be enclosed within
round brackets ().
If tag fields are provided in the input list, the resulting list contains strings grouped by the tag fields. Within
each tag group, the strings are sorted in a user-specified order. The tag groups themselves are always sorted
in ascending alphabetical order.

OPTIONS
-s

Sort the list in ascending order.

-r

Sort the list in descending order. Note: if both the -s and -r options are specified, only the -s
option is considered.

-u

Remove duplicate entries. The resulting list contains only unique entries.

If you do not provide a sorting option, the string order is not changed. The strings are only grouped by tag.

ORDER STYLE
-1

If specified, the resulting list is printed in the format


<tag> <character string>

-2

If specified, the resulting list is printed in the format


<tag>: <character string>

-3

If specified, the resulting list is printed in the format


(<tag>) <character string>

If no order style option is specified, the resulting list is printed in the format
(<tag>) <character string>

EXAMPLES
In this example, input lines are contained in a file called list.txt.
$cat list.txt
(city) bangalore
(country) australia
(city) new york
asia
(country) united states
(city) adelaide
(city) new york

NSH

order(1)

Property of BladeLogic, Inc.


Strictly confidential and proprietary

order(1)

america
(country) india
(country) australia
(country) england
europe
(city) new york
(city) Rome
(country) australia
(country) germany
If no sorting option is provided:
$order < list.txt
asia
america
europe
(city) bangalore
(city) new york
(city) adelaide
(city) new york
(city) new york
(city) Rome
(country) australia
(country) united states
(country) india
(country) australia
(country) england
(country) australia
(country) germany
If ascending order is specified:
$order -s < list.txt
america
asia
europe
(city) Rome
(city) adelaide
(city) bangalore
(city) new york
(city) new york
(city) new york
(country) australia
(country) australia
(country) australia
(country) england
(country) germany
(country) india
(country) united states
If descending order is specified with the -u (unique) option and the order style specified as -2:
$order -r -u -2 < list.txt
europe

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

order(1)

order(1)

asia
america
city:new york
city:bangalore
city:adelaide
city:Rome
country:united states
country:india
country:germany
country:england
country:australia

ORIGIN
order was developed by BladeLogic, Inc.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

paste ( 1 )

NAME

paste - merge corresponding or subsequent lines of files


SYNOPSIS

paste [-s] [-d list] file ...


DESCRIPTION

The Paste utility concatenates the corresponding lines of the given input files, replacing all but the last files
newline characters with a single tab character, and writes the resulting lines to standard output. If end-offile is reached on an input file while other input files still contain data, the file is treated as if it were an endless source of empty lines.
The options are as follows:
-d list

Use one or more of the provided characters to replace the newline characters instead of the
default tab. The characters in list are used circularly, i.e., when list is exhausted the first character
from list is reused. This continues until a line from the last input file (in default operation) or the
last line in each file (using the -s option) is displayed, at which time paste begins selecting characters from the beginning of list again.

The following special characters can also be used in list:


\n
\t
\
\0

newline character
tab character
backslash character
Empty string (not a null character).

Any other character preceded by a backslash is equivalent to the character itself.


-s

Concatenate all of the lines of each separate input file in command line order. The newline character of every line except the last line in each input file is replaced with the tab character, unless
otherwise specified by the -d option.

If - is specified for one or more of the input files, the standard input is used; standard input is read one line
at a time, circularly, for each instance of -.
The paste utility exits 0 on success, and >0 if an error occurs.
ORIGIN

Paste includes software developed by the University of California, Berkeley and its contributors. Please see
the intro section for complete acknowledgements.
SEE ALSO

cut(1)

SunOS 5.8

Last change: NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

pax(1)

pax(1)

NAME
pax,tar - read and write file archives and copy directory hierarchies

SYNOPSIS
tar -[bcefmprutvwxBLPX[0-9]] [option arguments] [files ...]
pax [-cdnv] [-f archive] [-s replstr] ... [-U user] ... [-G group] ... [-T [from_date] [,to_date]] ... [pattern ...]
pax -r [-cdiknuvDYZ] [-f archive] [-o options] ... [-p string] ... [-s replstr] ... [-E limit] [-U user] ... [-G
group] ... [-T [from_date] [,to_date]] ... [pattern ...]
pax -w [-dituvHLPX] [-b blocksize] [[-a] [-f archive]] [-x format] [-s replstr] ... [-o options] ... [-U user] ...
[-G group] ... [-B bytes] [-T [from_date] [,to_date] [/[c][m]]] ... [file ...]
pax -r -w [-diklntuvDHLPXYZ] [-p string] ... [-s replstr] ... [-U user] ... [-G group] ... [-T [from_date]
[,to_date] [/[c][m]]] ... [file ...] directory

DESCRIPTION
pax will read, write, and list the members of an archive file, and will copy directory hierarchies. pax operation is independent of the specific archive format, and supports a wide variety of different archive formats.
For a list of supported archive formats, see the -x option.
pax also supports a tar interface if the basename of argv[0] is tar. For a description of tar options, see the
section below.
The presence of the -r and the -w options specifies which of the following functional modes pax will operate under: list, read, write, and copy.
<none> List. pax will read an archive file from standard input, and write a table of contents to standard
output. The table of contents will contain the members of the archive file whose pathnames match
the specified patterns. The table of contents contains one filename per line and is written using
single line buffering.
-r

Read. pax will read an archive file from standard input, and extract the archive file members
whose pathnames match the specified patterns. The archive format and blocking is automatically
determined on input. When an extracted file is a directory, pax extracts the entire file hierarchy
rooted at that directory. All extracted files are created relative to the current file hierarchy. The
setting of ownership, access and modification times, and file mode of the extracted files are discussed in more detail under the -p option.

-w

Write. pax writes an archive containing the file operands to standard output using the specified
archive format. If you do not specify any file operands, pax reads a list of files to copy with one
per line from standard input. When a file operand is also a directory, the entire file hierarchy
rooted at that directory will be included.

-r -w

Copy. pax copies the file operands to the destination directory. If you do not specify any file
operands, pax reads a list of files to copy with one per line from the standard input. When a file
operand is also a directory the entire file hierarchy rooted at that directory will be included. The
effect of the copy is as if the copied files were written to an archive file and then subsequently
extracted, except that there may be hard links between the original and the copied files (see the -l
option below).
Warning: The destination directory must not be one of the file operands or a member of a file
hierarchy rooted at one of the file operands. The result of a copy under these conditions is unpredictable.

While processing a damaged archive during a read or list operation, pax will attempt to recover from media
defects and will search through the archive to locate and process the largest number of archive members
possible (see the -E option for more details on error handling).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

pax(1)

pax(1)

OPERANDS
There are three types of operands: directory operands, pattern operands, and file operands.
The directory operand specifies a destination directory pathname. If the directory operand does not exist, or
if it is not writable by the user, or if it is not of type directory, pax will exit with a non-zero exit status.
The pattern operand is used to select one or more pathnames of archive members. pax selects archive
members using the pattern matching notation described by fnmatch(3). If you do not supply a pattern
operand, pax selects all members of the archive. When a pattern matches a directory, pax selects the entire
file hierarchy rooted at that directory. When a pattern operand does not select at least one archive member,
pax will write these pattern operands in a diagnostic message to standard error and then exit with a nonzero exit status.
The file operand specifies the pathname of a file to be copied or archived. When a file operand does not
select at least one archive member, pax will write these file operand pathnames in a diagnostic message to
standard error and then exit with a non-zero exit status.

OPTIONS
-r

Read an archive file from standard input and extract the specified files. If any intermediate directories are needed in order to extract an archive member, these directories will be created as if
mkdir(2) was called with the bitwise inclusive OR of S_IRWXU, S_IRWXG, and S_IRWXO as
the mode argument. When the selected archive format supports the specification of linked files
and these files cannot be linked while the archive is being extracted, pax will write a diagnostic
message to standard error and exit with a non-zero exit status at the completion of operation.

-w

Write files to the standard output in the specified archive format. If you do not specify any file
operands, pax reads standard input for a list of pathnames with one per line without any leading
or trailing <blanks>.

-a

Append files to the end of a previously written archive. If you do not specify an archive format -x
option, pax uses the archives existing format. If you try to append to an archive, using a format
different from the archives existing format, pax exits immediately with a non-zero exit status.
pax will observe the blocking size being used in the archive volume where the writing starts, and
will continue to use that blocking size for the remainder of the archive volume.
Warning: Many storage devices are not able to support the operations necessary to perform an
append operation. Any attempt to append to an archive stored on such a device may damage the
archive or have other unpredictable results. Tape drives in particular are more likely to not support an append operation. An archive stored in a regular file system file or on a disk device will
usually support an append operation.

-b blocksize
Tells pax the size of the output block (bytes per write) it should use when writing an archive.
blocksize must be a positive decimal integer that is a multiple of 512 bytes. Its maximum is
32256 bytes. A blocksize can end with k or b to specify multiplication by 1024 (1K) or 512,
respectively. You can separate a pair of blocksizes by x to indicate a product. A specific archive
device may impose additional restrictions on the size of blocking it will support. If you do not
specify a block size, the default block size depends on the specific archive format being used (see
the -x option).
-c

Match all file or archive members except those specified by the pattern and file operands.

-d

Cause files of type directory being copied or archived, or archive members of type directory being
extracted, to match only the directory file or archive member and not the file hierarchy rooted at
the directory.

-f archive
Specify archive as the pathname of the input or output archive, overriding the default standard
input (for list and read) or standard output (for write). A single archive may span multiple files
and different archive devices. When required, pax will prompt for the pathname of the file or

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

pax(1)

pax(1)

device of the next volume in the archive.


-i

Interactively rename files or archive members. For each archive member matching a pattern
operand or each file matching a file operand, pax will prompt to /dev/tty giving the name of the
file, its file mode and, its modification time. pax will then read a line from /dev/tty. If this line is
blank, pax skips the file or archive member. If this line consists of a single period, pax processes
the file or archive member with no modification to its name. Otherwise, pax replaces its name
with the contents of the line. pax will immediately exit with a non-zero exit status if <EOF> is
encountered when reading a response or if /dev/tty cannot be opened for reading and writing.

-k

Do not overwrite existing files.

-l

Link files. (This option is the letter ell). In the copy mode ( -r -w), pax makes hard links between
the source and destination file hierarchies whenever possible.

-n

Select the first archive member that matches each pattern operand. Match no more than one
archive member for each pattern. When pax matches members of type directory, it also matches
the file hierarchy rooted at that directory (unless -d is also specified).

-o options
Information to modify the algorithm for extracting or writing archive files. These options are specific to the archive format specified by -x. In general, options take the form:
name=value
-p string Specify one or more file characteristic options (privileges). The string option-argument is a string
specifying file characteristics to be retained or discarded on extraction. The string consists of the
specification characters a, e, m, o, and p (described below). You can concatenate multiple characteristics within the same string, and you can specify multiple -p options. The meanings of the
specification characters are:
a

Do not preserve file access times. By default, pax preserves file access times whenever
possible.

Preserve everything -- the user ID, group ID, file mode bits, file access time, and file
modification time. This is intended to be used by root, someone with all the appropriate
privileges, in order to preserve all aspects of the files as they are recorded in the
archive. The e flag is the sum of the o and p flags.

Do not preserve file modification times. By default, pax preserves file modification
times whenever possible.

Preserve the user ID and group ID.

Preserve the file mode bits. This intended to be used by a user with regular privileges
who wants to preserve all aspects of the file other than the ownership. The file times are
preserved by default, but two other flags are offered to disable this and use the time of
extraction instead.

In the preceding list, preserve indicates that an attribute stored in the archive is given to the
extracted file, subject to the permissions of the invoking process. Otherwise the attribute of the
extracted file is determined as part of the normal file creation action. If neither the e nor the o
specification character is specified, or the user ID and group ID are not preserved for any reason,
pax will not set the S_ISUID (setuid) and S_ISGID (setgid) bits of the file mode. If the preservation of any of these items fails for any reason, pax will write a diagnostic message to standard
error. Failure to preserve these items will affect the final exit status, but will not cause the
extracted file to be deleted. If the file characteristic letters in any of the string option-arguments
are duplicated or conflict with each other, the one(s) given last will take precedence. For example,
if -p eme is specified, file modification times are still preserved.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

pax(1)

pax(1)

-s replstr
Modify the file or archive member names specified by the pattern or file operands according to
the substitution expression replstr, using the syntax of the ed(1) utility regular expressions. The
format of these regular expressions is: /old/new/[gp] As in ed(1), old is a basic regular expression
and new can contain an ampersand (&), \n (where n is a digit) back-references, or subexpression
matching. The old string may also contain <newline> characters. Any non-null character can be
used as a delimiter (/ is shown here).
You can specify multiple -s expressions. pax applies the expressions in the order you specify them on the
command line, terminating with the first successful substitution. The optional trailing g continues to apply
the substitution expression to the pathname substring which starts with the first character following the end
of the last successful substitution. The first unsuccessful substitution stops the operation of the g option.
The optional trailing p will cause the final result of a successful substitution to be written to standard error
in the following format:
<original pathname> >> <new pathname>
File or archive member names that substitute to the empty string are not selected and will be
skipped.
-t

Reset the access times of any file or directory that pax read or accessed to be the same as they
were before pax. read or accessed them.

-u

Ignore files that are older (having a less recent file modification time) than a pre-existing file or
archive member with the same name. During read, an archive member with the same name as a
file in the file system will be extracted if the archive member is newer than the file. During write,
a file system member with the same name as an archive member will be written to the archive if it
is newer than the archive member. During copy, the file in the destination hierarchy is replaced by
the file in the source hierarchy or by a link to the file in the source hierarchy if the file in the
source hierarchy is newer.

-v

During a list operation, produce a verbose table of contents using the format of the ls(1) utility
with the -l option. For pathnames representing a hard link to a previous member of the archive,
the output has the format:
<ls -l listing> == <link name>
For pathnames representing a symbolic link, the output has the format:
<ls -l listing> => <link name>
Where <ls -l listing> is the output format specified by the ls(1) utility when used with the -l
option. Otherwise, for all the other operational modes ( read, write, and copy), pax writes pathnames and flushes them to standard error without a trailing <newline> as soon as processing
begins on that file or archive member. The trailing <newline>, is not buffered, and is written only
after the file has been read or written.

-x format
Specify the output archive format, with the default format being ustar. pax currently supports the
following formats:
cpio

The extended cpio interchange format specified in the IEEE Std1003.2 (POSIX)
standard. The default blocksize for this format is 5120 bytes. If this format truncates
inode and device information about a file (used for detecting file hard links), pax
detects the truncation and repairs it.

bcpio

The old binary cpio format. The default blocksize for this format is 5120 bytes. This
format is not very portable. Therefore, do not use this format if other formats are

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

pax(1)

pax(1)

available. If this format truncates inode and device information about a file (used for
detecting file hard links), pax detects the truncation and repairs it.
sv4cpio

The System V release 4 cpio. The default blocksize for this format is 5120 bytes. If
this format truncates inode and device information about a file (used for detecting file
hard links), pax detects the truncation and repairs it.

sv4crc

The System V release 4 cpio with file crc checksums. The default blocksize for this
format is 5120 bytes. If this format truncates inode and device information about a
file (used for detecting file hard links), pax detects the truncation and repairs it.

tar

The old BSD tar format as found in BSD4.3. The default blocksize for this format is
10240 bytes. Pathnames stored by this format must be 100 characters or less in
length. Only regular files, hard links, soft links, and directories will be archived
(other file system types are not supported). For backwards compatibility with even
older tar formats, a -o option can be used when writing an archive to omit the storage
of directories. This option takes the form:
-o write_opt=nodir

ustar

The extended tar interchange format specified in the IEEE Std1003.2 (POSIX)
standard. The default blocksize for this format is 10240 bytes. Pathnames stored by
this format must be 250 characters or less in length.

pax will detect and report any file that it is unable to store or extract as the result of any specific
archive format restrictions. The individual archive formats may impose additional restrictions on
use. Typical archive format restrictions include (but are not limited to): file pathname length, file
size, link pathname length and the type of the file.
-B bytes Limit the number of bytes written to a single archive volume to the value you specify here. The
bytes limit can end with m, k, or b to specify multiplication by 1048576 (1M), 1024 (1K) or 512,
respectively. A pair of bytes limits can be separated by x to indicate a product.
Warning: Use this option only when writing an archive to a device that supports an end of file
read condition based on last (or largest) write offset (such as a regular file or a tape drive). We do
not recommend using this option with a floppy or hard disk.
-D

This option is the same as the -u option, except that pax checks the file inode change time instead
of the file modification time. The file inode change time can be used to select files whose inode
information (for example, uid, gid, etc.) is newer than a copy of the file in the destination directory.

-E limit Limit the number of consecutive read faults while trying to read a flawed archive to the number
specified here. With a positive limit, pax will attempt to recover from an archive read error and
will continue processing starting with the next file stored in the archive. A limit of 0 will cause
pax to stop operation after it detects the first read error on an archive volume. A limit of NONE
will cause pax to attempt to recover from read errors forever. The default limit is a small positive
number of retries.
Warning: Use NONE with extreme caution, because pax may get stuck in an infinite loop on a
very badly flawed archive.
-G group
Select a file based on its group name, or when starting with a #, a numeric gid. You can use a to
escape the #. You can supply multiple -G options. Checking stops with the first match.
-H

Follow only command line symbolic links while performing a physical file system traversal.

-L

Follow all symbolic links to perform a logical file system traversal.

-P

Do not follow symbolic links. Instead, perform a physical file system traversal. This is the default
mode.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

pax(1)

pax(1)

-T [from_date][,to_date][/[c][m]]
Allow files to be selected based on a file modification or inode change time falling within a specified time range of from_date to to_date (the dates are inclusive). If you supply only a from_date,
pax selects all files with a modification or inode change time equal to or younger than the fromdate. If you supply only a to_date, pax selects all files with a modification or inode change time
equal to or older than the to-date. When the from_date is equal to the to_date, pax selects only
files with a modification or inode change time of exactly that time.
When pax is in the write or copy mode, you can use the optional trailing field [c][m] to specify
which file time (inode change, file modification or both) pax should use in the comparison. If you
specify neither, pax defaults to using the file modification time only. The m tells pax to compare
the file modification time (the time when the file was last written). The c tells pax to compare the
inode change time (the time when the file inode was last changed; for example, the last time there
was a change of owner, group, mode, etc). If you specify both c and m, then pax compares both
the modification time and the inode change time. The inode change time comparison is useful in
selecting files whose attributes were recently changed, or selecting files that were recently created
and had their modification time reset to an older time (as happens when a file is extracted from an
archive and the modification time is preserved). Time comparisons using both file times are useful when you are using pax to create a time based incremental archive (only files that were
changed during a specified time range will be archived).
A time range is made up of six different fields. Each field must contain two digits. The format is:
[yy[mm[dd[hh]]]]mm[.ss] Where yy is the last two digits of the year, the first mm is the month
(from 01 to 12), dd is the day of the month (from 01 to 31), hh is the hour of the day (from 00 to
23), the second mm is the minute (from 00 to 59), and ss is the seconds (from 00 to 59). The
minute field mm is required, while the other fields are optional and must be added in the following order: hh, dd, mm, yy. The ss field may be added independently of the other fields. Time
ranges are relative to the current time, so -T 1234/cm would select all files with a modification or
inode change time of 12:34 PM today or later. You can supply multiple -T time ranges. Checking
stops with the first match.
-U user

Select a file based on its user name, or when starting with a #, a numeric uid. A can be used to
escape the #. You can supply multiple -U options. Checking stops with the first match.

-X

When traversing the file hierarchy specified by a pathname, do not descend into directories that
have a different device ID. See the st_dev field as described in stat(2) for more information about
device IDs.

-Y

This option is the same as the -D option, except that pax checks the inode change time using the
pathname created after all the file name modifications have completed.

-Z

This option is the same as the -u option, except that pax checks the modification time using the
pathname created after all the file name modifications have completed.

The options that operate on the names of files or archive members ( -c, -i, -n, -s, -u, -v, -D, -G, -T, -U, -Y,
and -Z) interact as follows.
When extracting files during a read operation, archive members are selected based only on the user specified pattern operands as modified by the -c, -n, -u, -D, -G, -T, -U options. Then any -s and -i options will
modify in that order, the names of these selected files. Then the -Y and -Z options will be applied based on
the final pathname. Finally the -v option will write the names resulting from these modifications.
When archiving files during a write operation, or copying files during a copy operation, archive members
are selected based only on the user specified pathnames as modified by the -n, -u, -D, -G, -T, and -U
options (the -D option applies only during a copy operation). Then any -s and -i
options will modify in that order, the names of these selected files. Then during a copy operation the -Y
and the -Z options will be applied based on the final pathname. Finally the -v option will write the names

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

pax(1)

pax(1)

resulting from these modifications.


If you specify one or both of the -u or -D options, along with the -n option, pax does not select a file unless
it is newer than the file to which it is compared.

TAR OPTIONS
The pax utility supports a tar interface if the basename of argv[0] is tar. In this case the following options
are supported.
b

The respective argument is the desired blocksize to use.

Create an archive.

Stop after first error.

The respective argument is the name of the archive to create/view/update.

Do not preserve modification time.

Preserve user ID, group ID, file mode, access/modification times.

Append to the archive.

Append to the archive.

List contents of the tape.

Verbose operation mode.

Interactive file rename.

Extract data from archive.

Follow command line symlinks only.

Follow symlinks.

Do not follow symlinks.

Do not pass over mount points in the file system.

[14578] Use tape device /dev/rmt/ N

EXAMPLES
The command:
pax -w -f /dev/rst0 .
copies the contents of the current directory to the device /dev/rst0.
The command:
pax -r -v -f filename
gives the verbose table of contents for an archive stored in filename.
The following commands:
mkdir newdir
cd olddir
pax -rw . newdir
will copy the entire olddir directory hierarchy to newdir.
The command:
pax -r -s ,//*usr//*,, -f a.pax
reads the archive a.pax, with all files rooted in /usr into the archive extracted relative to the current directory.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

pax(1)

pax(1)

The command:
pax -rw -i . dest_dir
can be used to interactively select the files to copy from the current directory to dest_dir.
The command:
pax -r -pe -U root -G bin -f a.pax
will extract all files from the archive a.pax that are owned by root with group bin and will preserve all file
permissions.
The command:
pax -r -w -v -Y -Z home /backup
will update (and list) only those files in the destination directory /backup that are older (less recent inode
change or file modification times) than files with the same name found in the source file tree home.

STANDARDS
The pax utility is a superset of the IEEE Std1003.2 (POSIX) standard. The options -B, -D, -E, -G, -H,
-L, -P, -T, -U, -Y, -Z, the archive formats bcpio, sv4cpio, sv4crc, tar, and the flawed archive handling during
list and read operations are extensions to the POSIX standard.

ORIGIN
pax includes software developed by the University of California, Berkeley and its contributors.

ERRORS
pax will exit with one of the following values:
0 All files were processed successfully.
1 An error occurred.
Whenever pax cannot create a file or a link when reading an archive or cannot find a file when writing an
archive, or cannot preserve the user ID, group ID, or file mode when the -p option is specified, pax writes a
diagnostic message to standard error and returns a non-zero exit status, but continues processing. In the
case where pax cannot create a link to a file, pax will not create a second copy of the file.
If the extraction of a file from an archive is prematurely terminated by a signal or error, pax may have only
partially extracted a file the user wanted. Additionally, the file modes of extracted files and directories may
have incorrect file bits, and the modification and access times may be wrong.
If the creation of an archive is prematurely terminated by a signal or error, pax may have only partially created the archive which may violate the specific archive format specification.
If, while doing a copy, pax detects a file is about to overwrite itself, pax does not copy the file. pax writes
a diagnostic message to standard error and when pax completes, it exits with a non-zero exit status.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

pkgadd(1)

pkgadd(1)

NAME
pkgadd Network Shell wrapper to pkgadd command

SYNOPSIS
pkgadd [-h host1 [hostn]] [-T tmpdir] <pkgadd arguments>

DESCRIPTION
The Network Shell version of pkgadd is a distributed utility wrapped around the Solaris pkgadd utility.
This utility lets you install Solaris packages onto any number of remote (or local) hosts. The packages you
install, as well as any optional response or admin files, can reside on any server, including remote servers.
The pkgadd wrapper utility works by automatically determining which files (package, admin, and/or
response) need to be copied to each target host, copying the necessary files to those target hosts, and executing the Solaris pkgadd command with the selected arguments on the target hosts.
pkgadd supports both individual files as well as directories. When you use the -d option to install a directory of packages in file system format (not a single file datastream), the pkgadd command will emulate the
standard pkgadd command. It will first determine which packages you want to install, and then will selectively copy those packages (directories) to each target host. For example, rather than copying a complete
CDROM to a remote host in order to install a single package, pkgadd will selectively copy just the package
needed for the installation.

OPTIONS
The pkgadd wrapper understands all the standard pkgadd command options as well as the options below.
-h host

The resolvable hostname or I.P. address of the host on which you want to install the package.
You can specify multiple hostname/I.P. address arguments. If you do not use this option, pkgadd
installs the package the host from which you executed the package command.

-T tmpdir
Defines an alternative directory for the default staging directory /tmp. Because the pkgadd utility acts as a wrapper utility that eventually executes the pkgadd command on the target Solaris
server, it needs a staging area to hold all files required for the installation.
<pkgadd arguments>
See the man section for the pkgadd (1M) command to see what options the pkgadd command
supports.

EXAMPLES
The pkgadd wrapper is designed for use from within the Network Shell (nsh). The following examples are
meant to work from within the Network Shell environment and may not necessarily work on any Solaris
standard shell, such as /bin/sh, /bin/ksh, etc.
Install a package on the local system where the package file also exists on the local system.
solaris # pkgadd -d SUNWppm
Install a package on the local system where the package file exists on the remote host athens.
solaris # pkgadd -d //athens/tmp/bc-1.06-sol8-sparc-local
Install a package on a remote host where the package file exists on the local host.
solaris # pkgadd -h rome -d SUNppm
The previous example could have also been done from the Network Shell as follows:
solaris # cd //rome/tmp
rome # pkgadd -d //@/cdrom/cdrom0/s0/Solaris_8/Product/SUNWppm

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

pkgadd(1)

pkgadd(1)

Install a package on a remote host where the package file exists on that same remote host.
solaris # cd //budapest/tmp
budapest # pkgadd -d apache-1.3.12-sol8-sparc-local.gz
Install a package on two remote hosts where the package file exists on the local host.
solaris # pkgadd -h rome paris -d SUNWppm
Install a package on a remote host where the package file (directory) exists on a different remote server.
solaris # pkgadd -h london -d //athens/cdrom/cdrom0/s0/Solaris_8/Product

DIAGNOSTICS
pkgadd has several of its own self-explanatory diagnostic messages. It also outputs all messages from the
execution of the remote pkgadd command.

EXIT CODES
pkgadd exits with a zero value if all package adds work successfully. If a remote pkgadd commands fails,
it returns an exit code of 6. General errors return an exit code of 1.

CAVEATS
When installing a remote package to a series of hosts where the remote package is being copied from a
(slower) WAN to hosts on a (faster) LAN, there is no option to tell the pkgadd command to copy the
remote package into the LAN environment first and then copy the package to each of the remote hosts.
Instead, pkgadd copies the package from the WAN to the LAN for each host.
You can install packages only on Solaris hosts, as reported by the uname system call (looking for
"SunOS").

ORIGIN
The pkgadd wrapper utility was written by Thomas Kraus.

SEE ALSO
pkgadd(1M), nsh(NSH).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

pr ( 1 )

NAME

pr - print files
SYNOPSIS

pr [+page] [-column] [-adFmrt] [[-e] [char] [gap]] [-h header] [[-i] [char] [gap]] [-l lines] [-o offset] [[-s]
[char]] [[-n] [char] [width]] [-w width] [-] [file ...]
DESCRIPTION

The pr utility is a printing and pagination filter for text files. When multiple input files are specified, each is
read, formatted, and written to standard output. By default, the input is separated into 66-line pages, each
with
A 5-line header with the page number, date, time, and the pathname of the file.
A 5-line trailer consisting of blank lines.
If standard output is associated with a terminal, diagnostic messages are suppressed until the pr utility has
completed processing.
When multiple column output is specified, text columns are of equal width. By default text columns are
separated by at least one <blank>. Input lines that do not fit into a text column are truncated. Lines are not
truncated under single column output.
OPTIONS

In the following option descriptions, column, lines, offset, page, and width are positive decimal integers and
gap is a nonnegative decimal integer.
+page

Begin output at page number page of the formatted input.

-column Produce output that is columns wide (default is 1) that is written vertically down each column in
the order in which the text is received from the input file. The options -e and -i are assumed.
This option should not be used with -m. When used with -t , the minimum number of lines is
used to display the output.
-a

Modify the effect of the -column option so that the columns are filled across the page in a roundrobin order (e.g., when column is 2, the first input line heads column 1, the second heads column
2, the third is the second line in column 1, etc.). This option requires the use of the -column
option.

-d

Produce output that is double spaced. An extra <newline> character is output following every
<newline> found in the input.

-e [char][gap]
Expand each input <tab> to the next greater column position specified by the formula ngap+1,
where n is an integer > 0. If gap is zero or is omitted the default is 8. All <tab> characters in the
input are expanded into the appropriate number of <space>s. If any nondigit character, char, is
specified, it is used as the input tab character.
-F

Use a <form-feed> character for new pages, instead of the default behavior that uses a sequence
of <newline> characters.

-h header
header Use the string header to replace the file name in the header line.
-i [char][gap]
In output, replace multiple <space>s with <tab>s whenever two or more adjacent <space>s reach
column positions gap+1, 2gap+1, etc. If gap is zero or omitted, default <tab> settings at every
eighth column position is used. If any nondigit character, char, is specified, it is used as the output <tab> character.
-l lines

SunOS 5.8

Override the 66 line default and reset the page length to lines. If lines is not greater than the sum
of both the header and trailer depths (in lines), the pr utility suppresses output of both the header
and trailer, as if the -t option were in effect.

Last change: NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

-m

pr ( 1 )

Merge the contents of multiple files. One line from each file specified by a file operand is written
side by side into text columns of equal fixed widths, in terms of the number of column positions.
The number of text columns depends on the number of file operands successfully opened. The
maximum number of files merged depends on page width and the per process open file limit. The
options -e and -i are assumed.

-n [char][width]
Provide width digit line numbering. The default for width, if not specified, is 5. The number
occupies the first width column positions of each text column or each line of -m output. If char
(any nondigit character) is given, it is appended to the line number to separate it from whatever
follows. The default for char is a <tab>. Line numbers longer than width columns are truncated.
-o offset Each line of output is preceded by offset <spaces>s. If the option is not specified, the default is
zero. The space taken is in addition to the output line width.
-r

Write no diagnostic reports on failure to open a file.

-s char

Separate text columns by the single character char instead of by the appropriate number of
<space>s (default for char is the <tab> character).

-t

Print neither the five-line identifying header nor the five-line trailer usually supplied for each
page. Quit printing after the last line of each file without spacing to the end of the page.

-w width Set the width of the line to width column positions for multiple text-column output only. If the -w
option is not specified and the -s option is not specified, the default width is 72. If the -w option is
not specified and the -s option is specified, the default width is 512.
file

A pathname of a file to be printed. If no file operands are specified, or if a file operand is -, the
standard input is used. The standard input is used only if no file operands are specified, or if a file
operand is -.

The -s option does not allow the option letter to be separated from its argument, and the options -e, -i , and
-n require that both arguments, if present, not be separated from the option letter.
ERRORS

If pr receives an interrupt while printing to a terminal, it flushes all accumulated error messages to the
screen before terminating.
EXIT CODES

The pr utility exits 0 on success, and 1 if an error occurs.


Error messages are written to standard error during the printing process (if output is redirected) or after all
successful file printing is complete (when printing to a terminal).
SEE ALSO

cat(1), more(1)
ORIGIN

Pr includes software developed by the University of California, Berkeley and its contributors. Please see
the intro section for complete acknowledgements.

SunOS 5.8

Last change: NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

prune(1)

prune(1)

NAME
prune prune log files to specified size

SYNOPSIS
prune

DESCRIPTION
prune is a utility that prunes log files to a specific size. prune clips off the tops of the log files to shorten
them.
prune reads the file share/prune/prune_list (from the Network Shell install directory) to find the names of
the files to prune. Each line of prune_list should consist of two white space separated fields. The first field
is the name of the file you want to prune and the second field is the size in KB that the file should be pruned
to. Lines beginning with a # are treated as comment lines and are ignored.
prune was designed to run from cron. When running from cron with root privileges be sure to allow root
access on remote hosts in order for prune to work (See exports(1)).

AUTHORS
prune was originally written by Ray Davis, with modifications made by Thomas Kraus.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

putcert(1)

putcert(1)

NAME
putcert push a certificate generated by bl_gen_ssl to one or more servers

SYNOPSIS
putcert user_name id.pem server1 [<server2> <server2>]

DESCRIPTION
The putcert command pushes a certificate that was generated by the bl_gen_ssl command to one or more
servers. When the putcert command is issued, BladeLogic places the public key in a file called
<user_name>. The file resides in the /nsh/certs directory on UNIX-style servers and in /Program
Files/BladeLogic/RSC/certs on Windows servers.

OPTIONS
user_name
The name of the user who created the certificate by running bl_gen_ssl.
id.pem

The path to the id.pem file generated by the bl_gen_ssl command.

server1 [<server2> <server2>]


A space-delimited list of the names or IP addresses of the servers to which the certificate should
be pushed.

EXAMPLE
putcert gopal id.pem linuxBuild solarisQA

ORIGIN
putcert was developed by BladeLogic, Inc.

SEE ALSO
bl_gen_ssl(NSH), nukecert(NSH)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

putlic(1)

putlic(1)

NAME
putlic License remote agents

SYNOPSIS
putlic

DESCRIPTION
The putlic command is meant to be used in conjunction with the getlic command. The basic idea is to let
you remotely license multiple servers. The getlic command gathers necessary license information from
each remote host, and places this information in a file called license.raw. BladeLogics licensing web
page takes this file and creates a file called license.dat. putlic uses license.dat to license the
remote agents.
The license.dat file can contain multiple entries, one per line. Each entry consists of a hostname, a
product code, a license key, and an optional expiration key. putlic sends this data to each remote host
(listed in the first field of each entry) and creates an appropriate license based on the data.

USAGE
The putlic command takes an optional argument that specifies the name of the file containing the license
data. If you do not specify a file name, putlic defaults to using the license.dat file.
host $ putlic
Host bombay successfully licensed
Host madras successfully licensed

CAVEATS
To install new licenses on remote UNIX-style machines, you usually need root privileges.

ORIGIN
putlic was written by Thomas Kraus

SEE ALSO
getlic(NSH), agentinfo(NSH).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

redi(1)

redi(1)

NAME
redi redirect input to a file

SYNOPSIS
redi [-?] [-a] filename

DESCRIPTION
redi reads the standard input and writes it to filename. If the file does not exist, redi creates it.
The primary purpose of this utility is to let you perform distributed redirection. In other words, you can use
redi as a replacement for the output redirection sh(1) commands (> and >>) in a distributed environment
by piping the data to the redi command.

OPTIONS
-a

Append to the file instead of overwriting the file. If the file does not exist, create it. Equivalent to
the >> command.

-?

Output a brief summary of available options and then exit with a zero status without redirecting
any input.

EXAMPLE
$ wc *.c | redi files.wc
This would be equivalent to:
$ wc *.c > files.wc
The following example appends the data found by the fgrep utility into the file /etc/users.bad on
host vaduz.
$ fgrep evil /etc/passwd | redi -a //vaduz/etc/users.bad

DIAGNOSTICS
redi: Unable to redirect output to file filename
redi was unable to create or append to the file filename.
redi: Error redirecting output to file filename
An error occurred while trying to write data to the named output file. This message will be followed by system error message offering a possible reason for the error.

EXIT CODES
0

No errors detected.

You specified an unknown option.

An error occurred in redirecting the data to the named output file.

255

Unable to get a license to use the software.

ORIGIN
redi was written by Thomas Kraus

SEE ALSO
sh(1).

NSH

Property
of BladeLogic,
BSD System
ManagersInc.
Manual
Strictly confidential and proprietary

RENICE ( 8 )

RENICE ( 8 )

NAME
renice alter priority of running processes
SYNOPSIS
renice priority [ [ p] pid ...] [ [ g] pgrp ...] [ [ u] user ...]
DESCRIPTION
Renice alters the scheduling priority of one or more running processes. The following who parameters are
interpreted as process IDs, process group IDs, or user names. Reniceing a process group causes all
processes in the process group to have their scheduling priority altered. Reniceing a user causes all
processes owned by the user to have their scheduling priority altered. By default, the processes to be affected
are specified by their process IDs.
Options supported by renice:
g

Force who parameters to be interpreted as process group IDs.

Force the who parameters to be interpreted as user names.

Resets the who interpretation to be (the default) process IDs.

For example,
renice +1 987 -u daemon root -p 32
would change the priority of process IDs 987 and 32, and all processes owned by users daemon and root.
Users other than the super-user may only alter the priority of processes they own, and can only monotonically increase their nice value within the range 0 to PRIO_MAX (20). (This prevents overriding administrative fiats.) The super-user may alter the priority of any process and set the priority to any value in the range
PRIO_MIN (20) to PRIO_MAX. Useful priorities are: 20 (the affected processes will run only when nothing else in the system wants to), 0 (the base scheduling priority), anything negative (to make things go
very fast).
FILES
/etc/passwd to map user names to user IDs
SEE ALSO
getpriority(2), setpriority(2)
BUGS
Non super-users can not increase scheduling priorities of their own processes, even if they were the ones that
decreased the priorities in the first place.
The Linux kernel (at least version 2.0.0) and linux libc (at least version 5.2.18) does not agree entierly on
what the specifics of the systemcall interface to set nice values is. Thus causes renice to report bogus previous nice values.
HISTORY
The renice command appeared in 4.0BSD.

4th Berkeley Distribution

June 9, 1993

Property of BladeLogic, Inc.


Strictly confidential and proprietary

rm(1)

rm(1)

NAME
rm Remove a file

SYNOPSIS
rm [-] [-firRv?] file ...

DESCRIPTION
rm removes the named files. rm removes a file by unlinking it from its parent directory. If this link was the
last link the file had, then rm also destroys the file.
rm does not remove directories unless you use the -r option. In this case, rm deletes ALL files and subdirectories in the named directory.

OPTIONS
-f

This option causes rm not to output any error messages that occur.

-i

This option causes rm to first prompt the user to see if rm should remove the file/directory. If the
user confirms with an entry beginning with the letter y, then rm removes the file/directory. See
UNIVERSE BEHAVIOR for details on how this option interacts with the -f option.

-r

If any of the named arguments is a directory, then rm will recursively descend the directory and
try to remove all files and sub-directories below it.

-R

Same as -r

-v

Output a message for each file or directory to be removed. Useful for monitoring recursive file
removal.

This option causes rm to treat the remaining arguments as file names. This can be useful when
trying to remove a file starting with the character -.

-?

Output a brief summary of available options and then exit with a zero status without removing
any files.

file

File to be removed

EXAMPLE
The first example removes all .old files in the directory /tmp The second example removes all .old
files in the directory /u1/data on host helsinki.
$ rm /tmp/*.old
$ rm -frv //helsinki/u1/data/*.old

DIAGNOSTICS
rm: filename non existent
You asked rm to remove a file that does not exist.
rm: dirname is a directory
You asked rm to remove a directory without using the -r option.
rm: Unable to access directory dirname
When removing a directory recursively, rm was unable to access a directory within the directory
hierarchy.
rm: Unable to remove file filename
There was a problem in removing the file filename.
rm: Unable to remove directory dirname
There was a problem in removing the directory dirname.

EXIT CODES
0

No errors detected.

You specified an unknown option.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

rm(1)

One of the files to be removed was not removable.

255

Unable to get a license to use the software.

rm(1)

CAVEATS
rm will not allow you to delete the directories . and ..

UNIVERSE BEHAVIOR
If both the -i and -f options are used, then with the P_BSD variable set (Berkeley behavior), the -i option
will override the -f option. With the P_ATT variable set, the -f option will override the -i option.

ORIGIN
rm was written by Thomas Kraus

SEE ALSO
rmdir(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

rmdir(1)

rmdir(1)

NAME
rmdir Remove an empty directory

SYNOPSIS
rmdir [-] [-ifps?] directory ...

DESCRIPTION
rmdir tries to remove the named directories. For a directory to be removed, it must be empty, meaning that
it must not contain any files or sub-directories.

OPTIONS
-f

This option causes rmdir not to output any error messages that occur.

-i

This option causes rmdir to first prompt the user to see if the directory should be removed. If the
user confirms with an entry beginning with the letter y, then rmdir will remove the directory. See
UNIVERSE BEHAVIOR for details on how this option interacts with the -f option.

-p

This option causes rmdir to try to also delete any of the named parent directories. If the parent
directory is not explicitly named as a component of the directory, then rmdir will not delete it.

-s

This option is used in conjunction with the -p option, where if there are any errors in removing a
directory, then no error messages are output.

This option causes rmdir to treat the remaining arguments as directory names. This can be useful when trying to remove a directory starting with the character -.

-?

Output a brief summary of available options and then exit with a zero status without removing
any directories.

directory
Directory to be removed

EXAMPLE
The first example will first ask for confirmation that the directory mydir should be deleted. The second
example deletes the directory mydir/foo and then tries to remove the (parent) directory mydir on host
valetta.
$ rmdir -i mydir
$ rmdir -p //valleta/mydir/foo

DIAGNOSTICS
rmdir: Cannot remove directories . or ..
rmdir does not allow you to remove the directories . and ... If you try to do this, and you
are not suppressing error messages, then rmdir displays this message.
rmdir: Unable to delete directory dirname
If there is an error in deleting the directory dirname, rmdir displays this message, along with a
possible explanation of why the operation failed.

EXIT CODES
0

No errors detected.

You specified an unknown option.

One of the files to be deleted was not accessible.

255

Unable to get a license to use the software.

CAVEATS
By default the command ls does not show hidden files in a directory (files beginning with the character .).
Consequently, running ls in a directory may seem to indicate that the directory is empty, but when you try
to remove the directory using rmdir, rmdir may complain that the directory is not empty. Use the -a option
in ls to find hidden files.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

rmdir(1)

rmdir(1)

UNIVERSE BEHAVIOR
If both the -i and -f options are used, then with the P_BSD variable set (Berkeley behavior), the -i option
will override the -f option. With the P_ATT variable set, the -f option will override the -i option.

ORIGIN
rmdir was written by Thomas Kraus

SEE ALSO
mkdir(1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

rscd(1)

rscd(1)

NAME
rscd - Remote System Call Daemon

SYNOPSIS
rscd [-D] [-d] [-f] [-i] [-r] [-x]

DESCRIPTION
The RSCD agent (or daemon) is the piece of software that needs to be installed and running on each remote
host, so that the Network Shell utilities can access the host.

STARTING THE RSCD AGENT


There are two ways to start the RSCD agent.
The first way is to start the RSCD agent directly, either from a command line or from a script. In this case,
the RSCD agent first turns itself into a daemon, so that it can run in background mode. This master process
will eventually fork off sub-processes for client connections as these connections are made and validated.
But first, the agent needs to determine the TCP/IP port on which it should be listening. The agent determines its TCP/IP port in the following way.
1 - It looks for an rscd entry in the secure file. If it finds an entry, it uses the configured port number.
2 - If it does not find an entry there, it looks for an rscd entry in the Internet service database (often
/etc/services ). If it finds an entry in the database, it uses the configured port number.
3 - If it does not find an entry in either the secure file or in the Internet services database, the agent
defaults to port 4750.
Once the agent has determined its TCP/IP port, it opens a connection on that port and listens for Network
Shell client connections. When it hears a connection, the agent determines and sets appropriate permissions
(see below).
Next, the agent forks off a child process to handle all future requests from that one client (connection).
Before the client exits, the connection to the agent is closed and the agent terminates.
The second way to start the RSCD agent is through the inetd mechanism. With this mechanism, the Internet services daemon ( inetd ) acts as the master process and just forks off rscd sub-processes as needed.
See the -i option for the RSCD agent below.

RSCD AND SECURITY


When a Network Shell utility (client) attempts to access a remote host, it basically attempts to make a connection to the RSCD daemon running on that remote host. When an RSCD agent receives a connection, it
initially accepts the connection and then checks to see if the connection is allowed. It goes through the following steps:
1 - Determine the client machine from which the connection is coming.
2 - Based on the client host, determine how the communication between the two should occur. This information is found in the secure file and includes, among other things, the encryption type and encryption
key or keys.
3 - Before going any further, the agent consults the exports file to determine if the client is even allowed
to make the connection. If not, the agent closes the connection. At this time full acceptance of the
client has not yet occurred, because some of the criteria for acceptance can only be determined after
the initial handshake. For now it will proceed and fork off a sub-process to continue handling the
acceptance. If you started the agent with the -i option (start from inetd) then the fork does not occur.
4 - The agent must now handle the initial handshake between the client and daemon (server). If necessary,
the agent decrypts the data that the client sent, then verifies that it is a valid handshake. If the handshake is invalid (which usually occurs when the encryption type and/or encryption keys do not match),
the agent closes the connection. If the handshake is valid, the initial handshake will include valuable
information about the connecting client. The agent will use this information in further security related
checks.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

rscd(1)

rscd(1)

5 - Once it has the initial handshake data, the daemon now consults the users file see if there should be
any specific (override) permissions for the connecting user. These are also known as the user overrides. If there should be overrides, the daemon sets them.
6 - Once the daemon has all the relevant information, it decides whether or not the client should have
access, and what permissions the client should have. If the client is not allowed to have access, the
daemon closes the connection without processing any requests. If the client is allowed to have access,
then the daemon sets the final permissions, which includes performing a seteuid and setegid (UNIX
type systems only).

OPTIONS
The RSCD agent accepts the following options:
-i

Use this option when you are starting the daemon from inetd. A sample entry for the
/etc/inetd.conf file might look something like this:
rscd stream tcp nowait root /opt/nsh/bin/rscd rscd -i

When you use this option, the default TCP/IP communications port is not determined by the
secure file, but rather by the rscd Internet service entry found in the /etc/services file or other
respective configuration file.
-r

This option tells the RSCD daemon to retry listening on the configured TCP/IP port if the port is
currently already being listened on. Sometimes after the master RSCD daemon exits, the port it
was listening on may continue to be busy for a short time longer. This option tells the daemon to
retry listening on the port every 10 seconds until it succeeds.
Note that if the daemon was initiated by inetd then the port will never be free (not being listened
on), and the daemon will just keep trying and trying and trying.

The following options are not recommended for use and exist only for debugging purposes.
-D

Do not go into daemon mode.

-f

Do not fork. Implied if -i option is used and basically makes the daemon single use. After the
first client exits the daemon exits as well.

-d

Output some debug messages.

-x

Output brief usage description.

ORIGIN
rscd was written by Thomas Kraus

SEE ALSO
exports (1), secure (1), users (1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

rsu(1)

rsu(1)

NAME
rsu Run NSH command with alternate privileges

SYNOPSIS
rsu [-p] user command [args ...]

DESCRIPTION
You can use the rsu command to run a command with a different set of permissions on a remote machine.
Normally, when you run an NSH command to access a remote host, the RSCD agent (NSH server) of that
host assigns you a specific set of permissions. Those permissions govern your access to that host. With the
rsu command, you can select an alternate user whose permissions will be granted to the selected NSH command you are using to access the remote host. The specified users permissions will override the standard
permissions. You obtain the specified users permissions by providing the password for the user on the
remote host. When the command accesses a remote host for the first time, you will be prompted for the
users password for that host. The user and entered password are then authenticated on the remote server.
If the user/password combination does not properly authenticate on the remote host, you will not get access
to the host. Otherwise the command will continue on with the new permissions.
If you are accessing multiple hosts, you will need to enter the respective password for the user for each
host.
Except when you are using the -p option (see below), this change in permissions applies only to the
selected command. It does not apply to any sub-commands (processes). In other words, if you rsu root a
vi session and enter into a sub-shell, the sub-shell and subsequent commands you run from the shell will
NOT have the new permissions.

OPTIONS
You can configure the RSCD agent to let you rsu to the remote server without having to enter a password.
To do this, use the -p option. For this option to work, the remote user must be configured on the remote
server as a user who does not need a password. If the remote user is not set up this way, you will not gain
access to the remote server, just as if you had entered an incorrect password.

EXAMPLE
The following example shows a sample session where you can determine your effective UID on the various
hosts you are working with.
$ /bin/nsh
host1 $ id
uid=503(tmk) gid=600(nsh)
host1 $ nexec host2 id
uid=503(tmk) gid=600(nsh)
host1 $ rsu root nexec host2 id
Password for root@host2:
uid=0(root) gid=1(other)
host1 $
In this example you can look at a restricted file on two hosts
$ /bin/nsh
host1 $ cat //host2/etc/shadow //host3/etc/shadow
cat: Cannot open file //host2/etc/shadow: Permission denied
cat: Cannot open file //host3/etc/shadow: Permission denied
host1 $ rsu root cat //host2/etc/shadow //host3/etc/shadow
Password for root@host2:
...
Password for root@host3:
...
host1 $

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

rsu(1)

rsu(1)

CAVEATS
The -p option will work only if the target server has been specifically configured to allow the rsu command
to access the server without providing a password. Appropriate entries (rsu=...) in the users,
users.local, and/or exports file must exist. See the users and/or exports man pages for more details.

EXIT CODES
rsu exits with the same exit code as that of the finished command.

ORIGIN
rsu was written by Thomas Kraus

SEE ALSO
users(1), exports (1), rscd(1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

runcmd(1)

runcmd(1)

NAME
runcmd Run a Network Shell command on one or more hosts

SYNOPSIS
runcmd [-v -n -p n] [-H header] [-NH] [-s | -c] [-d directory] [-f file] [-h host1 ... hostn] [-e command1 ...
commandn]
runscript [-v -n -p n] [-H header] [-NH] [-s | -c] [-d directory] [-f file] [-h host1 ... hostn] [-e command1 ...
commandn]

DESCRIPTION
The programs runcmd and runscript let you run the same command on multiple machines. The difference
between the two is that runcmd executes a shell command, while runscript runs the given Network Shell
script on each machine.
Depending on what action you are currently performing, you may want to know which host you are dealing
with. To this end, the environment variable NSH_RUNCMD_HOST is set for each sub-command that is run.
Furthermore the environment variable NSH_RUNCMD_DIR is set indicating the current Network Shell
path.

OPTIONS
-c

Execute a Network Shell command on each host. This is implicit if the program name is runcmd

-d dirname
When you specify the hosts on which you want to run the command, you have the option of also
specifying a start directory on each host. If you do not specify a start directory with the host, you
can specify it using the -d options dirname.
-e cmd ...
This option specifies the command to execute. This option must be the last option. All arguments
after the -e are assumed to be part of the commands to be executed on each host.
-f file

This option indicates that file file contains the names of the hosts on which the command is to be
executed. The format of this file is one entry per line, where each entry can be either a hostname
or a UNC name, which consists of a hostname and directory.

-h host ...
This option indicates the host(s) on which you want to run the command. You can specify multiple hosts by putting spaces between host names. After encountering the -h option, runcmd and
runscript consider all subsequent arguments to be host names, until runcmd and runscript
encounter another option (an argument starting with -). As with each entry in the file specified
with the -f file option, each -h argument can be either a hostname or a UNC name, which consists
of a hostname and directory.
-H header
By default, runcmd and runscript output a brief header before the command is executed. This
lets you easily differentiate the output that each host produces. The default header is "==> %h
<==" where the macro "%h" is substituted by the name of the host where the program is about to
be executed.
The -H header option lets you specify a custom header. For example, if you specified
-H "%h belongs to Engineering"
for the host eng1, your header line would read
eng1 belongs to Engineering.
-n

This option tells runcmd and runscript not to output a CR (carriage return) after the header.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

runcmd(1)

runcmd(1)

-NH

This option tells runcmd and runscript not to display a header. This includes the default header
or any header you defined using the -H option.

-p n

Run up to n commands/scripts in parallel. This can significantly speed things up, but be advised
that since things are running in parallel, the output generated by each instance may overall not be
output in a linear way. In other words, if you are going to make assumptions about the output produced by each instance, you may not want to do things in parallel.

-v

Output the effective command executed for each host.

-V

Tag each line with the name of the host the output is coming from. The host name is preceded by
a ( and followed by a ) as in (hostname).

-s

Execute a Network Shell script on each host. This is implicit if the program name is runscript.

-?

Output a brief explanation of the available options.

EXAMPLE
Some simple examples.
host% runcmd -h rome athens -d /etc -e ls -l \| wc -c
host% runscript -h //rome/bin //athens/bin -e scriptname -script_option
host% runcmd -h rome athens paris london -p 2 -e ifconfig ppp down
host% runcmd -h rome athens -d /tmp -e sh -c echo $NSH_RUNCMD_HOST $NSH_RUNCM
==> rome <==
rome //rome/tmp
==> athens <==
athens //athens/tmp

EXIT STATUS
If a command or script is successfully executed on all named hosts, then these programs will exit with a status of 0. If an error occurs or if a command or script exits with a non zero status, then these programs will
exit with a non-zero status.

ORIGIN
runcmd and runscript were written by Thomas Kraus

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

scriptutil(1)

scriptutil(1)

NAME
scriptutil Copy and execute scripts on remote servers

SYNOPSIS
scriptutil [-d dir] [-f file] -h host1 [host2 ...] [-l] [-o file] -s scan [-x arg]

DESCRIPTION
The idea behind scriptutil is to execute a given script on a remote server without the need to have the script
on the given server before the script is executed (if the script already exists on the remote server one can
execute the script directly by using nexec).
Scriptutil also supports the concept of a script library that in turn supports the concept of OS abstraction. As
a particular task may have different implementations on various UNIX type servers, one still wants to have
a single point of access for all platforms for that task.
The script library is found in <install_directory>/share/sensors. Scripts in the library with an OS name
extension (output of uname command) are treated as overrides for the particular platform (i.e. no OS name
extension). As such, when looking to run a script, scriptutil proceeds as follows for a given script to run on
a particular server:
1)

Determine remote OS type

2)

Look for script name with OS name extension in library directory

3)

If not found look for script in library directory as is (no OS name extension)

4)

Copy script to remote server

5)

Execute script on remote server capturing (and passing through) stdout and stderr

6)

Remove script from remote server

OPTIONS
The following options are supported.
-d dir

The default staging directory for the script is /tmp. With this option one can override the staging directory.

-f file

file contains a list of servers one wants to run the scripts on (one entry per line). See also -h

-h host [host ...]


Add host to the list of hosts one wants to run the script on. Can specify multiple hosts and can
also be used in conjunction with the -f file option.
-l [name]
Show the list of scripts in the library and exit. If a name is given, then it will show all scripts (for
all OSes) of that name.
-o file

By default, the output (stdout) of the script is sent to stdout on the local machine. With this option
one can specify a file to which the output is sent.

-s script Specify the name of the script one want to run on the given remote servers. If the script refers to
an existing file then that file will be the one copied and executed. If it does not refer to an existing file, then the script library will be searched with the OS type extension filter applied.

EXAMPLE
Show all scripts
host% scriptutil -l
.
.
grp_uniq_gid
grp_uniq_grpname
net_disabled_uucp.AIX

- [ALL] Audit non-unique GIDs in /etc/group


- [ALL] Audit non-unique group names in /etc/group
- [AIX] Audit that UUCP is disabled

NSH

scriptutil(1)

Property of BladeLogic, Inc.


Strictly confidential and proprietary
net_disabled_uucp.HP-UX
.
.

scriptutil(1)

- [HP-UX] Audit that UUCP is disabled

Example of using a script in the script library


host% scriptutil -h rome -s net_disabled_uucp
Example of using an existing script
host% cd //athens/tmp
athens% cat rr
pwd
athens% scriptutil -h rome -s rr -d /tmp/nsh
/tmp/nsh

ORIGIN
scriptutil was written by Thomas Kraus

SEE ALSO
runscript (NSH), nexec (NSH).

NSH

SDIFF (1)

System General Commands Manual

SDIFF (1)

NAME
sdiff side-by-side diff
SYNOPSIS
sdiff [ abdilstW] [ I regexp] [ o outfile] [ w width] file1 file2
DESCRIPTION
sdiff displays two files side by side, with any differences between the two highlighted as follows: new
lines are marked with >; deleted lines are marked with <; and changed lines are marked with |.
sdiff can also be used to interactively merge two files, prompting at each set of differences. See the o
option for an explanation.
The options are:
l

Only print the left column for identical lines.

o outfile
Interactively merge file1 and file2 into outfile. In this mode, the user is prompted for each
set of differences. See EDITOR and VISUAL, below, for details of which editor, if any, is invoked.
The commands are as follows:
l | 1 Choose left set of diffs.
r | 2 Choose right set of diffs.

Silent mode identical lines are not printed.

Verbose mode identical lines are printed.

Start editing an empty file, which will be merged into outfile upon exiting the editor.

e l

Start editing file with left set of diffs.

e r

Start editing file with right set of diffs.

e b

Start editing file with both sets of diffs.

Quit sdiff.

Skip identical lines.

w width
Print a maximum of width characters on each line. The default is 130 characters.
Options passed to diff(1) are:
a

Treat file1 and file2 as text files.

Ignore trailing blank spaces.

Minimize diff size.

I regexp
Ignore line changes matching regexp. All lines in the change must match regexp for the change
to be ignored.
i

BSD

Do a case-insensitive comparison.

March 28, 2008

SDIFF (1)

System General Commands Manual

Expand tabs to spaces.

Ignore all spaces (the w flag is passed to diff(1)).

SDIFF (1)

ENVIRONMENT
EDITOR, VISUAL
Specifies an editor to use with the o option. If both EDITOR and VISUAL are set, VISUAL takes
precedence. If neither EDITOR nor VISUAL are set, the default is vi(1).
TMPDIR
Specifies a directory for temporary files to be created. The default is /tmp.
SEE ALSO
cmp(1), diff(1), diff3(1), vi(1), re_format(7)
AUTHORS
sdiff was written from scratch for the public domain by Ray Lai ray@cyth.net.
CAVEATS
Although undocumented, sdiff supports most long options supported by GNU sdiff, though some require
GNU diff.
Tabs are treated as anywhere from one to eight characters wide, depending on the current column. Terminals
that treat tabs as eight characters wide will look best.
BUGS
sdiff may not work with binary data.

BSD

March 28, 2008

secadmin(1)

Property of BladeLogic, Inc.


Strictly confidential and proprietary

secadmin(1)

NAME
secadmin Utility to define encryption and authentication security

SYNOPSIS
secadmin -up | -down | -top | -bottom hostname
secadmin -c <config_file> ...
secadmin -c <config_file> -i
secadmin -d [hostname]
secadmin -P [-C]
secadmin -W hostname size
secadmin -a|m [hostname] [-w size] [-r [port [hostname]]] [-p 5] [-e tls]
secadmin [-appserver_host [hostname]] [-appserver_port [port]] [-appserver_protocol [ clear | srp ]]
secadmin [-cu [username]] [-cp [password]]

DESCRIPTION
Secadmin is a utility that can be used to define communications parameters, including encryption and
authentication parameters, for BladeLogic clients and RSCD servers running on the local host.
By default, BladeLogic clients and servers use a communication protoccol called protocol 5 that is based on
a TLS transportation mechanism (a.k.a. SSL). Protocol 5 auto-negotiates the most secure connection
between a client and server.
Secadmin also lets you edit the securecert file, which stores encrypted password information needed to
access the private key for X.509 certificates. By storing passwords in the securecert file, BladeLogic can
access those passwords without any user interaction. Accessing passwords non-interactively is essential for
setting up secure, certificate-based communication between an Application Server and agents and repeaters.
It is also necessary when using secure communication to deploy assets via repeaters (that is, through an
indirect deployment). See CREATING ENTRIES IN THE SECURECERT FILE.

CREATING ENTRIES IN THE SECURE FILE


When using secadmin to create a secure file, you can specify communication parameters by creating three
types of entries: rscd, default, or hostname.
When configuring default communication parameters for servers, use the special hostname rscd.
When configuring default communication parameters for BladeLogic clients, use the special hostname
default. If an entry does not exist for a particular remote host, then the software looks for a default entry.
Thus, if you are using the same communication parameters for all your RSCD Agents, you do not have to
create an entry for each remote host needing access to those agents.
When configuring communication parameters for a specific host (client or server), create a hostname entry
in the secure file. When entering a value for hostname, you can provide a hosts IP address, a resolvable
host name, or a subnet designation that defines a range of addresses (see SUBNET DESIGNATIONS
below).
NOTE: Hostnames are matched to secure file entries by matching the IP addresses (including ranges) of
their respective resolved names and not by comparing the hostnames entered in secure file entries.
The order of entries in the secure file matters. When a client attempts to establish a connection with a
server, the client searches from top to bottom through entries in its secure file until it finds the first entry
that resolves to an IP address matching the IP address of the server. If the client does not find a match, it
uses the default entry. On the agent side, when the agent detects that a host is attempting to make a connection, the agent searches its secure file from top to bottom until it finds the first entry that resolves to an IP
address matching the IP address of the client attempting to make a connection. If the agent does not find a
match, it uses the rscd entry. If you are creating entries for individual hostnames as well as an rscd or
default entry, place the rscd or default entry at the end of the list.

CREATING ENTRIES IN THE SECURECERT FILE


When using secadmin to edit a securecert file, you can create entries for an Application Server and entries
for repeaters.
For an Application Server, create an entry that stores the password for the owner of the process that

NSH

secadmin(1)

Property of BladeLogic, Inc.


Strictly confidential and proprietary

secadmin(1)

communicates securely with repeaters and servers. On UNIX-style systems, that user is bladmin. On Windows, that user is SYSTEM. To accomplish this, enter one of the following commands:
# secadmin -m default -cu bladmin -cp password
# secadmin -m default -cu SYSTEM -cp password
For a repeater, create an entry that stores the password for the administrative user that communicates with
servers. On UNIX-style systems, that user is typically root. On Windows, that user is BladeLogicRSCD. To
accomplish this, enter one of the following commands:
# secadmin -m default -cu root -cp password
# secadmin -m default -cu BladeLogicRSCD -cp password

OPTIONS
With the secadmin utility, you can delete or modify an existing entry in the secure file as well as add new
entries to the file. When issuing a secadmin command, you must append one of the following options
immediately after the command:
-c file

Use file as an alternate secure file. If no value is entered for file, then the file secure.cfg is used.
(NOTE: The alternate secure file is encrypted). The primary use for this option is to create and
install pre-configured secure files. As mentioned above, in a regular secure file, passwords (keys)
are encrypted using a key that is unique to the host for which the key is generated. While this is
an important security measure, it impedes the ability to pre-configure the secure file for use in
automated or non-interactive installations on multiple systems. With the -c option you can create
and install (-c and -i) a portable secure file. Since this alternate secure file is encrypted, the passwords are not revealed. The encrypted file must be installed on a system using the -i option. See
below for details.

-d hostname
Delete the entry for entry hostname. If hostname is not provided, you are prompted to enter the
hostname.
-m hostname
Modify the entry for host hostname. If hostname is not provided, you are prompted to enter the
hostname.
-a hostname
Create a new entry for host hostname. If hostname is not provided, you are prompted to enter the
hostname.
-P

Print the output of the current configuration in a formatted table. If this option is followed by the
-C option then the output will be in a CSV format.

At times it may be necessary to re-arrange the order of the entries in the secure file. This primarily happens when you are working with subnet definitions (see below) and you have individual host overrides in
that subnet. Use the following options to change the order of an entry:
-up hostname
Move the entry up one.
-down hostname
Move the entry down one.

NSH

secadmin(1)

Property of BladeLogic, Inc.


Strictly confidential and proprietary

secadmin(1)

-top hostname
Move the entry to the top of the list.
-bottom hostname
Move the entry to the bottom of the list.
If you are adding or modifying an entry, you can enter the following options to define the communication
parameters for a given hostname. Each of the following options may require additional arguments. If you
omit these additional arguments from the command line, the secadmin utility prompts you for all information required to create or modify an entry.
-W hostname size
Only update the network write buffer size for host hostname to be size bytes.
-i

Install an encrypted secure file created with the -c option. This option must be used with the -c
option. Please see the EXAMPLES section below for an example.

-w size

Set the network write buffer size to be size bytes with the default size being 4480 bytes. See the
nshopt command for details about the network write buffer size.

-z value Set compression level. By default data is not compressed. To compress data, set value to a number between 1 and 9, with a higher number indicating better compression. Note that better compression is more CPU intensive.
-l n

When set to a non-zero positive value, this option determines the maximum number of times a
bad connection is allowed from a source address before the address is locked. A bad connection
can happen if encryption is not set up properly or a particular host is not granted access. The
address is locked for a period of time as defined by the -u field (see below).

-u n

This option is used in conjunction with the -l option, which allows you to lock out IP addresses
that repeatedly fail to connect to an agent. These failures are limited to encryption misconfigurations and host authorization errors. With the -u option, you can specify how many minutes the IP
address should be locked before allowing connection attempts to resume. If -u is a negative number, the IP address is locked until the RSCD Agent is restarted. The default value for -u is 1
minute.

-T mode Specify one of the following TLS features:


encryption_only
Use the TLS protocol to auto-negotiate an encryption type (that is, a cipher) and then
use that cipher to communicate. No authorizations or certificates are required.
encryption_and_auth
Use TLS for encryption and authorization. This option requires a certificate. The software searches for certificates in $HOME/BladeLogic/id.pem.
-p protocolnum
Specify which protocol to use. The default protocol is protocol 5, supported since release 5.2.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

secadmin(1)

secadmin(1)

-r [port [hostname]]
Specify port redirection parameters. When accessing the host specified in either the -m or -a
option, data should be sent to the specified port number on the host hostname. If no hostname is
given, then data is sent to the alternate port number on the hostname specified by the -m or -a
options. Setting hostname to - is the same as giving no redirection host. This value is useful
because otherwise the secadmin utility will prompt you for a redirection host.
Currently the rscd daemon cannot listen to multiple ports for connections. Consequently, if you
want to use an alternate port number for a server, all clients must be configured to use that alternate port number when accessing a server.
-e tls

Specify the encryption method to be used to encrypt data between BladeLogic clients and the
RSCD Agent (daemon). BladeLogic now only supports the tls encryption type.

-appserver_host
Specify the Application Server, configured as a Network Shell Proxy Server, that functions as an
intermediary when Network Shell is communicating with RSCD agents.
-appserver_port
Specify the port used to connect to a Network Shell Proxy Server. This value is related to the
-appserver_host setting.
-appserver_protocol
Specify the authentication protocol used when communicating with a Network Shell Proxy
Server. This field is related to the -appserver_host setting. Set the protocol to one of the following:
clear

Do not use authentication when communicating with the Network Shell Proxy Server.

srp

Use SRP authentication when communicating with the Network Shell Proxy Server.

The secadmin utility also provides the following options, which let you add entries to the securecert file:
-cu

The user for whom you are storing a password to the private key for an X.509 certificate.

-cp

The password to the private key for a users X.509 certificate.

SUBNET DESIGNATIONS
When defining a hostname or address for a specific permission, you can choose to specify a subnet address
that defines a range of addresses for that entry. A subnet designation has the following format:
@<IP Address or Hostname>/mask
The @ symbol indicates that a subnet is being defined. It should be followed by an IP address or hostnames
within the subnet followed by a / and then the number of bits in the subnet mask. A subnet with a subnet
mask of 255.255.255.0 might look something like:
@192.168.10.0/24
Here are some sample subnet mask definitions:

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

secadmin(1)
255.255.255.000
255.255.255.128
255.255.255.192
255.255.255.224
255.255.255.240
255.255.255.248

secadmin(1)

@192.168.100.0/24
@192.168.100.129/25
@192.168.100.193/26
@192.168.100.225/27
@192.168.100.241/28
@192.168.100.249/29

EXAMPLES
The following examples illustrate actions you can take to modify the secure file.
To delete the entry for host foo, enter
# secadmin -d foo
To create a standard entry for host foo so it communicates using protocol 5 (the default communication protocol), enter
# secadmin -a foo -p 5 -e tls
To specify use of port 999 rather than the default port of 4750, enter the following command on the server
host:
# secadmin -a rscd -p 5 -r 999 -e tls
On each client host that is communicating with the server host, enter the following command.
# secadmin -a <server_host> -r 999 -e tls

SEE ALSO
nshopt (1).

NSH

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

SED (1)

SED (1)

NAME
sed stream editor
SYNOPSIS
sed [ an] command [file . . .]
sed [ an] [ e command] [ f command_file] [file . . .]
DESCRIPTION
The sed utility reads the specified files, or the standard input if no files are specified, modifying the input as
specified by a list of commands. The input is then written to the standard output.
A single command may be specified as the first argument to sed. Multiple commands may be specified by
using the e or f options. All commands are applied to the input in the order they are specified regardless
of their origin.
The options are as follows:
a

The files listed as parameters for the w functions are created (or truncated) before any processing
begins, by default. The a option causes sed to delay opening each file until a command containing the related w function is applied to a line of input.

e command
Append the editing commands specified by the command argument to the list of commands.
f command_file
Append the editing commands found in the file command_file to the list of commands. The
editing commands should each be listed on a separate line.
n

By default, each line of input is echoed to the standard output after all of the commands have been
applied to it. The n option suppresses this behavior.

The form of a sed command is as follows:


[address[,address]]function[arguments]
Whitespace may be inserted before the first address and the function portions of the command.
Normally, sed cyclically copies a line of input, not including its terminating newline character, into a
pattern space, (unless there is something left after a D function), applies all of the commands with
addresses that select that pattern space, copies the pattern space to the standard output, appending a newline,
and deletes the pattern space.
Some of the functions use a hold space to save all or part of the pattern space for subsequent retrieval.
SED ADDRESSES
An address is not required, but if specified must be a number (that counts input lines cumulatively across
input files), a dollar character ( $ ) that addresses the last line of input, or a context address (which consists
of a regular expression preceded and followed by a delimiter).
A command line with no addresses selects every pattern space.
A command line with one address selects all of the pattern spaces that match the address.
A command line with two addresses selects the inclusive range from the first pattern space that matches the
first address through the next pattern space that matches the second. (If the second address is a number less
than or equal to the line number first selected, only that line is selected.) Starting at the first line following
the selected range, sed starts looking again for the first address.

BSD

December 30, 1993

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

SED (1)

SED (1)

Editing commands can be applied to non-selected pattern spaces by use of the exclamation character ( ! )
function.
SED REGULAR EXPRESSIONS
The sed regular expressions are basic regular expressions ( BREs ) . See re_format(7) for more information on regular expressions. In addition, sed has the following two additions to BREs:
1.

In a context address, any character other than a backslash ( \ ) or newline character may be used to
delimit the regular expression. Also, putting a backslash character before the delimiting character
causes the character to be treated literally. For example, in the context address \xabc\xdefx, the RE
delimiter is an x and the second x stands for itself, so that the regular expression is abcxdef.

2.

The escape sequence \n matches a newline character embedded in the pattern space. You cant, however, use a literal newline character in an address or in the substitute command.

One special feature of sed regular expressions is that they can default to the last regular expression used. If
a regular expression is empty, i.e., just the delimiter characters are specified, the last regular expression
encountered is used instead. The last regular expression is defined as the last regular expression used as part
of an address or substitute command, and at run-time, not compile-time. For example, the command
/abc/s//XXX/ will substitute XXX for the pattern abc.
SED FUNCTIONS
In the following list of commands, the maximum number of permissible addresses for each command is indicated by [0addr], [1addr], or [2addr], representing zero, one, or two addresses.
The argument text consists of one or more lines. To embed a newline in the text, precede it with a backslash.
Other backslashes in text are deleted and the following character taken literally.
The r and w functions take an optional file parameter, which should be separated from the function letter
by whitespace. Each file given as an argument to sed is created (or its contents truncated) before any input
processing begins.
The b, r, s, t, w, y, !, and : functions all accept additional arguments. The following synopses
indicate which arguments have to be separated from the function letters by whitespace characters.
Two of the functions take a function-list. This is a list of sed functions separated by newlines, as follows:
{ function
function
...
function
}
The { can be preceded or followed by whitespace. The function can be preceded by whitespace as well.
The terminating } must be preceded by a newline or optional whitespace.
[2addr] function-list
Execute function-list only when the pattern space is selected.
[1addr]a\
text
Write text to standard output immediately before each attempt to read a line of input, whether
by executing the N function or by beginning a new cycle.
[2addr]b[label]
Branch to the : function with the specified label. If the label is not specified, branch to the end
of the script.

BSD

December 30, 1993

SED (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

SED (1)

[2addr]c\
text
Delete the pattern space. With 0 or 1 address or at the end of a 2-address range, text is written
to the standard output.
[2addr]d

Delete the pattern space and start the next cycle.

[2addr]D

Delete the initial segment of the pattern space through the first newline character and start the
next cycle.

[2addr]g

Replace the contents of the pattern space with the contents of the hold space.

[2addr]G

Append a newline character followed by the contents of the hold space to the pattern space.

[2addr]h

Replace the contents of the hold space with the contents of the pattern space.

[2addr]H

Append a newline character followed by the contents of the pattern space to the hold space.

[1addr]i\
text
Write text to the standard output.
[2addr]l

(The letter ell.) Write the pattern space to the standard output in a visually unambiguous form.
This form is as follows:
backslash
alert
form-feed
newline
carriage-return
tab
vertical tab

\\
\a
\f
\n
\r
\t
\v

Non-printable characters are written as three-digit octal numbers (with a preceding backslash)
for each byte in the character (most significant byte first). Long lines are folded, with the point
of folding indicated by displaying a backslash followed by a newline. The end of each line is
marked with a $.
[2addr]n

Write the pattern space to the standard output if the default output has not been suppressed, and
replace the pattern space with the next line of input.

[2addr]N

Append the next line of input to the pattern space, using an embedded newline character to separate the appended material from the original contents. Note that the current line number
changes.

[2addr]p

Write the pattern space to standard output.

[2addr]P

Write the pattern space, up to the first newline character to the standard output.

[1addr]q

Branch to the end of the script and quit without starting a new cycle.

[1addr]r file
Copy the contents of file to the standard output immediately before the next attempt to read a
line of input. If file cannot be read for any reason, it is silently ignored and no error condition is
set.
[2addr]s/re/replacement/flags
Substitute the replacement string for the first instance of the regular expression in the pattern
space. Any character other than backslash or newline can be used instead of a slash to delimit

BSD

December 30, 1993

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

SED (1)

SED (1)

the RE and the replacement. Within the RE and the replacement, the RE delimiter itself can be
used as a literal character if it is preceded by a backslash.
An ampersand ( & ) appearing in the replacement is replaced by the string matching the RE.
The special meaning of & in this context can be suppressed by preceding it by a backslash.
The string \#, where # is a digit, is replaced by the text matched by the corresponding backreference expression (see re_format(7)).
A line can be split by substituting a newline character into it. To specify a newline character in
the replacement string, precede it with a backslash.
The value of flags in the substitute function is zero or more of the following:
0 ... 9

Make the substitution only for the Nth occurrence of the regular expression
in the pattern space.

Make the substitution for all non-overlapping matches of the regular expression, not just the first one.

Write the pattern space to standard output if a replacement was made. If the
replacement string is identical to that which it replaces, it is still considered to
have been a replacement.

w file

Append the pattern space to file if a replacement was made. If the replacement string is identical to that which it replaces, it is still considered to have
been a replacement.

[2addr]t[label]
Branch to the : function bearing the label if any substitutions have been made since the most
recent reading of an input line or execution of a t function. If no label is specified, branch to
the end of the script.
[2addr]w file
Append the pattern space to the file.
[2addr]x

Swap the contents of the pattern and hold spaces.

[2addr]y/string1/string2/
Replace all occurrences of characters in string1 in the pattern space with the corresponding
characters from string2. Any character other than a backslash or newline can be used instead of
a slash to delimit the strings. Within string1 and string2, a backslash followed by any character
other than a newline is that literal character, and a backslash followed by an n is replaced by a
newline character.
[2addr]!function, [2addr]!function-list
Apply the function or function-list only to the lines that are not selected by the address(es).
[0addr]:label
This function does nothing; it bears a label to which the b and t commands may branch.
[1addr]=

Write the line number to the standard output followed by a newline character.

[0addr]

Empty lines are ignored.

[0addr]#

The # and the remainder of the line are ignored (treated as a comment), with the single exception that if the first two characters in the file are #n, the default output is suppressed. This is
the same as specifying the n option on the command line.

The sed utility exits 0 on success or >0 if an error occurred.

BSD

December 30, 1993

SED (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

SED (1)

SEE ALSO
awk(1), ed(1), grep(1), regex(3), re_format(7)
"SED A Non-interactive Text Editor", /usr/share/doc/usd/15.sed/.
STANDARDS
The sed function is expected to be a superset of the IEEE Std 1003.2 (POSIX.2) specification.
HISTORY
A sed command appeared in Version 7 AT&T UNIX.

BSD

December 30, 1993

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

sort ( 1 )

NAME

sort - sort or merge text files


SYNOPSIS

sort [-cmubdfinr] [-t char] [-T char] [-k field1[,field2]] ... [-o output] [file] ...
DESCRIPTION

The sort utility sorts text files by lines. Comparisons are based on one or more sort keys extracted from
each line of input, and are performed lexicographically. By default, if keys are not given, sort regards each
input line as a single field.
The following options are available:
-c

Check that the single input file is sorted. If the file is not sorted, sort produces the appropriate
error messages and exits with code 1; otherwise, sort returns 0. Sort -c produces no output.

-m

Merge only; the input files are assumed to be pre-sorted.

-o output The argument given is the name of an output file to be used instead of the standard output. This
file can be the same as one of the input files.
-u

Unique: suppress all but one in each set of lines having equal keys. If used with the -c option,
check that there are no lines with duplicate keys.

The following options override the default ordering rules. When ordering options appear independent of
key field specifications, the requested field ordering rules are applied globally to all sort keys. When
attached to a specific key (see -k), the ordering options override all global ordering options for that key.
-d

Only blank space and alphanumeric characters are used in making comparisons.

-f

Considers all lowercase characters that have uppercase equivalents to be the same for purposes of
comparison.

-i

Ignore all non-printable characters.

-n

An initial numeric string, consisting of optional blank space, optional minus sign, and zero or
more digits (including decimal point) is sorted by arithmetic value. (The -n option no longer
implies the -b option.)

-r

Reverse the sense of comparisons.

The treatment of field separators can be altered using the options:


-b

Ignores leading blank space when determining the start and end of a restricted sort key. A -b
option specified before the first -k option applies globally to all -k options. Otherwise, the -b
option can be attached independently to each field argument of the -k option (see below). Note
that the -b option has no effect unless key fields are specified.

-t char

Char is used as the field separator character. The initial char is not considered to be part of a field
when determining key offsets (see below). Each occurrence of char is significant (for example,
charchar delimits an empty field). If -t is not specified, blank space characters are used as
default field separators.

-T char

Char is used as the record separator character. This should be used with discretion; -T
<alphanumeric> usually produces undesirable results. The default line separator is newline.

-k field1[,field2]
Designates the starting position, field1, and optional ending position, field2, of a key field. The -k
option replaces the obsolescent options +pos1 and -pos2.
The following operands are available: file The pathname of a file to be sorted, merged, or checked. If no
file operands are specified, or if a file operand is -, the standard input is used.
A field is defined as a minimal sequence of characters followed by a field separator or a newline character.
By default, the first blank space of a sequence of blank spaces acts as the field separator. All blank spaces

SunOS 5.8

Last change: NSH

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

sort ( 1 )

in a sequence of blank spaces are considered as part of the next field; for example, all blank spaces at the
beginning of a line are considered to be part of the first field.
Fields are specified by the -k field1[,field2] argument. A missing field2 argument defaults to the end of a
line.
The arguments field1 and field2 have the form m.n followed by one or more of the options -b, -d, -f, -i, -n,
-r. A field1 position specified by m.n (m,n > 0) is interpreted as the nth character in the mth field. A missing .n in field1 means indicating the first character of the , field; If the -b option is in effect, n is counted
from the first non-blank character in the mth field; m.1b refers to the first non-blank character in the mth
field.
A field2 position specified by m.n is interpreted as the nth character (including separators) of the mth field.
A missing .n indicates the last character of the mth field; m = 0 designates the end of a line. Thus the
option -k v.x,w.y is synonymous with the obsolescent option +v-1.x-1 -w-1.y; when y is omitted, -k v.x,w
is synonymous with +v-1.x-1 -w+1.0. The obsolescent +pos1 -pos2 option is still supported, except for
-w.0b, which has no -k equivalent.
FILES

/tmp/sort.
Default temporary directories. output#PID
if output already exists.

Temporary name for output

SEE ALSO

sort(1), comm(1), uniq(1), join(1)


RETURN VALUES

Sort exits with one of the following values: 0:


with the -c option 2: an error occurred.

normal behavior. 1:

on disorder (or non-uniqueness)

BUGS

Lines longer than 65522 characters are discarded and processing continues. To sort files larger than 60Mb,
use sort -H; files larger than 704Mb must be sorted in smaller pieces, then merged. To protect data sort -o
calls link and unlink, and thus fails in protected directories.
ORIGIN

Sort includes software developed by the University of California, Berkeley and its contributors. Please see
the intro section for complete acknowledgements.
NOTES

The current sort command uses lexicographic radix sorting, which requires that sort keys be kept in
memory (as opposed to previous versions which used quick and merge sorts and did not.) Thus performance depends highly on efficient choice of sort keys, and the -b option and the field2 argument of the -k
option should be used whenever possible. Similarly, sort -k1f is equivalent to sort -f and may take twice as
long.

SunOS 5.8

Last change: NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

split ( 1 )

NAME

split - split a file into pieces


SYNOPSIS

split [-b byte_count[km]] [-l line_count] [file [name]]


DESCRIPTION

The split utility reads the given file (or standard input if no file is specified) and breaks it up into files of
1000 lines each.
OPTIONS

The options are as follows:


-b

Create smaller files byte_count bytes in length. If k is appended to the number, the file is split
into byte_count kilobyte pieces. If m is appended to the number, the file is split into
byte_count megabyte pieces.

-l

Create smaller files n lines in length.

If additional arguments are specified, the first is used as the name of the input file which is to be split. If a
second additional argument is specified, it is used as a prefix for the names of the files into which the file is
split. In this case, each file into which the file is split is named by the prefix followed by a lexically ordered
suffix in the range of aa-zz.
If the name argument is not specified, the file is split into lexically ordered files named in the range of
xaa-zzz.
BUGS

For historical reasons, if you specify name, split can only create 676 separate files. The default naming
convention allows 2028 separate files.
ORIGIN

Split includes software developed by the University of California, Berkeley and its contributors. Please see
the intro section for complete acknowledgements.

SunOS 5.8

Last change: NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

strings(1)

strings(1)

NAME
strings - find printable strings in a file

SYNOPSIS
strings [-afo] [-n number] [file ...]

DESCRIPTION
Strings displays the sequences of printable characters in each of the specified files, or in the standard input,
by default. By default, a sequence must be at least four characters in length before being displayed.
The options are as follows:
-a

By default, strings only searches the text and data segments of object files. The -a option causes
strings to search the entire object file.

-f

Each string is preceded by the name of the file in which it was found.

-n

Specifies the minimum number of characters in a sequence to be


number, instead of four.

-o

Each string is preceded by its decimal offset in the file.

Strings is useful for identifying random binaries, among other things.

SEE ALSO
hexdump(1)

BUGS
The algorithm for identifying strings is extremely primitive. In particular, machine code instructions on
certain architectures can resemble sequences of ASCII bytes, which will fool the algorithm.

NOTES
Since strings works in a multi platform environment, it can not recognize all types of executable files. Consequently the -a option is always assumed to be turned on. This may be fixed in the future. Strings includes
software developed by the University of California, Berkeley and its contributors. Please see the intro section for complete acknowledgements.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

su ( 1 )

NAME

su substitute user identity


SYNOPSIS

su [-flm] [login [args ... ]]


DESCRIPTION

Su requests the password for login (or for root, if no login is provided), and switches to that user and group
ID and then executes the Network Shell nsh. If su is executed by root, no password is requested and the
Network Shell with the appropriate user ID is executed
By default, the environment is unmodified with the exception of USER, HOME, and SHELL. HOME and
SHELL are set to the target logins default values. USER is set to the target login, unless the target login
has a user ID of 0, in which case it is unmodified. The invoked shell is the target logins. This is the traditional behavior of su.
The options are as follows:
-f

This flag is used in confunction with the csh which of course we are not running. This option is
accepted for compatability reasons and is ignored.

-l or -

Simulate a full login. The environment is discarded except for HOME, SHELL, PATH, TERM,
and USER. HOME and SHELL are modified as above. USER is set to the target login. PATH is
set to /usr/sbin/usr/bin on Solaris hosts, /usr/sbin:/usr/bin on HPUX hosts,
/usr/ucb:/bin:/usr/bin on Sun OS hosts, and TERM is imported from your current environment.
The invoked shell is the Network Shell nsh, and su will change directory to the target logins
home directory.

-m

Leave the environment unmodified. The Network Shell is started and no directory or environment variable changes are made.

The -l and -m options are mutually exclusive; the last one specified overrides any previous ones.
By default (unless the prompt is reset by a startup file) the super-user prompt is set to # to remind one of
its awesome power.
SEE ALSO

nsh(1), login(1)
ENVIRONMENT

Environment variables used by su:


HOME

Default home directory of real user ID unless modified as specified above.

PATH

Default search path of real user ID unless modified as specified above.

TERM

Provides terminal type which may be retained for the substituted user ID.

USER

The user ID is always the effective ID (the target user ID) after an su unless the user ID is 0
(root).

SunOS 5.8

Last change: NSH

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

TAIL (1)

TAIL (1)

NAME
tail display the last part of a file
SYNOPSIS
tail [ f | r] [ b number | c number | n number | number] [file . . .]
DESCRIPTION
The tail utility displays the contents of file or, by default, its standard input, to the standard output.
The display begins at a byte, line, or 512-byte block location in the input. Numbers having a leading plus
( + ) sign are relative to the beginning of the input, for example, -c +2 starts the display at the second
byte of the input. Numbers having a leading minus ( - ) sign or no explicit sign are relative to the end of
the input, for example, -n 2 displays the last two lines of the input. The default starting location is -n 10,
or the last 10 lines of the input.
The options are as follows:
b number
The location is number 512-byte blocks.
c number
The location is number bytes.
n number | number
The location is number lines.
f

Do not stop when end-of-file is reached, but rather to wait for additional data to be appended to the
input. If the file is replaced (i.e., the inode number changes), tail will reopen the file and continue. If the file is truncated, tail will reset its position to the beginning. This makes tail more
useful for watching log files that may get rotated. The f option is ignored if the standard input is a
pipe, but not if it is a FIFO.

The r option causes the input to be displayed in reverse order, by line. Additionally, this option
changes the meaning of the b, c, and n options. When the r option is specified, these
options specify the number of bytes, lines or 512-byte blocks to display, instead of the bytes, lines,
or blocks from the beginning or end of the input from which to begin the display. The default for
the r option is to display all of the input.

If more than a single file is specified, each file is preceded by a header consisting of the string ==> XXX
<== where XXX is the name of the file.
The tail utility exits 0 on success or >0 if an error occurred.
EXAMPLES
To display the last 500 lines of the file foo:
$ tail -500 foo
Keep /var/log/messages open, displaying to the standard output anything appended to the file:
$ tail -f /var/log/messages
SEE ALSO
cat(1), head(1), sed(1)

BSD

June 6, 1993

TAIL (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

TAIL (1)

STANDARDS
The tail utility is expected to be a superset of the IEEE Std 1003.2-1992 (POSIX.2) specification. In particular, the b and r options are extensions to that standard.
The historic command line syntax of tail is supported by this implementation. The only difference
between this implementation and historic versions of tail, once the command line syntax translation has
been done, is that the b, c and n options modify the r option, i.e., -r -c 4 displays the last 4 characters of the last line of the input, while the historic tail (using the historic syntax -4cr) would ignore the
c option and display the last 4 lines of the input.
HISTORY
A tail command appeared in Version 7 AT&T UNIX.

BSD

June 6, 1993

Property of BladeLogic, Inc.


Strictly confidential and proprietary

tee(1)

tee(1)

NAME
tee Pipe fitting

SYNOPSIS
tee [-ai?] [file ...]

DESCRIPTION
The tee utility copies the standard input to standard output, making copies of the input to the optionally
named files.

OPTIONS
The following options may modify the behavior of tee.
-a

Append the output to the files rather than overwriting them.

-i

This option causes tee to ignore the SIGINT signal.

EXAMPLE
The first example takes the output from the program someprog and appends it to the file messages creating the file if it does not already exist. The second example copies the file /etc/motd to the hosts
ottawa and washington.
$ someprog | tee -a messages
$ cat /etc/motd | tee //ottawa/etc/motd //washington/etc/motd

DIAGNOSTICS
tee: Unable to access file filename
Error creating or trying to append to one of the name files.
tee: Write error to file filename
An error occurred updating (writing) to one of the files.

EXIT CODES
0

No errors detected

An unknown option was given

Was not able to create or able to write to one the files.

255

Unable to get a license to use the software.

ORIGIN
Tee includes software developed by the University of California, Berkeley and its contributors. Please see
the intro section for complete acknowledgments.

SEE ALSO
tee(1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

test(1)

test(1)

NAME
test Test value of expression

SYNOPSIS
test expression

DESCRIPTION
The test command tests the value of the given expression and exits with an appropriate exit code to indicate
if the expression was TRUE or FALSE. In the sh(1) family of command interpreters, an exit code of 0 indicates a value of TRUE, while a non zero exit code indicates a value of FALSE.

OPTIONS
You can build an expression from any combination of the following primitives.
-b file

TRUE if file is a block special device.

-c file

TRUE if file is a character special device.

-d file

TRUE if file is a directory.

-f file.

TRUE if file is not a directory (P_BSD).

-f file

TRUE if file is a regular file (P_ATT).

-g file

TRUE if file has its set-GID bit set.

-h file

TRUE if file is a symbolic link.

-k file

TRUE if file has its sticky bit set.

-l string

The length of string.

-n string

TRUE if length of strings is not zero.

-p file

TRUE if file is a named pipe (FIFO).

-r file

TRUE if file is readable.

-s file

TRUE if file is greater than 0 bytes large.

-t fd

TRUE if file descriptor is associated with a tty.

-u file

TRUE if file has its set-UID bit set.

-w file

TRUE if file is writable.

-x file

TRUE if file is executable.

-z string

TRUE if length of strings is zero.

s1 = s2

TRUE if strings s1 and s2 are equal.

s1 != s2

TRUE if strings s1 and s2 are not equal.

n1 -eq n2

TRUE if integers n1 and n2 are equal.

n1 -ne n2

TRUE if integers n1 and n2 are not equal.

n1 -gt n2

TRUE if integer n1 is greater than integer n2.

n1 -ge n2

TRUE if integer n1 is greater than or equal to integer n2.

n1 -lt n2

TRUE if integer n1 is less than integer n2.

n1 -le n2

TRUE if integer n1 is less than or equal to integer n2.

Unary negation operator.

-a

Binary and operator.

-o

Binary or operator.

(expr)

Parentheses for grouping.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

test(1)

-?

test(1)

Output a brief summary of available options and then exit with a zero status
without doing any testing.

The -a (binary AND) operator has a higher precedence than the -o (binary OR) operator, which in turn has
a higher precedence than the ! (negation) operator. You can use parentheses to group operators so that they
are evaluated in the order you want.

EXAMPLE
The first example would return TRUE if both the files /etc/passwd and /etc/group exist on host
bonn. The second example would return TRUE if either one of the files /etc/passwd or /etc/group
exists, and the directory /etc/security exists.
$ test -f //bonn/etc/passwd -a -f //bonn/etc/group
$ test -f \( /etc/passwd -o -f /etc/group \) -a -d /etc/security

DIAGNOSTICS
test: argument expected
This message is output if a primitive of the expression is missing an operand.

EXIT CODES
0

Value of the expression is TRUE.

Value of the expression is FALSE.

An operand of a primitive was missing.

255

Unable to get a license to use the software.

CAVEATS
Parentheses, which can be used for grouping primitives, also have special meaning to the sh(1). Consequently you must escape or quote them, so as not to have them interpreted by sh(1).
The sh(1) counterpart test(1) is a built in function to the shell and a separate executable program for it does
not exist. test is an executable program.

UNIVERSE BEHAVIOR
With the P_BSD variable set (Berkeley behavior), the -f primitive checks if the file is not a directory. With
the P_ATT variable set, the -f primitive check that the file is a regular file.
The difference is that a special file such as a character special file is neither a directory nor a regular file.
Consequently the primitive -f <character_special_file> will produce different values in the two universes.

ORIGIN
test was written by Thomas Kraus

NSH

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

TOUCH (1)

TOUCH (1)

NAME
touch change file access and modification times
SYNOPSIS
touch [ acfm] [ r file] [ t [[CC]YY]MMDDhhmm[.SS]] file [ . . .]
DESCRIPTION
The touch utility sets the modification and access times of files to the current time of day. If the file
doesnt exist, it is created with default permissions.
The options are as follows:
a

Change the access time of the file. The modification time of the file is not changed unless the m
flag is also specified.

Do not create the file if it does not exist. The touch utility does not treat this as an error. No error
messages are displayed and the exit value is not affected.

Attempt to force the update, even if the file permissions do not currently permit it.

Change the modification time of the file. The access time of the file is not changed unless the a
flag is also specified.

Use the access and modification times from the specified file instead of the current time of day.

Change the access and modification times to the specified time. The argument should be in the form
[[CC]YY]MMDDhhmm[.SS] where each pair of letters represents the following:
CC
YY
MM
DD
hh
mm
SS

The first two digits of the year (the century).


The second two digits of the year. If YY is specified, but CC is not, a value for
YY between 69 and 99 results in a CC value of 19. Otherwise, a CC value of
20 is used.
The month of the year, from 1 to 12.
The day of the month, from 1 to 31.
The hour of the day, from 0 to 23.
The minute of the hour, from 0 to 59.
The second of the minute, from 0 to 61.

If the CC and YY letter pairs are not specified, the values default to the current year. If the
SS letter pair is not specified, the value defaults to 0.
The touch utility exits 0 on success or >0 if an error occurred.
SEE ALSO
utimes(2)
STANDARDS
The obsolescent form of touch, where a time format is specified as the first argument, is supported. When
no r or t option is specified, there are at least two arguments, and the first argument is a string of digits
either eight or ten characters in length, the first argument is interpreted as a time specification of the form
MMDDhhmm[YY].
The MM, DD, hh and mm letter pairs are treated as their counterparts specified to the t option. If
the YY letter pair is in the range 69 to 99, the year is set from 1969 to 1999; otherwise, the year is set in
the 21st century.

BSD

April 28, 1995

TOUCH (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

TOUCH (1)

The touch utility is expected to be a superset of the IEEE Std 1003.2 (POSIX.2) specification.
HISTORY
A touch utility appeared in Version 7 AT&T UNIX.

BSD

April 28, 1995

Property
of Reference
BladeLogic,
Inc.
BSD
Manual
Strictly confidential and proprietary

TR ( 1 )

TR ( 1 )

NAME
tr Translate Characters.
SYNOPSIS
tr [ cs] string1 string2
tr [ c] d string1
tr [ c] s string1
tr [ c] ds string1 string2
DESCRIPTION
The tr utility copies the standard input to the standard output with substitution or deletion of selected characters.
The following options are available:
c

Complements the set of characters in string1, that is -c ab includes every character except for
a and b.

The d option causes characters to be deleted from the input.

The s option squeezes multiple occurrences of the characters listed in the last operand (either
string1 or string2) in the input into a single instance of the character. This occurs after all
deletion and translation is completed.

In the first synopsis form, the characters in string1 are translated into the characters in string2 where
the first character in string1 is translated into the first character in string2 and so on. If string1 is
longer than string2, the last character found in string2 is duplicated until string1 is exhausted.
In the second synopsis form, the characters in string1 are deleted from the input.
In the third synopsis form, the characters in string1 are compressed as described for the s option.
In the fourth synopsis form, the characters in string1 are deleted from the input, and the characters in
string2 are compressed as described for the s option.
The following conventions can be used in string1 and string2 to specify sets of characters:
character

Any character not described by one of the following conventions represents itself.

\octal

A backslash followed by 1, 2 or 3 octal digits represents a character with that encoded value.
To follow an octal sequence with a digit as a character, left zero-pad the octal sequence to the
full 3 octal digits.

\character

A backslash followed by certain special characters maps to special values.


\a
\b
\f
\n
\r
\t
\v

<alert character>
<backspace>
<form-feed>
<newline>
<carriage return>
<tab>
<vertical tab>

A backslash followed by any other character maps to that character.

Shpink

October 27, 1991

Property
of Reference
BladeLogic,
Inc.
BSD
Manual
Strictly confidential and proprietary

TR ( 1 )

c-c

Represents the range of characters between the range endpoints, inclusively.

[:class:]

Represents all characters belonging to the defined character class. Class names are:
alnum
alpha
cntrl
digit
graph
lower
print
punct
space
upper
xdigit

TR ( 1 )

<alphanumeric characters>
<alphabetic characters>
<control characters>
<numeric characters>
<graphic characters>
<lower-case alphabetic characters>
<printable characters>
<punctuation characters>
<space characters>
<upper-case characters>
<hexadecimal characters>

With the exception of the upper and lower classes, characters in the classes are in
unspecified order. In the upper and lower classes, characters are entered in ascending
order.
For specific information as to which ASCII characters are included in these classes, see
ctype(3) and related manual pages.
[=equiv=]

Represents all characters or collating (sorting) elements belonging to the same equivalence
class as equiv. If there is a secondary ordering within the equivalence class, the characters
are ordered in ascending sequence. Otherwise, they are ordered after their encoded values. An
example of an equivalence class might be c and ch in Spanish; English has no
equivalence classes.

[#n]

Represents n repeated occurrences of the character represented by #. This expression is only


valid when it occurs in string2. If n is omitted or is zero, it is be interpreted as large
enough to extend string2 sequence to the length of string1. If n has a leading zero, it is
interpreted as an octal value, otherwise, its interpreted as a decimal value.

The tr utility exits 0 on success, and >0 if an error occurs.


EXAMPLES
The following examples are shown as given to the shell:
Create a list of the words in file1, one per line, where a word is taken to be a maximal string of letters.
tr -cs

[:alpha:]" "\n" < file1"

Translate the contents of file1 to upper-case.


tr

[:lower:]" "[:upper:]" < file1"

Strip out non-printable characters from file1.


tr -cd

[:print:]" < file1"

COMPATIBILITY
System V has historically implemented character ranges using the syntax [c-c] instead of the c-c used
by historic BSD implementations and standardized by POSIX. System V shell scripts should work under
this implementation as long as the range is intended to map in another range, i.e. the command tr [a-z] [A-

Shpink

October 27, 1991

TR ( 1 )

Property
of Reference
BladeLogic,
Inc.
BSD
Manual
Strictly confidential and proprietary

TR ( 1 )

Z] will work as it will map the [ character in string1 to the [ character in string2. However, if
the shell script is deleting or squeezing characters as in the command tr -d [a-z], the characters [ and
] will be included in the deletion or compression list which would not have happened under an historic
System V implementation. Additionally, any scripts that depended on the sequence a-z to represent the
three characters a, - and z will have to be rewritten as a\-z.
The tr utility has historically not permitted the manipulation of NUL bytes in its input and, additionally,
stripped NULs from its input stream. This implementation has removed this behavior as a bug.
The tr utility has historically been extremely forgiving of syntax errors, for example, the c and s options were ignored unless two strings were specified. This implementation will not permit illegal syntax.
STANDARDS
The tr utility is expected to be IEEE Std1003.2 (POSIX) compatible. It should be noted that the feature
wherein the last character of string2 is duplicated if string2 has less characters than string1 is permitted by POSIX but is not required. Shell scripts attempting to be portable to other POSIX systems should
use the [#] convention instead of relying on this behavior.

Shpink

October 27, 1991

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

UNAME (1)

UNAME (1)

NAME
uname print operating system name
SYNOPSIS
uname [ amnprsv]
DESCRIPTION
The uname utility writes symbols representing one or more system characteristics to the standard output.
The options are as follows:
a

Behave as though all of the options mnrsv were specified.

Print the machine hardware name.

Print the nodename (the nodename may be a name that the system is known by to a communications
network).

Print the processor type in more detail.

Print the operating system release.

Print the operating system name.

Print the patch level.

Print the operating system version.

If no options are specified, uname prints the operating system name as if the s option had been specified.
SEE ALSO
hostname(1), machine(1), uname(3)
STANDARDS
The uname utility conforms to IEEE Std 1003.2-1992 (POSIX.2).
HISTORY
The uname command appeared in 4.4 BSD.

BSD

January 26, 1994

Property of BladeLogic, Inc.


Strictly confidential and proprietary

uncp(1)

uncp(1)

NAME
uncp Uncopy files backed up during a cp or dsync

SYNOPSIS
uncp [-dnv] [-s suf] file1 ...

DESCRIPTION
The cp and dsync commands have an option (-b or -B) that lets you back up the target file (if it exists)
before the new source file is copied into its place. The backup is done by renaming the target file with a suffix. The default suffix is (foo -> foo).
The uncp command is a mechanism to restore the saved files to their previous state by renaming them back
to their original name (foo -> foo). uncp does not rename directories as it will automatically recursively
travel through the directories passed to it as arguments.

OPTIONS
-d

Instead of restoring the files to their previous names, just delete the files. This is a useful option
when you want to remove any files that the dsync or cp commands previously backed up.

-n

Do not actually make any changes. This option automatically turns on the verbose flag -v and just
lists the renames it would perform if you had not turned on the -n option. It does not rename any
files.

-v

Output a message for each file being renamed.

-s suf

Set the suffix to suf. By default, uncp looks for the suffix . This option tells it to look for a different suffix. When uncp finds files with the specified suffix, it renames them (removes the suffix).

ORIGIN
uncp was written by Thomas Kraus.

SEE ALSO
cp(1), dsync(1).

NSH

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

UNIQ (1)

UNIQ (1)

NAME
uniq report or filter out repeated lines in a file
SYNOPSIS
uniq [ c | d | u] [ f fields] [ s chars] [input_file [output_file]]
DESCRIPTION
The uniq utility reads the standard input comparing adjacent lines and writes a copy of each unique input
line to the standard output. The second and succeeding copies of identical adjacent input lines are not written. Repeated lines in the input will not be detected if they are not adjacent, so it may be necessary to sort
the files first.
The options are as follows:
c

Precede each output line with the count of the number of times the line occurred in the input, followed by a single space.

Only output lines which have duplicates.

f fields
Ignore the first fields in each input line when doing comparisons. A field is a string of non-blank
characters separated from adjacent fields by blanks. Field numbers are one based, i.e., the first field
is field one.
s chars
Ignore the first chars characters in each input line when doing comparisons. If specified in conjunction with the f option, the first chars characters after the first fields fields will be
ignored. Character numbers are one based, i.e., the first character is character one.
u

Only output lines which are unique.

If additional arguments are specified on the command line, the first such argument is used as the name of an
input file, the second is used as the name of an output file. A file name of - denotes the standard input or
the standard output ( depending on its position on the command line ) .
The uniq utility exits 0 on success or >0 if an error occurred.
SEE ALSO
sort(1)
STANDARDS
The historic +number and number options have been deprecated but are still supported in this implementation.
The uniq utility is expected to be IEEE Std 1003.2 (POSIX.2) compatible.

BSD

December 8, 2002

Property of BladeLogic, Inc.


Strictly confidential and proprietary

unlink(1)

unlink(1)

NAME
unlink Unlink a file and/or directory

SYNOPSIS
unlink [-?] file ...

DESCRIPTION
The unlink command is similar to the rm command, except that it does exactly what it is told to do, without doing any type of error checking. In other words, it unlinks the named files (which is the mechanism to
remove files) regardless of the state of the files.
We strongly suggest that you use the commands rm and rmdir instead of the unlink command, because
improper use may adversely affect the consistency of the file systems.

OPTIONS
-?

Output a brief summary of available options and then exit with a zero status without unlinking
any files.

file

File to be unlinked

EXAMPLE
The first example unlinks the file foo.bar The second example removes all .old files in the directory
/u1/data on host amsterdam.
$ unlink foo.bar
$ unlink //amsterdam/u1/data/*.old

DIAGNOSTICS
Since unlink errors are ignored, there are no diagnostic messages to be output except for network and
licensing messages.

EXIT CODES
0

Besides license problems, unlink always exits with 0.

255

Unable to get a license to use the software.

CAVEATS
Since unlink does not perform any error checking, you should use it only in exceptional cases. Normally,
you should use the rm command.

ORIGIN
unlink was written by Thomas Kraus

SEE ALSO
rm(1),

NOTES
By default, any user can run the unlink command. To restrict its use to the super user, change the ownership of the unlink file to root and the mode to 500.

NSH

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIP ( 1L )

NAME

unzip list, test and extract compressed files in a ZIP archive


SYNOPSIS

unzip [Z] [cflptuvz[abjnoqsCLMVX$/]] file[.zip] [file(s) . . .] [x xfile(s) . . .] [d exdir]


DESCRIPTION

unzip will list, test, or extract files from a ZIP archive, commonly found on MS-DOS systems. The default
behavior (with no options) is to extract into the current directory (and subdirectories below it) all files from
the specified ZIP archive. A companion program, zip(1L), creates ZIP archives; both programs are compatible with archives created by PKWAREs PKZIP and PKUNZIP for MS-DOS, but in many cases the program options or default behaviors differ.
ARGUMENTS

file[.zip]
Path of the ZIP archive(s). If the file specification is a wildcard, each matching file is processed in
an order determined by the operating system (or file system). Only the filename can be a wildcard;
the path itself cannot. Wildcard expressions are similar to Unix egrep(1) (regular) expressions and
may contain:

matches a sequence of 0 or more characters

matches exactly 1 character

[. . .]

matches any single character found inside the brackets; ranges are specified by a beginning character, a hyphen, and an ending character. If an exclamation point or a caret (!
or ) follows the left bracket, then the range of characters within the brackets is complemented (that is, anything except the characters inside the brackets is considered a match).

(Be sure to quote any character that might otherwise be interpreted or modified by the operating
system, particularly under Unix and VMS.) If no matches are found, the specification is assumed
to be a literal filename; and if that also fails, the suffix . z i p is appended. Note that selfextracting ZIP files are supported, as with any other ZIP archive; just specify the . e x e suffix (if
any) explicitly.
[file(s)] An optional list of archive members to be processed, separated by spaces. (VMS versions compiled with VMSCLI defined must delimit files with commas instead. See v in OPTIONS
below.) Regular expressions (wildcards) may be used to match multiple members; see above.
Again, be sure to quote expressions that would otherwise be expanded or modified by the operating system.
[x xfile(s)]
An optional list of archive members to be excluded from processing. Since wildcard characters
match directory separators (/), this option may be used to exclude any files that are in subdirectories. For example, u n z i p f o o . [ c h ] - x / would extract all C source files in the
main directory, but none in any subdirectories. Without the x option, all C source files in all
directories within the zipfile would be extracted.
[d exdir]
An optional directory to which to extract files. By default, all files and subdirectories are recreated
in the current directory; the d option allows extraction in an arbitrary directory (always assuming
one has permission to write to the directory). This option need not appear at the end of the command line; it is also accepted before the zipfile specification (with the normal options), immediately after the zipfile specification, or between the file(s) and the x option. The option and directory may be concatenated without any white space between them, but note that this may cause normal shell behavior to be suppressed. In particular, d (tilde) is expanded by Unix C shells
into the name of the users home directory, but d is treated as a literal subdirectory of
the current directory.

Info-ZIP

Last change: 14 January 2001 (v5.42)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIP ( 1L )

OPTIONS

Note that, in order to support obsolescent hardware, unzips usage screen is limited to 22 or 23 lines and
should therefore be considered only a reminder of the basic unzip syntax rather than an exhaustive list of all
possible flags. The exhaustive list follows:

Info-ZIP

zipinfo(1L) mode. If the first option on the command line is Z, the remaining options are taken to
be zipinfo(1L) options. See the appropriate manual page for a description of these options.

[OS/2, Unix DLL] print extended help for the DLLs programming interface (API).

extract files to stdout/screen (CRT). This option is similar to the p option except that the
name of each file is printed as it is extracted, the a option is allowed, and ASCII-EBCDIC
conversion is automatically performed if appropriate. This option is not listed in the unzip usage
screen.

freshen existing files, i.e., extract only those files that already exist on disk and that are newer than
the disk copies. By default unzip queries before overwriting, but the o option may be used to
suppress the queries. Note that under many operating systems, the TZ (timezone) environment
variable must be set correctly in order for f and u to work properly (under Unix the variable is
usually set automatically). The reasons for this are somewhat subtle but have to do with the
differences between DOS-format file times (always local time) and Unix-format times (always in
GMT/UTC) and the necessity to compare the two. A typical TZ value is PST8PDT (US Pacific
time with automatic adjustment for Daylight Savings Time or summer time).

list archive files (short format). The names, uncompressed file sizes and modification dates and
times of the specified files are printed, along with totals for all files specified. If UnZip was compiled with OS2_EAS defined, the l option also lists columns for the sizes of stored OS/2 extended
attributes (EAs) and OS/2 access control lists (ACLs). In addition, the zipfile comment and individual file comments (if any) are displayed. If a file was archived from a single-case file system (for
example, the old MS-DOS FAT file system) and the L option was given, the filename is converted to lowercase and is prefixed with a caret ().

extract files to pipe (stdout). Nothing but the file data is sent to stdout, and the files are always
extracted in binary format, just as they are stored (no conversions).

test archive files. This option extracts each specified file in memory and compares the CRC
(cyclic redundancy check, an enhanced checksum) of the expanded file with the original files
stored CRC value.

[most OSes] set the timestamp on the archive(s) to that of the newest file in each one. This
corresponds to zips go option except that it can be used on wildcard zipfiles (e.g., unzip T
\.zip) and is much faster.

update existing files and create new ones if needed. This option performs the same function as the
f option, extracting (with query) files that are newer than those with the same name on disk, and
in addition it extracts those files that do not already exist on disk. See f above for information on
setting the timezone properly.

be verbose or print diagnostic version info. This option has evolved and now behaves as both an
option and a modifier. As an option it has two purposes: when a zipfile is specified with no other
options, v lists archive files verbosely, adding to the basic l info the compression method,
compressed size, compression ratio and 32-bit CRC. When no zipfile is specified (that is, the complete command is simply unzip v), a diagnostic screen is printed. In addition to the normal
header with release date and version, unzip lists the home Info-ZIP ftp site and where to find a list
of other ftp and non-ftp sites; the target operating system for which it was compiled, as well as
(possibly) the hardware on which it was compiled, the compiler and version used, and the compilation date; any special compilation options that might affect the programs operation (see also
DECRYPTION below); and any options stored in environment variables that might do the same
(see ENVIRONMENT OPTIONS below). As a modifier it works in conjunction with other

Last change: 14 January 2001 (v5.42)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIP ( 1L )

options (e.g., t) to produce more verbose or debugging output; this is not yet fully implemented
but will be in future releases.
z

display only the archive comment.

MODIFIERS

Info-ZIP

convert text files. Ordinarily all files are extracted exactly as they are stored (as binary files).
The a option causes files identified by zip as text files (those with the t label in zipinfo listings,
rather than b) to be automatically extracted as such, converting line endings, end-of-file characters and the character set itself as necessary. (For example, Unix files use line feeds (LFs) for
end-of-line (EOL) and have no end-of-file (EOF) marker; Macintoshes use carriage returns (CRs)
for EOLs; and most PC operating systems use CR+LF for EOLs and control-Z for EOF. In addition, IBM mainframes and the Michigan Terminal System use EBCDIC rather than the more common ASCII character set, and NT supports Unicode.) Note that zips identification of text files is
by no means perfect; some text files may actually be binary and vice versa. unzip therefore
prints [text] or [binary] as a visual check for each file it extracts when using the a
option. The aa option forces all files to be extracted as text, regardless of the supposed file type.

[general] treat all files as binary (no text conversions). This is a shortcut for a.

[Tandem] force the creation files with filecode type 180 (C) when extracting Zip entries marked
as "text". (On Tandem, a is enabled by default, see above).

[VMS] auto-convert binary files (see a above) to fixed-length, 512-byte record format. Doubling
the option (bb) forces all files to be extracted in this format.

[Unix only, and only if compiled with UNIXBACKUP defined] save a backup copy of each
overwritten file with a tilde appended (e.g., the old copy of foo is renamed to foo~). This
is similar to the default behavior of emacs(1) in many locations.

match filenames case-insensitively. unzips philosophy is you get what you ask for (this is also
responsible for the L/U change; see the relevant options below). Because some file systems are
fully case-sensitive (notably those under the Unix operating system) and because both ZIP
archives and unzip itself are portable across platforms, unzips default behavior is to match both
wildcard and literal filenames case-sensitively. That is, specifying makefile on the command line will only match makefile in the archive, not Makefile or MAKEFILE (and
similarly for wildcard specifications). Since this does not correspond to the behavior of many
other operating/file systems (for example, OS/2 HPFS, which preserves mixed case but is not sensitive to it), the C option may be used to force all filename matches to be case-insensitive. In the
example above, all three files would then match makefile (or make, or similar). The
C option affects files in both the normal file list and the excluded-file list (xlist).

[MacOS only] display contents of MacOS extra field during restore operation.

[Acorn only] suppress removal of NFS filetype extension from stored filenames.

[Unix only, and only if compiled with ACORN_FTYPE_NFS defined] translate filetype information from ACORN RISC OS extra field blocks into a NFS filetype extension and append it to the
names of the extracted files. (When the stored filename appears to already have an appended NFS
filetype extension, it is replaced by the info from the extra field.)

[MacOS only] ignore filenames stored in MacOS extra fields. Instead, the most compatible
filename stored in the generic part of the entrys header is used.

junk paths. The archives directory structure is not recreated; all files are deposited in the extraction directory (by default, the current one).

[BeOS only] junk file attributes. The files BeOS file attributes are not restored, just the files data.

[MacOS only] ignore MacOS extra fields. All Macintosh specific info is skipped. Data-fork and
resource-fork are restored as separate files.

Last change: 14 January 2001 (v5.42)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIP ( 1L )

convert to lowercase any filename originating on an uppercase-only operating system or file system. (This was unzips default behavior in releases prior to 5.11; the new default behavior is
identical to the old behavior with the U option, which is now obsolete and will be removed in a
future release.) Depending on the archiver, files archived under single-case file systems (VMS,
old MS-DOS FAT, etc.) may be stored as all-uppercase names; this can be ugly or inconvenient
when extracting to a case-preserving file system such as OS/2 HPFS or a case-sensitive one such
as under Unix. By default unzip lists and extracts such filenames exactly as theyre stored (excepting truncation, conversion of unsupported characters, etc.); this option causes the names of all files
from certain systems to be converted to lowercase. The LL option forces conversion of every
filename to lowercase, regardless of the originating file system.

pipe all output through an internal pager similar to the Unixmore(1) command. At the end of a
screenful of output, unzip pauses with a More prompt; the next screenful may be viewed
by pressing the Enter (Return) key or the space bar. unzip can be terminated by pressing the q
key and, on some systems, the Enter/Return key. Unlike Unix more(1), there is no forwardsearching or editing capability. Also, unzip doesnt notice if long lines wrap at the edge of the
screen, effectively resulting in the printing of two or more lines and the likelihood that some text
will scroll off the top of the screen before being viewed. On some systems the number of available
lines on the screen is not detected, in which case unzip assumes the height is 24 lines.

never overwrite existing files. If a file already exists, skip the extraction of that file without
prompting. By default unzip queries before extracting any file that already exists; the user may
choose to overwrite only the current file, overwrite all files, skip extraction of the current file, skip
extraction of all existing files, or rename the current file.

[Amiga] extract file comments as Amiga filenotes. File comments are created with the c option
of zip(1L), or with the N option of the Amiga port of zip(1L), which stores filenotes as comments.

overwrite existing files without prompting. This is a dangerous option, so use it with care. (It is
often used with f, however, and is the only way to overwrite directory EAs under OS/2.)

P password
use password to decrypt encrypted zipfile entries (if any). THIS IS INSECURE! Many multiuser operating systems provide ways for any user to see the current command line of any other
user; even on stand-alone systems there is always the threat of over-the-shoulder peeking. Storing
the plaintext password as part of a command line in an automated script is even worse. Whenever
possible, use the non-echoing, interactive prompt to enter passwords. (And where security is truly
important, use strong encryption such as Pretty Good Privacy instead of the relatively weak
encryption provided by standard zipfile utilities.)

Info-ZIP

perform operations quietly (qq = even quieter). Ordinarily unzip prints the names of the files its
extracting or testing, the extraction methods, any file or zipfile comments that may be stored in the
archive, and possibly a summary when finished with each archive. The q[q] options suppress the
printing of some or all of these messages.

[OS/2, NT, MS-DOS] convert spaces in filenames to underscores. Since all PC operating systems
allow spaces in filenames, unzip by default extracts filenames with spaces intact (e.g.,
EA DATA. SF). This can be awkward, however, since MS-DOS in particular does not gracefully support spaces in filenames. Conversion of spaces to underscores can eliminate the awkwardness in some cases.

(obsolete; to be removed in a future release) leave filenames uppercase if created under MS-DOS,
VMS, etc. See L above.

retain (VMS) file version numbers. VMS files can be stored with a version number, in the format
file.ext;##. By default the ;## version numbers are stripped, but this option allows them
to be retained. (On file systems that limit filenames to particularly short lengths, the version
numbers may be truncated or stripped regardless of this option.)

Last change: 14 January 2001 (v5.42)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIP ( 1L )

[VMS, Unix, OS/2, NT] restore owner/protection info (UICs) under VMS, or user and group info
(UID/GID) under Unix, or access control lists (ACLs) under certain network-enabled versions of
OS/2 (Warp Server with IBM LAN Server/Requester 3.0 to 5.0; Warp Connect with IBM Peer
1.0), or security ACLs under Windows NT. In most cases this will require special system
privileges, and doubling the option (XX) under NT instructs unzip to use privileges for extraction; but under Unix, for example, a user who belongs to several groups can restore files owned by
any of those groups, as long as the user IDs match his or her own. Note that ordinary file attributes are always restored--this option applies only to optional, extra ownership info available on
some operating systems. [NTs access control lists do not appear to be especially compatible with
OS/2s, so no attempt is made at cross-platform portability of access privileges. It is not clear
under what conditions this would ever be useful anyway.]

[MS-DOS, OS/2, NT] restore the volume label if the extraction medium is removable (e.g., a
diskette). Doubling the option ($$) allows fixed media (hard disks) to be labelled as well. By
default, volume labels are ignored.

/ extensions
[Acorn only] overrides the extension list supplied by Unzip$Ext environment variable. During
extraction, filename extensions that match one of the items in this extension list are swapped in
front of the base name of the extracted file.
ENVIRONMENT OPTIONS

unzips default behavior may be modified via options placed in an environment variable. This can be done
with any option, but it is probably most useful with the a, L, C, q, o, or n modifiers: make unzip
auto-convert text files by default, make it convert filenames from uppercase systems to lowercase, make it
match names case-insensitively, make it quieter, or make it always overwrite or never overwrite files as it
extracts them. For example, to make unzip act as quietly as possible, only reporting errors, one would use
one of the following commands:
UNZIP=qq; export UNZIP
setenv UNZIP qq
set UNZIP=qq
define UNZIP_OPTS "qq"

Unix Bourne shell


Unix C shell
OS/2 or MS-DOS
VMS (quotes for lowercase)

Environment options are, in effect, considered to be just like any other command-line options, except that
they are effectively the first options on the command line. To override an environment option, one may use
the minus operator to remove it. For instance, to override one of the quiet-flags in the example above,
use the command
unzip q[other options] zipfile
The first hyphen is the normal switch character, and the second is a minus sign, acting on the q option.
Thus the effect here is to cancel one quantum of quietness. To cancel both quiet flags, two (or more)
minuses may be used:
unzip tq zipfile
unzip qt zipfile
(the two are equivalent). This may seem awkward or confusing, but it is reasonably intuitive: just ignore
the first hyphen and go from there. It is also consistent with the behavior of Unix nice(1).
As suggested by the examples above, the default variable names are UNZIP_OPTS for VMS (where the
symbol used to install unzip as a foreign command would otherwise be confused with the environment variable), and UNZIP for all other operating systems. For compatibility with zip(1L), UNZIPOPT is also
accepted (dont ask). If both UNZIP and UNZIPOPT are defined, however, UNZIP takes precedence.
unzips diagnostic option (v with no zipfile name) can be used to check the values of all four possible
unzip and zipinfo environment variables.

Info-ZIP

Last change: 14 January 2001 (v5.42)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIP ( 1L )

The timezone variable (TZ) should be set according to the local timezone in order for the f and u to
operate correctly. See the description of f above for details. This variable may also be necessary in order
for timestamps on extracted files to be set correctly. Under Windows 95/NT unzip should know the correct
timezone even if TZ is unset, assuming the timezone is correctly set in the Control Panel.
DECRYPTION

Encrypted archives are fully supported by Info-ZIP software, but due to United States export restrictions,
de-/encryption support might be disabled in your compiled binary. However, since spring 2000, US export
restrictions have been liberated, and our source archives do now include full crypt code. In case you need
binary distributions with crypt support enabled, see the file WHERE in any Info-ZIP source or binary
distribution for locations both inside and outside the US.
Some compiled versions of unzip may not support decryption. To check a version for crypt support, either
attempt to test or extract an encrypted archive, or else check unzips diagnostic screen (see the v option
above) for [decryption] as one of the special compilation options.
As noted above, the P option may be used to supply a password on the command line, but at a cost in
security. The preferred decryption method is simply to extract normally; if a zipfile member is encrypted,
unzip will prompt for the password without echoing what is typed. unzip continues to use the same password as long as it appears to be valid, by testing a 12-byte header on each file. The correct password will
always check out against the header, but there is a 1-in-256 chance that an incorrect password will as well.
(This is a security feature of the PKWARE zipfile format; it helps prevent brute-force attacks that might
otherwise gain a large speed advantage by testing only the header.) In the case that an incorrect password is
given but it passes the header test anyway, either an incorrect CRC will be generated for the extracted data
or else unzip will fail during the extraction because the decrypted bytes do not constitute a valid
compressed data stream.
If the first password fails the header check on some file, unzip will prompt for another password, and so on
until all files are extracted. If a password is not known, entering a null password (that is, just a carriage
return or Enter) is taken as a signal to skip all further prompting. Only unencrypted files in the
archive(s) will thereafter be extracted. (In fact, thats not quite true; older versions of zip(1L) and
zipcloak(1L) allowed null passwords, so unzip checks each encrypted file to see if the null password works.
This may result in false positives and extraction errors, as noted above.)
Archives encrypted with 8-bit passwords (for example, passwords with accented European characters) may
not be portable across systems and/or other archivers. This problem stems from the use of multiple encoding methods for such characters, including Latin-1 (ISO 8859-1) and OEM code page 850. DOS PKZIP
2.04g uses the OEM code page; Windows PKZIP 2.50 uses Latin-1 (and is therefore incompatible with
DOS PKZIP); Info-ZIP uses the OEM code page on DOS, OS/2 and Win3.x ports but Latin-1 everywhere
else; and Nico Maks WinZip 6.x does not allow 8-bit passwords at all. UnZip 5.3 attempts to use the
default character set first (e.g., Latin-1), followed by the alternate one (e.g., OEM code page) to test passwords. On EBCDIC systems, if both of these fail, EBCDIC encoding will be tested as a last resort. (Since
there are no known archivers that encrypt using EBCDIC encoding, EBCDIC is not tested on non-EBCDIC
systems.) ISO character encodings other than Latin-1 are not supported.
EXAMPLES

To use unzip to extract all members of the archive letters.zip into the current directory and subdirectories
below it, creating any subdirectories as necessary:
unzip letters
To extract all members of letters.zip into the current directory only:
unzip -j letters
To test letters.zip, printing only a summary message indicating whether the archive is OK or not:
unzip -tq letters

Info-ZIP

Last change: 14 January 2001 (v5.42)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIP ( 1L )

To test all zipfiles in the current directory, printing only the summaries:
unzip -tq \.zip
(The backslash before the asterisk is only required if the shell expands wildcards, as in Unix; double quotes
could have been used instead, as in the source examples below.) To extract to standard output all members
of letters.zip whose names end in .tex, auto-converting to the local end-of-line convention and piping the
output into more(1):
unzip ca letters \.tex | more
To extract the binary file paper1.dvi to standard output and pipe it to a printing program:
unzip p articles paper1.dvi | dvips
To extract all FORTRAN and C source files--.f, .c, .h, and Makefile--into the /tmp directory:
unzip source.zip ".[fch]" Makefile -d /tmp
(the double quotes are necessary only in Unix and only if globbing is turned on). To extract all FORTRAN
and C source files, regardless of case (e.g., both .c and .C, and any makefile, Makefile, MAKEFILE or
similar):
unzip C source.zip ".[fch]" makefile -d /tmp
To extract any such files but convert any uppercase MS-DOS or VMS names to lowercase and convert the
line-endings of all of the files to the local standard (without respect to any files that might be marked
binary):
unzip aaCL source.zip ".[fch]" makefile -d /tmp
To extract only newer versions of the files already in the current directory, without querying (NOTE: be
careful of unzipping in one timezone a zipfile created in another--ZIP archives other than those created by
Zip 2.1 or later contain no timezone information, and a newer file from an eastern timezone may, in fact,
be older):
unzip fo sources
To extract newer versions of the files already in the current directory and to create any files not already
there (same caveat as previous example):
unzip uo sources
To display a diagnostic screen showing which unzip and zipinfo options are stored in environment variables, whether decryption support was compiled in, the compiler with which unzip was compiled, etc.:
unzip v
In the last five examples, assume that UNZIP or UNZIP_OPTS is set to -q. To do a singly quiet listing:
unzip l file.zip
To do a doubly quiet listing:
unzip ql file.zip
(Note that the .zip is generally not necessary.) To do a standard listing:
unzip ql file.zip
or
unzip lq file.zip
or
unzip lq file.zip

(extra minuses dont hurt)

TIPS

The current maintainer, being a lazy sort, finds it very useful to define a pair of aliases: tt for unzip
tq and ii for unzip Z (or zipinfo). One may then simply type tt zipfile to test
an archive, something that is worth making a habit of doing. With luck unzip will report No errors

Info-ZIP

Last change: 14 January 2001 (v5.42)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIP ( 1L )

detected in compressed data of zipfile.zip, after which one may breathe a sigh of
relief.
The maintainer also finds it useful to set the UNZIP environment variable to aL and is tempted to add
C as well. His ZIPINFO variable is set to z.
DIAGNOSTICS

The exit status (or error level) approximates the exit codes defined by PKWARE and takes on the following
values, except under VMS:
0

normal; no errors or warnings detected.

one or more warning errors were encountered, but processing completed successfully
anyway. This includes zipfiles where one or more files was skipped due to unsupported
compression method or encryption with an unknown password.

a generic error in the zipfile format was detected. Processing may have completed successfully anyway; some broken zipfiles created by other archivers have simple workarounds.

a severe error in the zipfile format was detected. Processing probably failed immediately.

unzip was unable to allocate memory for one or more buffers during program initialization.

unzip was unable to allocate memory or unable to obtain a tty to read the decryption
password(s).

unzip was unable to allocate memory during decompression to disk.

unzip was unable to allocate memory during in-memory decompression.

[currently not used]

the specified zipfiles were not found.

10

invalid options were specified on the command line.

11

no matching files were found.

50

the disk is (or was) full during extraction.

51

the end of the ZIP archive was encountered prematurely.

80

the user aborted unzip prematurely with control-C (or similar)

81

testing or extraction of one or more files failed due to unsupported compression methods
or unsupported decryption.

82

no files were found due to bad decryption password(s). (If even one file is successfully
processed, however, the exit status is 1.)

VMS interprets standard Unix (or PC) return values as other, scarier-looking things, so unzip instead maps
them into VMS-style status codes. The current mapping is as follows: 1 (success) for normal exit,
0x7fff0001 for warning errors, and (0x7fff000? + 16normal_unzip_exit_status) for all other errors, where
the ? is 2 (error) for unzip values 2, 9-11 and 80-82, and 4 (fatal error) for the remaining ones (3-8, 50,
51). In addition, there is a compilation option to expand upon this behavior: defining RETURN_CODES
results in a human-readable explanation of what the error status means.
BUGS

Multi-part archives are not yet supported, except in conjunction with zip. (All parts must be concatenated
together in order, and then zip F must be performed on the concatenated archive in order to fix
it.) This will definitely be corrected in the next major release.
Archives read from standard input are not yet supported, except with funzip (and then only the first member
of the archive can be extracted).

Info-ZIP

Last change: 14 January 2001 (v5.42)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIP ( 1L )

Archives encrypted with 8-bit passwords (e.g., passwords with accented European characters) may not be
portable across systems and/or other archivers. See the discussion in DECRYPTION above.
unzips M (more) option is overly simplistic in its handling of screen output; as noted above, it fails to
detect the wrapping of long lines and may thereby cause lines at the top of the screen to be scrolled off
before being read. unzip should detect and treat each occurrence of line-wrap as one additional line printed.
This requires knowledge of the screens width as well as its height. In addition, unzip should detect the true
screen geometry on all systems.
Dates, times and permissions of stored directories are not restored except under Unix.
[MS-DOS] When extracting or testing files from an archive on a defective floppy diskette, if the Fail
option is chosen from DOSs Abort, Retry, Fail? message, older versions of unzip may hang the system,
requiring a reboot. This problem appears to be fixed, but control-C (or control-Break) can still be used to
terminate unzip.
Under DEC Ultrix, unzip would sometimes fail on long zipfiles (bad CRC, not always reproducible). This
was apparently due either to a hardware bug (cache memory) or an operating system bug (improper handling of page faults?). Since Ultrix has been abandoned in favor of Digital Unix (OSF/1), this may not be
an issue anymore.
[Unix] Unix special files such as FIFO buffers (named pipes), block devices and character devices are not
restored even if they are somehow represented in the zipfile, nor are hard-linked files relinked. Basically
the only file types restored by unzip are regular files, directories and symbolic (soft) links.
[OS/2] Extended attributes for existing directories are only updated if the o (overwrite all) option is
given. This is a limitation of the operating system; because directories only have a creation time associated
with them, unzip has no way to determine whether the stored attributes are newer or older than those on
disk. In practice this may mean a two-pass approach is required: first unpack the archive normally (with or
without freshening/updating existing files), then overwrite just the directory entries (e.g., unzip -o
foo /).
[VMS] When extracting to another directory, only the [.foo] syntax is accepted for the d option; the simple Unix foo syntax is silently ignored (as is the less common VMS foo.dir syntax).
[VMS] When the file being extracted already exists, unzips query only allows skipping, overwriting or
renaming; there should additionally be a choice for creating a new version of the file. In fact, the
overwrite choice does create a new version; the old version is not overwritten or deleted.
SEE ALSO

funzip(1L), zip(1L), zipcloak(1L), zipgrep(1L), zipinfo(1L), zipnote(1L), zipsplit(1L)


URL

The Info-ZIP home page is currently at http://www.info-zip.org/pub/infozip/ or


ftp://ftp.info-zip.org/pub/infozip/ .
AUTHORS

The primary Info-ZIP authors (current semi-active members of the Zip-Bugs workgroup) are: Greg Cave
Newt Roelofs (UnZip); Onno van der Linden (Zip); Jean-loup Gailly (compression); Mark Adler
(decompression, fUnZip); Christian Spieler (UnZip maintance coordination, VMS, MS-DOS, Windows 95,
NT, shared code, general Zip and UnZip integration and optimization); Mike White (Windows GUI, Windows DLLs); Kai Uwe Rommel (OS/2); Paul Kienitz (Amiga, Windows 95); Chris Herborth (BeOS, QNX,
Atari); Jonathan Hudson (SMS/QDOS); Sergio Monesi (Acorn RISC OS); Harald Denker (Atari, MVS);
John Bush (Solaris, Amiga); Hunter Goatley (VMS); Steve Salisbury (Windows 95, NT); Steve Miller
(Windows CE GUI), Johnny Lee (MS-DOS, Windows 95, NT); and Dave Smith (Tandem NSK). The
author of the original unzip code upon which Info-ZIPs was based is Samuel H. Smith; Carl Mascott did
the first Unix port; and David P. Kirschbaum organized and led Info-ZIP in its early days with Keith Petersen hosting the original mailing list at WSMR-SimTel20. The full list of contributors to UnZip has grown
quite large; please refer to the CONTRIBS file in the UnZip source distribution for a relatively complete
version.

Info-ZIP

Last change: 14 January 2001 (v5.42)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIP ( 1L )

VERSIONS

v1.2
v2.0
v2.x
v3.0
v3.1
v4.0
v4.1
v4.2
v5.0
v5.01
v5.1
v5.11
v5.12
v5.2
v5.3
v5.31
v5.32
v5.4
v5.41
v5.42

Info-ZIP

15 Mar 89
9 Sep 89
fall 1989
1 May 90
15 Aug 90
1 Dec 90
12 May 91
20 Mar 92
21 Aug 92
15 Jan 93
7 Feb 94
2 Aug 94
28 Aug 94
30 Apr 96
22 Apr 97
31 May 97
3 Nov 97
28 Nov 98
16 Apr 00
14 Jan 01

Samuel H. Smith
Samuel H. Smith
many Usenet contributors
Info-ZIP (DPK, consolidator)
Info-ZIP (DPK, consolidator)
Info-ZIP (GRR, maintainer)
Info-ZIP
Info-ZIP (Zip-Bugs subgroup, GRR)
Info-ZIP (Zip-Bugs subgroup, GRR)
Info-ZIP (Zip-Bugs subgroup, GRR)
Info-ZIP (Zip-Bugs subgroup, GRR)
Info-ZIP (Zip-Bugs subgroup, GRR)
Info-ZIP (Zip-Bugs subgroup, GRR)
Info-ZIP (Zip-Bugs subgroup, GRR)
Info-ZIP (Zip-Bugs subgroup, GRR)
Info-ZIP (Zip-Bugs subgroup, GRR)
Info-ZIP (Zip-Bugs subgroup, GRR)
Info-ZIP (Zip-Bugs subgroup, SPC)
Info-ZIP (Zip-Bugs subgroup, SPC)
Info-ZIP (Zip-Bugs subgroup, SPC)

Last change: 14 January 2001 (v5.42)

10

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIPSFX ( 1L )

NAME

unzipsfx self-extracting stub for prepending to ZIP archives


SYNOPSIS

<name of unzipsfx+archive combo> [cfptuz[ajnoqsCLV$]] [file(s) . . . [x xfile(s) . . .]]

DESCRIPTION

unzipsfx is a modified version of unzip(1L) designed to be prepended to existing ZIP archives in order to
form self-extracting archives. Instead of taking its first non-flag argument to be the zipfile(s) to be
extracted, unzipsfx seeks itself under the name by which it was invoked and tests or extracts the contents of
the appended archive. Because the executable stub adds bulk to the archive (the whole purpose of which is
to be as small as possible), a number of the less-vital capabilities in regular unzip have been removed.
Among these are the usage (or help) screen, the listing and diagnostic functions (l and v), the ability to
decompress older compression formats (the reduce, shrink and implode methods), and the ability
to extract to a directory other than the current one. Decryption is supported as a compile-time option but
should be avoided unless the attached archive contains encrypted files.
Note that self-extracting archives made with unzipsfx are no more (or less) portable across different
operating systems than is the unzip executable itself. In general a self-extracting archive made on a particular Unix system, for example, will only self-extract under the same flavor of Unix. Regular unzip may
still be used to extract the embedded archive as with any normal zipfile, although it will generate a harmless
warning about extra bytes at the beginning of the zipfile. Despite this, however, the self-extracting archive
is technically not a valid ZIP archive, and PKUNZIP may be unable to test or extract it. This limitation is
due to the simplistic manner in which the archive is created; the internal directory structure is not updated
to reflect the extra bytes prepended to the original zipfile.
ARGUMENTS

[file(s)] An optional list of archive members to be processed. Regular expressions (wildcards) similar to
those in Unix egrep(1) may be used to match multiple members. These wildcards may contain:

matches a sequence of 0 or more characters

matches exactly 1 character

[. . .]

matches any single character found inside the brackets; ranges are specified by a beginning character, a hyphen, and an ending character. If an exclamation point or a caret (!
or ) follows the left bracket, then the range of characters within the brackets is complemented (that is, anything except the characters inside the brackets is considered a match).

(Be sure to quote any character that might otherwise be interpreted or modified by the operating
system, particularly under Unix and VMS.)
[x xfile(s)]
An optional list of archive members to be excluded from processing. Since wildcard characters
match directory separators (/), this option may be used to exclude any files that are in subdirectories. For example, f o o s f x . [ c h ] - x / would extract all C source files in the main
directory, but none in any subdirectories. Without the x option, all C source files in all directories within the zipfile would be extracted.
If unzipsfx is compiled with SFX_EXDIR defined, the following option is also enabled:
[d exdir]
An optional directory to which to extract files. By default, all files and subdirectories are recreated
in the current directory; the d option allows extraction in an arbitrary directory (always assuming
one has permission to write to the directory). The option and directory may be concatenated
without any white space between them, but note that this may cause normal shell behavior to be
suppressed. In particular, d (tilde) is expanded by Unix C shells into the name of the
users home directory, but d is treated as a literal subdirectory of the current directory.

Info-ZIP

Last change: 14 January 2001 (v5.42)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIPSFX ( 1L )

OPTIONS

unzipsfx supports the following unzip(1L) options: c and p (extract to standard output/screen), f and u
(freshen and update existing files upon extraction), t (test archive) and z (print archive comment). All
normal listing options (l, v and Z) have been removed, but the testing option (t) may be used as a
poor mans listing. Alternatively, those creating self-extracting archives may wish to include a short
listing in the zipfile comment.
See unzip(1L) for a more complete description of these options.
MODIFIERS

unzipsfx currently supports all unzip(1L) modifiers: a (convert text files), n (never overwrite), o
(overwrite without prompting), q (operate quietly), C (match names case-insenstively), L (convert
uppercase-OS names to lowercase), j (junk paths) and V (retain version numbers); plus the following
operating-system specific options: X (restore VMS owner/protection info), s (convert spaces in
filenames to underscores [DOS, OS/2, NT]) and $ (restore volume label [DOS, OS/2, NT, Amiga]).
(Support for regular ASCII text-conversion may be removed in future versions, since it is simple enough
for the archives creator to ensure that text files have the appropriate format for the local OS. EBCDIC
conversion will of course continue to be supported since the zipfile format implies ASCII storage of text
files.)
See unzip(1L) for a more complete description of these modifiers.
ENVIRONMENT OPTIONS

unzipsfx uses the same environment variables as unzip(1L) does, although this is likely to be an issue only
for the person creating and testing the self-extracting archive. See unzip(1L) for details.
DECRYPTION

Decryption is supported exactly as in unzip(1L); that is, interactively with a non-echoing prompt for the
password(s). See unzip(1L) for details. Once again, note that if the archive has no encrypted files there is
no reason to use a version of unzipsfx with decryption support; that only adds to the size of the archive.
EXAMPLES

To create a self-extracting archive letters from a regular zipfile letters.zip and change the new archives permissions to be world-executable under Unix:
cat unzipsfx letters.zip > letters
chmod 755 letters
zip -A letters
To create the same archive under MS-DOS, OS/2 or NT (note the use of the /b [binary] option to the copy
command):
copy /b unzipsfx.exe+letters.zip letters.exe
zip -A letters.exe
Under VMS:
copy unzipsfx.exe,letters.zip letters.exe
letters == "$currentdisk:[currentdir]letters.exe"
zip -A letters.exe
(The VMS append command may also be used. The second command installs the new program as a
foreign command capable of taking arguments. The third line assumes that Zip is already installed as a
foreign command.) Under AmigaDOS:
MakeSFX letters letters.zip UnZipSFX
(MakeSFX is included with the UnZip source distribution and with Amiga binary distributions. zip
-A doesnt work on Amiga self-extracting archives.) To test (or list) the newly created self-extracting
archive:

Info-ZIP

Last change: 14 January 2001 (v5.42)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIPSFX ( 1L )

letters t
To test letters quietly, printing only a summary message indicating whether the archive is OK or not:
letters tqq
To extract the complete contents into the current directory, recreating all files and subdirectories as necessary:
letters
To extract all .txt files (in Unix quote the ):
letters .txt
To extract everything except the .txt files:
letters -x .txt
To extract only the README file to standard output (the screen):
letters -c README
To print only the zipfile comment:
letters z
LIMITATIONS

The principle and fundamental limitation of unzipsfx is that it is not portable across architectures or operating systems, and therefore neither are the resulting archives. For some architectures there is limited portability, however (e.g., between some flavors of Intel-based Unix).
Another problem with the current implementation is that any archive with junk prepended to the beginning technically is no longer a zipfile (unless zip(1) is used to adjust the zipfile offsets appropriately, as
noted above). unzip(1) takes note of the prepended bytes and ignores them since some file-transfer protocols, notably MacBinary, are also known to prepend junk. But PKWAREs archiver suite may not be able
to deal with the modified archive unless its offsets have been adjusted.
unzipsfx has no knowledge of the users PATH, so in general an archive must either be in the current directory when it is invoked, or else a full or relative path must be given. If a user attempts to extract the archive
from a directory in the PATH other than the current one, unzipsfx will print a warning to the effect, cant
find myself. This is always true under Unix and may be true in some cases under MS-DOS, depending on
the compiler used (Microsoft C fully qualifies the program name, but other compilers may not). Under
OS/2 and NT there are operating-system calls available that provide the full path name, so the archive may
be invoked from anywhere in the users path. The situation is not known for AmigaDOS, Atari TOS,
MacOS, etc.
As noted above, a number of the normal unzip(1L) functions have been removed in order to make unzipsfx
smaller: usage and diagnostic info, listing functions and extraction to other directories. Also, only stored
and deflated files are supported. The latter limitation is mainly relevant to those who create SFX archives,
however.
VMS users must know how to set up self-extracting archives as foreign commands in order to use any of
unzipsfxs options. This is not necessary for simple extraction, but the command to do so then becomes,
e.g., run letters (to continue the examples given above).
unzipsfx on the Amiga requires the use of a special program, MakeSFX, in order to create working selfextracting archives; simple concatenation does not work. (For technically oriented users, the attached
archive is defined as a debug hunk.) There may be compatibility problems between the ROM levels of
older Amigas and newer ones.
All current bugs in unzip(1L) exist in unzipsfx as well.
DIAGNOSTICS

unzipsfxs exit status (error level) is identical to that of unzip(1L); see the corresponding man page.

Info-ZIP

Last change: 14 January 2001 (v5.42)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

UNZIPSFX ( 1L )

SEE ALSO

funzip(1L), unzip(1L), zip(1L), zipcloak(1L), zipgrep(1L), zipinfo(1L), zipnote(1L), zipsplit(1L)


URL

The Info-ZIP home page is currently at http://www.info-zip.org/pub/infozip/ or


ftp://ftp.info-zip.org/pub/infozip/ .
AUTHORS

Greg Roelofs was responsible for the basic modifications to UnZip necessary to create UnZipSFX. See
unzip(1L) for the current list of Zip-Bugs authors, or the file CONTRIBS in the UnZip source distribution
for the full list of Info-ZIP contributors.

Info-ZIP

Last change: 14 January 2001 (v5.42)

Property of BladeLogic, Inc.


Strictly confidential and proprietary

uuencode(1)

uuencode(1)

NAME
uuencode, uudecode - encode/decode a binary file

SYNOPSIS
uuencode [file] name
uudecode [file ...]

DESCRIPTION
Uuencode and uudecode are used to transmit binary files over transmission mediums that do not support
other than simple ASCII data.
Uuencode reads file (or by default the standard input) and writes an encoded version to the standard output.
The encoding uses only printing ASCII characters and includes the mode of the file and the operand name
for use by uudecode.
Uudecode transforms uuencoded files (or by default, the standard input) into the original form. The resulting file is named name and will have the mode of the original file except that setuid and execute bits are not
retained. Uudecode ignores any leading and trailing lines.

OPTIONS
There are no options for any of these commands.

EXAMPLES
The following example packages up a source tree, compresses it, uuencodes it and mails it to a user. When
uudecode is run on the target system, the file src_tree.tar.Z will be created which may then be uncompressed and extracted into the original tree.
tar cf - src_tree | compress |
uuencode src_tree.tar.Z | mail jsmith

FILE FORMAT
Files output by uuencode(1) consist of a header line, followed by a number of body lines, and a trailer line.
The uudecode(1) command will ignore any lines preceding the header or following the trailer. Lines preceding a header must not, of course, look like a header.
The header line is distinguished by having the first 6 characters begin (note the trailing space). The
word begin is followed by a mode (in octal), and a string which names the remote file. A space separates
the three items in the header line.
The body consists of a number of lines, each at most 62 characters long (including the trailing newline).
These consist of a character count, followed by encoded characters, followed by a newline. The character
count is a single printing character, and represents an integer, the number of bytes the rest of the line represents. Such integers are always in the range from 0 to 63 and can be determined by subtracting the character space (octal 40) from the character.
Groups of 3 bytes are stored in 4 characters, 6 bits per character. All are offset by a space to make the characters printing. The last line may be shorter than the normal 45 bytes. If the size is not a multiple of 3, this
fact can be determined by the value of the count on the last line. Extra garbage will be included to make
the character count a multiple of 4. The body is terminated by a line with a count of zero. This line consists of one ASCII space.
The trailer line consists of end on a line by itself.

CAVEATS
The encoded form of the file is expanded by 35% (3 bytes become 4 plus control information).

ORIGIN
Uuencode and uudecode include software developed by the University of California, Berkeley and its contributors. Please see the intro section for complete acknowledgements.

NSH

uuencode(1)

Property of BladeLogic, Inc.


Strictly confidential and proprietary

uuencode(1)

SEE ALSO
uuencode(1), uudecode (1), compress(1)

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

version(1)

version(1)

NAME
version Output version information about BladeLogic software

SYNOPSIS
version

DESCRIPTION
The version command outputs release information about the BladeLogic software that it detects as being
installed on the local server. Sample output is:
BladeLogic RSCD Agent 4.5.0.494 [Oct 20 2002 16:41:59]
Copyright (C) 1996 - 2002 BladeLogic Inc.
BladeLogic Network Shell 4.5.0.494 [Oct 20 2002 16:41:59]
Copyright (C) 1996 - 2002 BladeLogic Inc.

ORIGIN
version was written by Thomas Kraus.

SEE ALSO
agentinfo(1),

NSH

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

VI (1)

NAME
ex, vi, view text editor
SYNOPSIS
ex [ FRrSsv] [ c cmd] [ t tag] [ w size] [file . . .]
vi [ eFRrS] [ c cmd] [ t tag] [ w size] [file . . .]
view [ eFrS] [ c cmd] [ t tag] [ w size] [file . . .]
DESCRIPTION
ex is a line-oriented text editor; vi is a screen-oriented text editor. ex and vi are different interfaces to the
same program, and it is possible to switch back and forth during an edit session. view is the equivalent of
using the R ( read-only ) option of vi.
This manual page is the one provided with the nex/nvi versions of the ex/vi text editors. nex/nvi are
intended as bug-for-bug compatible replacements for the original Fourth Berkeley Software Distribution
( 4BSD ) ex and vi programs. For the rest of this manual page, nex/nvi is used only when its necessary
to distinguish it from the historic implementations of ex/vi.
This manual page is intended for users already familiar with ex/vi. Anyone else should almost certainly
read a good tutorial on the editor before this manual page. See the SEE ALSO section below for a list of
additional materials. If youre in an unfamiliar environment, and you absolutely have to get work done
immediately, read the section after the options description, entitled FAST STARTUP. Its probably enough
to get you going.
The following options are available:
c cmd

Execute cmd on the first file loaded. Particularly useful for initial positioning in the file,
although cmd is not limited to positioning commands. This is the POSIX 1003.2 interface for
the historic +cmd syntax. nex/nvi supports both the old and new syntax.

Start editing in ex mode, as if the command name were ex.

Dont copy the entire file when first starting to edit. (The default is to make a copy in case
someone else modifies the file during your edit session.)

Start editing in read-only mode, as if the command name was view, or the readonly option
was set.

Recover the specified files, or, if no files are specified, list the files that could be recovered. If
no recoverable files by the specified name exist, the file is edited as if the r option had not
been specified.

Run with the secure edit option set, disallowing all access to external programs.

Enter batch mode; applicable only to ex edit sessions. Batch mode is useful when running ex
scripts. Prompts, informative messages and other user oriented messages are turned off, and no
startup files or environment variables are read. This is the POSIX 1003.2 interface for the historic - argument. nex/nvi supports both the old and new syntax.

t tag

Start editing at the specified tag (see ctags(1)).

Start editing in vi mode, as if the command name was vi.

w size Set the initial window size to the specified number of lines.
Command input for ex/vi is read from the standard input. In the vi interface, it is an error if standard input
is not a terminal. In the ex interface, if standard input is not a terminal, ex will read commands from it
regardless; however, the session will be a batch mode session, exactly as if the s option had been specified.

BSD

October 10, 1996

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

VI (1)

ex/vi exits 0 on success, or greater than 0 if an error occurs.


FAST STARTUP
This section will tell you the minimum amount that you need to do simple editing tasks using vi. If youve
never used any screen editor before, youre likely to have problems even with this simple introduction. In
that case you should find someone that already knows vi and have them walk you through this section.
vi is a screen editor. This means that it takes up almost the entire screen, displaying part of the file on each
screen line, except for the last line of the screen. The last line of the screen is used for you to give commands
to vi, and for vi to give information to you.
The other fact that you need to understand is that vi is a modeful editor, i.e. you are either entering text or
you are executing commands, and you have to be in the right mode to do one or the other. You will be in
command mode when you first start editing a file. There are commands that switch you into input mode.
There is only one key that takes you out of input mode, and that is the escape key.
Key names are written using less-than and greater-than signs, e.g. escape means the escape key, usually
labeled Esc on your terminals keyboard. If youre ever confused as to which mode youre in, keep entering the escape key until vi beeps at you. Generally, vi will beep at you if you try and do something thats
not allowed. It will also display error messages.
To start editing a file, enter the following command:
$ vi file
The command you should enter as soon as you start editing is:
:set verbose showmode
This will make the editor give you verbose error messages and display the current mode at the bottom of the
screen.
The commands to move around the file are:
h

Move the cursor left one character.

Move the cursor down one line.

Move the cursor up one line.

Move the cursor right one character.

cursor-arrows
The cursor arrow keys should work, too.
/text

Search for the string text in the file, and move the cursor to its first character.

The commands to enter new text are:


a

Append new text, after the cursor.

Insert new text, before the cursor.

Open a new line above the line the cursor is on, and start entering text.

Open a new line below the line the cursor is on, and start entering text.

escape

Once youve entered input mode using one of the a, i, O or o commands, use escape to quit
entering text and return to command mode.

The commands to copy text are:

BSD

October 10, 1996

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

Append the copied line after the line the cursor is on.

yy

Copy the line the cursor is on.

VI (1)

The commands to delete text are:


dd

Delete the line the cursor is on.

Delete the character the cursor is on.

The commands to write the file are:


:w

Write the file back to the file with the name that you originally used as an argument on the vi command line.

:w file_name
Write the file back to the file with the name file_name.
The commands to quit editing and exit the editor are:
:q

Quit editing and leave vi (if youve modified the file, but not saved your changes, vi will refuse to
quit).

:q!

Quit, discarding any modifications that you may have made.

One final caution: Unusual characters can take up more than one column on the screen, and long lines can
take up more than a single screen line. The above commands work on physical characters and lines, i.e.
they affect the entire line no matter how many screen lines it takes up and the entire character no matter how
many screen columns it takes up.
VI COMMANDS
The following section describes the commands available in the command mode of the vi editor. In each
entry below, the tag line is a usage synopsis for the command character.
control-A
Search forward for the current word.
[count] control-B
Page backwards count screens.
[count] control-D
Scroll forward count lines. If count is not given, scroll forward half the number of lines in the
current screen.
[count] control-E
Scroll forward count lines, leaving the current line and column as is, if possible.
[count] control-F
Page forward count screens.
control-G
Display the file information.
[count] control-H
[count] h
Move the cursor back count characters in the current line.
[count] control-J

BSD

October 10, 1996

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

VI (1)

[count] control-N
[count] j
Move the cursor down count lines without changing the current column.
control-L
control-R
Repaint the screen.
[count] control-M
[count] +
Move the cursor down count lines to the first non-blank character of that line.
[count] control-P
[count] k
Move the cursor up count lines, without changing the current column.
control-T
Return to the most recent tag context.
[count] control-U
Scroll backwards count lines. If count is not given, scroll forward half the number of lines in the
current screen.
control-W
Switch to the next lower screen in the window, or to the first screen if there are no lower screens in
the window.
[count] control-Y
Scroll backwards count lines, leaving the current line and column as is, if possible.
control-Z
Suspend the current editor session.
escape
Execute ex commands or cancel partial commands.
control-]
Push a tag reference onto the tag stack.
control-
Switch to the most recently edited file.
[count] space
[count] l
Move the cursor forward count characters without changing the current line.
[count] ! motion shell-argument(s) carriage-return
Replace text with results from a shell command.
[count] # #|+|Increment or decrement the number under the cursor. If the trailing character is a # or +, the
number is incremented. If the trailing character is a -, the number is decremented.
[count] $
Move the cursor to the end of a line.
%

BSD

Move to the matching character.

October 10, 1996

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

&

VI (1)

Repeat the previous substitution command on the current line.

character
character
Return to a context marked by the character character. The first form returns to the beginning of
the line marked by character. The second form returns to the first character of the context
marked by character.
[count] (
Back up count sentences.
[count] )
Move forward count sentences.
[count] ,
Reverse find character count times.
[count] Move to the first non-blank of the previous line, count times.
[count] .
Repeat the last vi command that modified text.
/RE carriage-return
/RE/ [offset] carriage-return
?RE carriage-return
?RE? [offset] carriage-return
N
n
Search forward ( / ) or backward ( ? ) for a regular expression. n and N repeat the last search in
the same or opposite directions, respectively. If offset is specified, the cursor is placed offset
lines before or after the matched regular expression.
0

Move to the first character in the current line.

Execute an ex command.

[count] ;
Repeat the last character find count times.
[count] <motion
[count] >motion
Shift lines left or right.
@ buffer
Execute a named buffer.
[count] A
Enter input mode, appending the text after the end of the line. If a count argument is given, the
characters input are repeated count 1 number of times.
[count] B
Move backwards count bigwords.
[buffer] [count] C
Change text from the current position to the end-of-line. If buffer is specified, yank the deleted
text into buffer.

BSD

October 10, 1996

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

VI (1)

[buffer] D
Delete text from the current position to the end-of-line. If buffer is specified, yank the deleted
text into buffer.
[count] E
Move forward count end-of-bigwords.
[count] F character
Search count times backward through the current line for character.
[count] G
Move to line count, or the last line of the file if count is not specified.
[count] H
Move to the screen line count 1 lines below the top of the screen.
[count] I
Enter input mode, inserting the text at the beginning of the line. If a count argument is given, the
characters input are repeated count 1 number of times.
[count] J
Join lines.
[count] L
Move to the screen line count 1 lines above the bottom of the screen.
M

Move to the screen line in the middle of the screen.

[count] O
Enter input mode, appending text in a new line above the current line. If a count argument is
given, the characters input are repeated count 1 number of times.
[buffer] P
Insert text from a buffer.
Q

Exit vi ( or visual ) mode and switch to ex mode.

[count] R
Enter input mode, replacing the characters in the current line. If a count argument is given, the
characters input are repeated count 1 number of times.
[buffer] [count] S
Substitute count lines. If buffer is specified, yank the deleted text into buffer.
[count] T character
Search backwards, count times, through the current line for the character after the specified
character.
U

Restore the current line to its state before the cursor last moved to it.

[count] W
Move forward count bigwords.
[buffer] [count] X
Delete count characters before the cursor. If buffer is specified, yank the deleted text into
buffer.
[buffer] [count] Y
Copy (or yank) count lines into the specified buffer, or the default buffer if none is specified.

BSD

October 10, 1996

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

ZZ

VI (1)

Write the file and exit vi.

[count] [[
Back up count section boundaries.
[count] ]]
Move forward count section boundaries.

Move to the first non-blank character on the current line.

[count] _
Move down count 1 lines, to the first non-blank character.
[count] a
Enter input mode, appending the text after the cursor. If a count argument is given, the characters
input are repeated count 1 number of times.
[count] b
Move backwards count words.
[buffer] [count] c motion
Change a region of text.
[buffer] [count] d motion
Delete a region of text.
[count] e
Move forward count end-of-words.
[count] f character
Search forward, count times, through the rest of the current line for character.
[count] i
Enter input mode, inserting the text before the cursor. If a count argument is given, the characters
input are repeated count 1 number of times.
m character
Save the current context ( line and column ) as character.
[count] o
Enter input mode, appending text in a new line under the current line. If a count argument is
given, the characters input are repeated count 1 number of times.
[buffer] p
Append text from a buffer.
[count] r character
Replace count characters.
[buffer] [count] s
Substitute count characters in the current line starting with the current character.
[count] t character
Search forward, count times, through the current line for the character immediately before
character.
u

Undo the last change made to the file.

[count] w
Move forward count words.

BSD

October 10, 1996

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

VI (1)

[buffer] [count] x
Delete count characters.
[buffer] [count] y motion
Copy (or yank) a text region specified by count and motion into a buffer.
[count1] z [count2] type
Redraw, optionally repositioning and resizing the screen. If count2 is specified, limit the screen
size to count2 lines. The following type characters may be used:
+

If count1 is specified, place the line count1 at the top of the screen. Otherwise, display
the screen after the current screen.

carriage-return
Place the line count1 at the top of the screen.
.

Place the line count1 in the center of the screen.

Place the line count1 at the bottom of the screen.

If count1 is given, display the screen before the screen before count1 ( i.e. 2 screens
before ) . Otherwise, display the screen before the current screen.

[count] {
Move backward count paragraphs.
[column] |
Move to a specific column position on the current line. If column is omitted, move to the start of
the current line.
[count] }
Move forward count paragraphs.
[count]
Reverse the case of the next count character(s).
[count] motion
Reverse the case of the characters in a text region specified by the count and motion. Only in
effect if the tildeop option is set.
interrupt
Interrupt the current operation. The interrupt character is usually control-C.
VI TEXT INPUT COMMANDS
The following section describes the commands available in the text input mode of the vi editor.
nul

Replay the previous input.

control-D
Erase to the previous shiftwidth column boundary.
control-D
Erase all of the autoindent characters, and reset the autoindent level.
0control-D
Erase all of the autoindent characters.
control-T
Insert sufficient tab and space characters to move forward to the next shiftwidth column
boundary.

BSD

October 10, 1996

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

VI (1)

erase
control-H
Erase the last character.
literal next
Escape the next character from any special meaning. The literal next character is usually
control-V.
escape
Resolve all text input into the file, and return to command mode.
line erase
Erase the current line.
control-W
word erase
Erase the last word. The definition of word is dependent on the altwerase and ttywerase
options.
control-X[0-9A-Fa-f]+
Insert a character with the specified hexadecimal value into the text.
interrupt
Interrupt text input mode, returning to command mode. The interrupt character is usually
control-C.
EX COMMANDS
The following section describes the commands available in the ex editor. In each entry below, the tag line is
a usage synopsis for the command.
end-of-file
Scroll the screen.
! argument(s)
[range] ! argument(s)
Execute a shell command, or filter lines through a shell command.
"

A comment.

[range] nu[mber] [count] [flags]


[range] # [count] [flags]
Display the selected lines, each preceded with its line number.
@ buffer
buffer
Execute a buffer.
[range] <[< . . .] [count] [flags]
Shift lines left.
[line] = [flags]
Display the line number of line. If line is not specified, display the line number of the last line
in the file.
[range] >[> . . .] [count] [flags]
Shift lines right.

BSD

October 10, 1996

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

VI (1)

ab[breviate] lhs rhs


vi only. Add lhs as an abbreviation for rhs to the abbreviation list.
[line] a[ppend][!]
The input text is appended after the specified line.
ar[gs]
bg

Display the argument list.


vi only. Background the current screen.

[range] c[hange][!] [count]


The input text replaces the specified range.
chd[ir][!] [directory]
cd[!] [directory]
Change the current working directory.
[range] co[py] line [flags]
[range] t line [flags]
Copy the specified lines after the destination line.
cs[cope] add | find | help | kill | reset
Execute a Cscope command.
[range] d[elete] [buffer] [count] [flags]
Delete the lines from the file.
di[splay] b[uffers] | c[onnections] | s[creens] | t[ags]
Display buffers, Cscope connections, screens or tags.
[Ee][dit][!] [+cmd] [file]
[Ee]x[!] [+cmd] [file]
Edit a different file.
exu[sage] [command]
Display usage for an ex command.
f[ile] [file]
Display and optionally change the file name.
[Ff]g [name]
vi mode only. Foreground the specified screen.
[range] g[lobal] /pattern/ [commands]
[range] v /pattern/ [commands]
Apply commands to lines matching ( global ) or not matching ( v ) a pattern.
he[lp]

Display a help message.

[line] i[nsert][!]
The input text is inserted before the specified line.
[range] j[oin][!] [count] [flags]
Join lines of text together.
[range] l[ist] [count] [flags]
Display the lines unambiguously.

BSD

October 10, 1996

10

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

VI (1)

map[!] [lhs rhs]


Define or display maps (for vi only).
[line] ma[rk] character
[line] k character
Mark the line with the mark character.
[range] m[ove] line
Move the specified lines after the target line.
mk[exrc][!] file
Write the abbreviations, editor options and maps to the specified file.
[Nn][ext][!] [file . . .]
Edit the next file from the argument list.
pre[serve]
Save the file in a form that can later be recovered using the ex r option.
[Pp]rev[ious][!]
Edit the previous file from the argument list.
[range] p[rint] [count] [flags]
Display the specified lines.
[line] pu[t] [buffer]
Append buffer contents to the current line.
q[uit][!]
End the editing session.
[line] r[ead][!] [file]
Read a file.
rec[over] file
Recover file if it was previously saved.
res[ize] [+|-]size
vi mode only. Grow or shrink the current screen.
rew[ind][!]
Rewind the argument list.
se[t] [option[=[value]] ...] [nooption . . .] [option? . . .] [all]
Display or set editor options.
sh[ell]
Run a shell program.
so[urce] file
Read and execute ex commands from a file.
[range] s[ubstitute] [/pattern/replace/] [options] [count] [flags]
[range] & [options] [count] [flags]
[range] [options] [count] [flags]
Make substitutions.
su[spend][!]

BSD

October 10, 1996

11

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

VI (1)

st[op][!]
suspend
Suspend the edit session. The suspend character is usually control-Z.
[Tt]a[g][!] tagstring
Edit the file containing the specified tag.
[Tt]agn[ext][!]
Edit the file containing the next context for the current tag.
tagp[op][!] [file | number]
Pop to the specified tag in the tags stack.
[Tt]agp[rev][!]
Edit the file containing the previous context for the current tag.
tagt[op][!]
Pop to the least recent tag on the tags stack, clearing the stack.
una[bbreviate] lhs
vi only. Delete an abbreviation.
u[ndo]

Undo the last change made to the file.

unm[ap][!] lhs
Unmap a mapped string.
ve[rsion]
Display the version of the ex/vi editor.
[line] vi[sual] [type] [count] [flags]
ex mode only. Enter vi.
[Vi]i[sual][!] [+cmd] [file]
vi mode only. Edit a new file.
viu[sage] [command]
Display usage for a vi command.
[range] w[rite][!] [>> ] [file]
[range] w[rite] [!] [file]
[range] wn[!] [>> ] [file]
[range] wq[!] [>> ] [file]
Write the file.
[range] x[it][!] [file]
Exit the editor, writing the file if it has been modified.
[range] ya[nk] [buffer] [count]
Copy the specified lines to a buffer.
[line] z [type] [count] [flags]
Adjust the window.
SET OPTIONS
There are a large number of options that may be set ( or unset ) to change the editors behavior. This section
describes the options, their abbreviations and their default values.

BSD

October 10, 1996

12

VI (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

In each entry below, the first part of the tag line is the full name of the option, followed by any equivalent
abbreviations. The part in square brackets is the default value of the option. Most of the options are boolean,
i.e. they are either on or off, and do not have an associated value.
Options apply to both ex and vi modes, unless otherwise specified.
altwerase [off ]
vi only. Select an alternate word erase algorithm.
autoindent, ai [off ]
Automatically indent new lines.
autoprint, ap [on]
ex only. Display the current line automatically.
autowrite, aw [off ]
Write modified files automatically when changing files.
backup [""]
Back up files before they are overwritten.
beautify, bf [off ]
Discard control characters.
cdpath [environment variable CDPATH, or current directory]
The directory paths used as path prefixes for the cd command.
cedit [no default ]
Set the character to edit the colon command-line history.
columns, co [80]
Set the number of columns in the screen.
comment [off ]
vi only. Skip leading comments in shell, C and C++ language files.
directory, dir [environment variable TMPDIR, or /tmp]
The directory where temporary files are created.
edcompatible, ed [off ]
Remember the values of the c and g suffixes to the substitute commands, instead of initializing them as unset for each new command.
escapetime [1]
The 10ths of a second ex/vi waits for a subsequent key to complete an escape key mapping.
errorbells, eb [off ]
ex only. Announce error messages with a bell.
exrc, ex [off ]
Read the startup files in the local directory.
extended [off ]
Use extended regular expressions ( EREs ) rather than basic regular expressions ( BREs ) . See
re_format(7) for more information on regular expressions.
filec [no default ]
Set the character to perform file path completion on the colon command line.

BSD

October 10, 1996

13

VI (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

flash [on]
Flash the screen instead of beeping the keyboard on error.
hardtabs, ht [0]
Set the spacing between hardware tab settings. This option currently has no effect.
iclower [off ]
Makes all regular expressions case-insensitive, as long as an upper-case letter does not appear in the
search string.
ignorecase, ic [off ]
Ignore case differences in regular expressions.
keytime [6]
The 10ths of a second ex/vi waits for a subsequent key to complete a key mapping.
leftright [off ]
vi only. Do left-right scrolling.
lines, li [24]
vi only. Set the number of lines in the screen.
lisp [off ]
vi only. Modify various search commands and options to work with Lisp. This option is not yet
implemented.
list [off ]
Display lines in an unambiguous fashion.
lock [on]
Attempt to get an exclusive lock on any file being edited, read or written.
magic [on]
Treat certain characters specially in regular expressions.
matchtime [7]
vi only. The 10ths of a second ex/vi pauses on the matching character when the showmatch
option is set.
mesg [on]
Permit messages from other users.
mesgcat [/usr/share/vi/catalog/ ]
Selects a message catalog to be used to display error and informational messages in a specified language.
modelines, modeline [off ]
Read the first and last few lines of each file for ex commands. This option will never be implemented.
noprint [""]
Characters that are never handled as printable characters.
number, nu [off ]
Precede each line displayed with its current line number.
octal [off ]
Display unknown characters as octal numbers, instead of the default hexadecimal.

BSD

October 10, 1996

14

VI (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

open [on]
ex only. If this option is not set, the open and visual commands are disallowed.
optimize, opt [on]
vi only. Optimize text throughput to dumb terminals. This option is not yet implemented
paragraphs, para [IPLPPPQPP LIpplpipbp]
vi only. Define additional paragraph boundaries for the { and } commands.
path [""]
Define additional directories to search for files being edited.
print [""]
Characters that are always handled as printable characters.
prompt [on]
ex only. Display a command prompt.
readonly, ro [off ]
Mark the file and session as read-only.
recdir [/var/tmp/vi.recover]
The directory where recovery files are stored.
redraw, re [off ]
vi only. Simulate an intelligent terminal on a dumb one. This option is not yet implemented.
remap [on]
Remap keys until resolved.
report [5]
Set the number of lines about which the editor reports changes or yanks.
ruler [off ]
vi only. Display a row/column ruler on the colon command line.
scroll, scr [($LINES 1) / 2]
Set the number of lines scrolled.
searchincr [off ]
Makes the / and ? commands incremental.
sections, sect [NHSHH HUnhsh]
vi only. Define additional section boundaries for the [[ and ]] commands.
secure [off ]
Turns off all access to external programs.
shell, sh [environment variable SHELL, or /bin/sh]
Select the shell used by the editor.
shellmeta [{[?$"\ ]
Set the meta characters checked to determine if file name expansion is necessary.
shiftwidth, sw [8]
Set the autoindent and shift command indentation width.
showmatch, sm [off ]
vi only. Note matching { and ( for } and ) characters.

BSD

October 10, 1996

15

VI (1)

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

showmode, smd [off ]


vi only. Display the current editor mode and a modified flag.
sidescroll [16]
vi only. Set the amount a left-right scroll will shift.
slowopen, slow [off ]
Delay display updating during text input. This option is not yet implemented.
sourceany [off ]
Read startup files not owned by the current user. This option will never be implemented.
tabstop, ts [8]
This option sets tab widths for the editor display.
taglength, tl [0]
Set the number of significant characters in tag names.
tags, tag [tags ]
Set the list of tags files.
term, ttytype, tty [environment variable TERM]
Set the terminal type.
terse [off ]
This option has historically made editor messages less verbose. It has no effect in this implementation.
tildeop [off ]
Modify the command to take an associated motion.
timeout, to [on]
Time out on keys which may be mapped.
ttywerase [off ]
vi only. Select an alternate erase algorithm.
verbose [off ]
vi only. Display an error message for every error.
w300 [no default ]
vi only. Set the window size if the baud rate is less than 1200 baud.
w1200 [no default ]
vi only. Set the window size if the baud rate is equal to 1200 baud.
w9600 [no default ]
vi only. Set the window size if the baud rate is greater than 1200 baud.
warn [on]
ex only. This option causes a warning message to be printed on the terminal if the file has been
modified since it was last written, before a ! command.
window, w, wi [environment variable LINES 1]
Set the window size for the screen.
windowname [off ]
Change the icon/window name to the current file name even if it cant be restored on editor exit.

BSD

October 10, 1996

16

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

VI (1)

wraplen, wl [0]
vi only. Break lines automatically, the specified number of columns from the left-hand margin. If
both the wraplen and wrapmargin edit options are set, the wrapmargin value is used.
wrapmargin, wm [0]
vi only. Break lines automatically, the specified number of columns from the right-hand margin. If
both the wraplen and wrapmargin edit options are set, the wrapmargin value is used.
wrapscan, ws [on]
Set searches to wrap around the end or beginning of the file.
writeany, wa [off ]
Turn off file-overwriting checks.
ENVIRONMENT
COLUMNS The number of columns on the screen. This value overrides any system or terminal specific values. If the COLUMNS environment variable is not set when ex/vi runs, or the columns option
is explicitly reset by the user, ex/vi enters the value into the environment.
EXINIT

A list of ex startup commands; read if the variable NEXINIT is not set.

HOME

The users home directory, used as the initial directory path for the startup $HOME/.nexrc and
$HOME/.exrc files. This value is also used as the default directory for the vi cd command.

LINES

The number of rows on the screen. This value overrides any system or terminal specific values.
If the LINES environment variable is not set when ex/vi runs, or the lines option is explicitly
reset by the user, ex/vi enters the value into the environment.

NEXINIT A list of ex startup commands.


SHELL

The users shell of choice (see also the shell option).

TERM

The users terminal type. The default is the type unknown. If the TERM environment variable
is not set when ex/vi runs, or the term option is explicitly reset by the user, ex/vi enters the
value into the environment.

TMPDIR

The location used to stored temporary files (see also the directory edit option).

ASYNCHRONOUS EVENTS
SIGALRM vi/ex uses this signal for periodic backups of file modifications and to display busy messages when operations are likely to take a long time.
SIGHUP
SIGTERM

SIGINT

If the current buffer has changed since it was last written in its entirety, the editor attempts to
save the modified file so it can be later recovered. See the vi/ex reference manual section
Recovery for more information.
When an interrupt occurs, the current operation is halted and the editor returns to the command
level. If interrupted during text input, the text already input is resolved into the file as if the text
input had been normally terminated.

SIGWINCH The screen is resized. See the vi/ex reference manual section Sizing the Screen for more
information.
FILES

BSD

October 10, 1996

17

Property
of BladeLogic,
Inc.Manual
System General
Commands
Strictly confidential and proprietary

VI (1)

/bin/sh
/etc/vi.exrc
/tmp
/var/tmp/vi.recover
$HOME/.nexrc
$HOME/.exrc
.nexrc
.exrc

VI (1)

The default user shell.


System-wide vi startup file.
Temporary file directory.
The default recovery file directory.
First choice for users home directory startup file.
Second choice for users home directory startup file.
First choice for local directory startup file.
Second choice for local directory startup file.

SEE ALSO
ctags(1), re_format(7)
The "Vi Quick Reference" card, /usr/share/doc/usd/12.vi/vi.summary.
"An Introduction to Display Editing with Vi", /usr/share/doc/usd/12.vi/. This document is the
closest thing available to an introduction to the vi screen editor.
"Ex Reference Manual", /usr/share/doc/usd/13.ex/. This document is the final reference for the
ex editor.
"Ex: A Tutorial", /usr/share/doc/usd/11.edit/. This document is the closest thing available to an
introduction to the ex editor.
"Vi/Ex Reference Manual", /usr/share/doc/usd/13.viref/. This document is the final reference
for the nex/nvi text editors.
Roff source for all of these documents is distributed with nex/nvi in the vi/docs/USD.doc directory of
the nex/nvi source code.
The files autowrite, input, quoting, and structures found in the vi/docs/internals directory of the nex/nvi source code.
STANDARDS
nex/nvi is close to IEEE Std 1003.2 (POSIX.2). That document differs from historical ex/vi practice in
several places; there are changes to be made on both sides.
HISTORY
The nex/nvi replacements for the ex/vi editor first appeared in 4.4 BSD.

BSD

October 10, 1996

18

Property of BladeLogic, Inc.


Strictly confidential and proprietary

vsh(1)

vsh(1)

NAME
vsh Virtual shell (keyboard capture tool)

SYNOPSIS
vsh

DESCRIPTION
vsh is a keyboard (actually input and output) capture tool. It is called vsh (Virtual Shell) because once you
start it, it will start a shell (or other tty application) session and capture input and output. You can configure
the vsh.conf file to specify which shell vsh should start. vsh itself does not take any arguments. Instead, it
passes any arguments you give it to the backend shell specified in vsh.conf

VSH.CONF
The vsh.conf file controls the behavior of vsh. This file is located in share/vsh.conf in the NSH installation directory.
The format of this file is:
username <field=val[:val...]>[,<field=val[:val]>...]
The accepted fields are:
shell

logout

The application (shell) to start when you invoke vsh. If you do not specify a shell, vsh will use
/bin/sh by default. If you specify <nsh>, then vsh will try to launch NSH instead.
Example:

shell=/bin/ksh

Example:

shell=<nsh>

Set an optional auto logout time in minutes. If there is no input or output activity for the specified
number of minutes, vsh will automatically terminate the session.
Example:

log

logout=30

Name of log file where you want to store the vsh session I/O. vsh dynamically creates directories
for the log files as needed. You can specify multiple log files. You can use NSH format to name
the log files, meaning that you can specify a log file on a remote server with the //hostname/path format.
You should create one log file per session. You can use macros (defined below) in your log file
names to dynamically create unique names for each log file. If you have more than one session
logged into a particular log file, the vsh log file viewer, vshview, may not properly understand the
result.
Example:

level

log=/var/log/vshlog-%u.vsh

This defines what you want to log. The available values are:
stdin

Log all user keyboard input.

stdout

Log all terminal output.

stderr

Log all terminal error output (same as stdout).

all

All of the above.

You can capture any combination of I/O streams by defining multiple levels as colon (:) separated values.
Example:

level=stdin:stdout

DEFAULT ENTRY
If the username of the given entry has the special name of default, then this entry will be used for all
users that do not have a specific entry in the vsh.conf file.
The vsh.conf file comes pre-configured with a default entry, which is a shell of /bin/sh, an autologout of

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

vsh(1)

vsh(1)

60 minutes, and a log file in the format:


/var/log/vsh/<hostname>/<username>/<start timestamp>.vsh

MACROS
As previously mentioned, log file names should be unique for each vsh session. To do this, you must
dynamically create log file names by using macros, which are expanded at run time. The following macros
are supported.
%a The abbreviated weekday name.
%A
The full weekday name.
%b The abbreviated month name.
%B The full month name.
%C The century number (year/100) as a 2-digit integer.
%d The day of the month as a decimal number (range 01 to 31).
%h Current host name.
%H
The hour as a decimal number using a 24-hour clock (range 00 to 23).
%I The hour as a decimal number using a 12-hour clock (range 01 to 12).
%j The day of the year as a decimal number (range 001 to 366).
%m
The month as a decimal number (range 01 to 12).
%M
The minute as a decimal number (range 00 to 59).
%S The second as a decimal number (range 00 to 61).
%u Current user name.
%w
The day of the week as a decimal, range 0 to 6, Sunday being 0.
%y The year as a decimal number without a century (range 00 to 99).
%Y
The year as a decimal number including the century.
%%
A literal % character.

ORIGIN
vsh was written by Thomas Kraus

SEE ALSO
vshview (1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

vshview(1)

vshview(1)

NAME
vshview vsh log file viewer

SYNOPSIS
vshview [-012lbvHTU] [-e expr] [-h host] [-i date]
[-s sort] [-o date] [-u user] file1 [file2 ...]

DESCRIPTION
The keyboard (I/O) capture tool vsh does not create plain text log files. To view the these log files, you need
to use the vshview utility.
There are two basic modes to vshview. The first mode is to show selected input and output (default mode).
The second mode (turned on with the -l option), shows a summary of login and logout activity.
In either case, vshview scans the given log files and produces the appropriate output. If a given file is a
directory, vshview will automatically recursively scan all files in the given directory.

OPTIONS
-0

Show keyboard (stdin) input. This is the default output if you do not select any other output type.
Can be used with -1 and -2.

-1

Show terminal (stdout) output. Can be used with -0 and -2.

-2

Show error (stderr) output (same as -1).

-b

Do not show any blank lines.

-v

Show the name of the log file being displayed as it is reached.

-e

Define a search expression (see below).

-l

Do not output any keyboard input or screen output. Instead, just output a summary of vsh sessions.

-H

Precede each line of output with the name of the host it relates to.

-U

Precede each line of output with the name of the user it relates to.

-T

Precede each line of output with the most recent available timestamp. vsh creates a time stamp
every 60 seconds. Therefore, only one minute granularity is available.

-h host

Output only those entries that happened on host.

-u user

Output only those entries that relate to user.

-i date

Output only those entries that happened on or after this date. The date has the format
month/day/year with the year being optional. (Note that when using this option, you do not
have to escape the forward slash date separator.)

-s sort

You can specify the following options to sort your display: user, host, login, logout, logintime,
logouttime, shell, or pid.

-o date

Output only those entries that happened before this date. The date has the format
month/day/year with the year being optional. (Note that when using this option, you do not
have to escape the forward slash date separator.)

EXPRESSIONS
You can use the -e option to define an expression that filters the output data. The expression should be a
single argument surrounded by single quotes. Use the following format:
expr = ( expr ) | operand operator operand | operand
operand = number | string | field name
number = value | value% | octal value | hex value

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

vshview(1)

vshview(1)

value = <integer value> | <floating point value> | <long long value>


string = "<value>"
field name = <user> | <host> | logindate | logoutdate | \
logintime | logouttime | <shell> | <pid>
logindate = month/day/year
logoutdate = month/day/year
logintime = HH:MM
logouttime = HH:MM
Here is the operator precedence. Operators of the same precedence are grouped together by { }:
operator = + | - | / | * | % | & | \| | > | >= | < | <= | = | != \
{ * / % } { + - } { > >= < <= = != } & |
Some sample expressions:
user = "tmk"
user = "tmk" & host = "linuxdev"
user != "tmk" | logindate > Feb\/12
(logintime > 10:00 ) | (user = "tmk" & logintime > 8:00)

EXAMPLES
$ vshview -T -b /var/log/vsh
Feb 22/03 12:59:48: ls -la
Feb 22/03 13:14:53: ls
Feb 22/03 13:14:53: ls -la
Feb 22/03 13:19:08: echo $0
Feb 22/03 13:19:08: [k
Feb 22/03 13:19:08: ls
Feb 22/03 13:19:08: stty -a
Feb 22/03 13:19:08: exit
$ vshview -u tmk -l /var/log/vsh
HOSTNAME USER LOGIN TIME
LOGOUT TIME
PID SHELL
linuxdev tmk Feb 22/03 12:59:48 Feb 22/03 12:59:54 26958 /bin/nsh
linuxdev tmk Feb 22/03 13:14:50 Feb 22/03 13:14:56 27070 /bin/nsh
linuxdev tmk Feb 22/03 13:19:07 Feb 22/03 13:19:52 27204 /bin/bash

NOTE
vshview deals with two types of non-printable characters. The first type are the control characters (ASCII
0-31). These are are displayed as (for example) D. The second type are 8 bit characters. These are are
displayed as (for example) 207.

ORIGIN
vshview was written by Thomas Kraus

SEE ALSO
vsh (1).

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

vtree(1)

vtree(1)

NAME
vtree show the directory structure of a file system

SYNOPSIS
vtree [ -d ] [ -h # ] [ -i ] [ -s ] [ -q ] [ -v ] [ -V ] <target-dir>

DESCRIPTION
The vtree command shows the directory structure of a file system or part of a file system. It also shows the
amount of space taken up by files in each subdirectory.
If any of the given file names is a directory (the usual case), vtree recursively descends into it, and the output line reflects the accumulated totals for all files in the directory.

OPTIONS
-d

Count duplicate nodes.

-h #

Height of tree to examine.

-i

Count nodes.

-s

Include subdirectories that were excluded due to the -h option.

-t

Place totals at the end.

-q

Provide a quick display with no counts.

-v

Provide a visual display.

-V

Show the current version. Adding two more Vs displays the options that are set when you run this
command. For example:
johnk% vtree -VVV
VTREE 1.0
4/26/88
Tree height:
9999

<target-dir>
The directory whose structure you want to display.

EXAMPLE
In this example, vtree lists the file system of the less directory.
/space/home/parag/nsh/src/commands/less
/space/home/parag/nsh/src/commands/less
mands/less +-> lessQef ---+-> .svn ------+-> text-base
|
+-> prop-base
|
+-> props
|
+-> wcprops
|
> tmp -------+-> text-base
|
+-> prop-base
|
+-> props
|
> wcprops
+-> .svn ------+-> text-base
|
+-> prop-base
|
+-> props
|
+-> wcprops
|
> tmp -------+-> text-base
|
+-> prop-base
|
+-> props
|
> wcprops
> lesskey ---+-> .svn ------+-> text-base
+-> prop-base

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

vtree(1)

vtree(1)

+-> props
+-> wcprops
> tmp -------+-> text-base
+-> prop-base
+-> props
> wcprops
Total space used: 0
Total inodes: 0

ORIGIN
vtree vtree is based upon "agef," written by David S. Hayes at the Army Artificial Intelligence Center at the
Pentagon.

NSH

Property of BladeLogic, Inc.


Strictly confidential and proprietary

wc(1)

wc(1)

NAME
wc Count the number of lines, words and/or characters in a file

SYNOPSIS
wc [-clw?] [file ...]

DESCRIPTION
wc counts the number of lines, words, and characters in a file and then outputs its findings. If you do not
specify any files, wc uses the standard input. wc outputs four columns containing the number of lines, the
number of words, the number of characters, and (if available) the name of the file it is counting.
If you specify more than one file, wc will also output a total for all files.

OPTIONS
By default, wc counts lines, words, and characters. If you do not want counts for all of these things, you can
use the following options to tell wc which things you want it to count.
-c

Count the number of characters in the file.

-l

Count the number of lines in the file.

-w

Count the number of words in the file.

-?

Output a brief summary of available options and then exit with a zero status without counting any
files.

EXAMPLE
The first example counts the number of lines in the file /etc/passwd on the host lisbon. The second
example counts lines, words, and characters of several source files.
$ wc -l //lisbon/etc/passwd
14 //lisbon/etc/passwd
$ wc src/*.c
347
945
6227 file1.c
449
1334
8491 file2.c
339
917
6051 file3.c
1135
3196
20769 total

DIAGNOSTICS
wc: Cannot open file filename
This message is output if wc is unable to access the file filename.

EXIT CODES
0

No errors detected.

You specified an unknown option.

One of the files to be counted was not accessible.

255

Unable to get a license to use the software.

UNIVERSE BEHAVIOR
There is a small difference in the way wc formats the output depending on the current universe. Both
behaviors output a column in at least seven spaces, however when the P_BSD variable is set (Berkeley
behavior), an extra SPACE is output between columns to ensure that they never touch. With the P_ATT
variable set, it is possible that columns will touch for very large numbers.

ORIGIN
wc was written by Thomas Kraus

NSH

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIP ( 1L )

NAME

zip, zipcloak, zipnote, zipsplit package and compress (archive) files


SYNOPSIS

zip
[aABcdDeEfFghjklLmoqrRSTuvVwXyz!@$]
[tt mmddyyyy] [ zipfile [ file1 file2 . . .]] [xi list]

[b path]

[n suffixes]

[t mmddyyyy]

zipcloak [dhL] [b path] zipfile


zipnote [hwL] [b path] zipfile
zipsplit [hiLpst] [n size] [b path] zipfile
DESCRIPTION

zip is a compression and file packaging utility for Unix, VMS, MSDOS, OS/2, Windows NT, Minix, Atari
and Macintosh, Amiga and Acorn RISC OS.
It is analogous to a combination of the UNIX commands tar(1) and compress(1) and is compatible with
PKZIP (Phil Katzs ZIP for MSDOS systems).
A companion program (unzip(1L)), unpacks zip archives. The zip and unzip(1L) programs can work with
archives produced by PKZIP, and PKZIP and PKUNZIP can work with archives produced by zip. zip version 2.3 is compatible with PKZIP 2.04. Note that PKUNZIP 1.10 cannot extract files produced by PKZIP
2.04 or zip 2.3. You must use PKUNZIP 2.04g or unzip 5.0p1 (or later versions) to extract them.
For a brief help on zip and unzip, run each without specifying any parameters on the command line.
The program is useful for packaging a set of files for distribution; for archiving files; and for saving disk
space by temporarily compressing unused files or directories.
The zip program puts one or more compressed files into a single zip archive, along with information about
the files (name, path, date, time of last modification, protection, and check information to verify file
integrity). An entire directory structure can be packed into a zip archive with a single command. Compression ratios of 2:1 to 3:1 are common for text files. zip has one compression method (deflation) and can also
store files without compression. zip automatically chooses the better of the two for each file to be
compressed.
When given the name of an existing zip archive, zip will replace identically named entries in the zip archive
or add entries for new names. For example, if foo.zip exists and contains foo/file1 and foo/file2, and the
directory foo contains the files foo/file1 and foo/file3, then:
z i p - r f oo f oo
will replace foo/file1 in foo.zip and add foo/file3 to foo.zip. After this, foo.zip contains foo/file1, foo/file2,
and foo/file3, with foo/file2 unchanged from before.
If the file list is specified as @, [Not on MacOS] zip takes the list of input files from standard input. Under
UNIX, this option can be used to powerful effect in conjunction with the find(1) command. For example,
to archive all the C source files in the current directory and its subdirectories:
f i n d . - n a me " . [ c h ] " - p r i n t z i p s o u r c e - @
(note that the pattern must be quoted to keep the shell from expanding it). zip will also accept a single dash
("-") as the zip file name, in which case it will write the zip file to standard output, allowing the output to be
piped to another program. For example:
z i p - r - . d d o f =/ d e v / n r s t 0 o b s =1 6 k
would write the zip output directly to a tape with the specified block size for the purpose of backing up the
current directory.
zip also accepts a single dash ("-") as the name of a file to be compressed, in which case it will read the file
from standard input, allowing zip to take input from another program. For example:
t a r c f - . z i p ba c kup -

Info-ZIP

Last change: 14 August 1999 (v2.3)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIP ( 1L )

would compress the output of the tar command for the purpose of backing up the current directory. This
generally produces better compression than the previous example using the -r option, because zip can take
advantage of redundancy between files. The backup can be restored using the command
unzip -p backup | tar xf When no zip file name is given and stdout is not a terminal, zip acts as a filter, compressing standard input
to standard output. For example,
tar cf - . | zip | dd of=/dev/nrst0 obs=16k
is equivalent to
tar cf - . | zip - - | dd of=/dev/nrst0 obs=16k
zip archives created in this manner can be extracted with the program funzip which is provided in the unzip
package, or by gunzip which is provided in the gzip package. For example:
dd if=/dev/nrst0 ibs=16k funzip tar xvf When changing an existing zip archive, zip will write a temporary file with the new contents, and only
replace the old one when the process of creating the new version has been completed without error.
If the name of the zip archive does not contain an extension, the extension .zip is added. If the name already
contains an extension other than .zip the existing extension is kept unchanged.
OPTIONS

[Systems using EBCDIC] Translate file to ASCII format.

Adjust self-extracting executable archive. A self-extracting executable archive is created by


prepending the SFX stub to an existing archive. The A option tells zip to adjust the entry offsets
stored in the archive to take into account this "preamble" data.

Note: self-extracting archives for the Amiga are a special case. At present, only the Amiga port of Zip is
capable of adjusting or updating these without corrupting them. -J can be used to remove the SFX stub if
other updates need to be made.
B

[VM/CMS and MVS] force file to be read binary (default is text).

Bn

[TANDEM] set Edit/Enscribe formatting options with n defined as


bit 0: Dont add delimiter (Edit/Enscribe)
bit 1: Use LF rather than CR/LF as delimiter (Edit/Enscribe)
bit 2: Space fill record to maximum record length (Enscribe)
bit 3: Trim trailing space (Enscribe)
bit 8: Force 30K (Expand) large read for unstructured files

b path Use the specified path for the temporary zip archive. For example:
zip -b /tmp stuff
will put the temporary zip archive in the directory /tmp, copying over stuff.zip to the current directory when done. This option is only useful when updating an existing archive, and the file system
containing this old archive does not have enough space to hold both old and new archives at the
same time.
c

Add one-line comments for each file. File operations (adding, updating) are done first, and the
user is then prompted for a one-line comment for each file. Enter the comment followed by return,
or just return for no comment.

Remove (delete) entries from a zip archive. For example:


zip -d foo foo/tom/junk foo/harry/\ \.o
will remove the entry foo/tom/junk, all of the files that start with foo/harry/, and all of the files that
end with .o (in any path). Note that shell pathname expansion has been inhibited with backslashes,
so that zip can see the asterisks, enabling zip to match on the contents of the zip archive instead of

Info-ZIP

Last change: 14 August 1999 (v2.3)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIP ( 1L )

the contents of the current directory.


Under MSDOS, d is case sensitive when it matches names in the zip archive. This requires that
file names be entered in upper case if they were zipped by PKZIP on an MSDOS system.
df

[MacOS] Include only data-fork of files zipped into the archive. Good for exporting files to
foreign operating-systems. Resource-forks will be ignored at all.

Do not create entries in the zip archive for directories. Directory entries are created by default so
that their attributes can be saved in the zip archive. The environment variable ZIPOPT can be
used to change the default options. For example under Unix with sh:
ZIPOPT="-D"; export ZIPOPT
(The variable ZIPOPT can be used for any option except i and x and can include several
options.) The option D is a shorthand for x "/" but the latter cannot be set as default in the
ZIPOPT environment variable.

Encrypt the contents of the zip archive using a password which is entered on the terminal in
response to a prompt (this will not be echoed; if standard error is not a tty, zip will exit with an
error). The password prompt is repeated to save the user from typing errors.

[OS/2] Use the .LONGNAME Extended Attribute (if found) as filename.

Replace (freshen) an existing entry in the zip archive only if it has been modified more recently
than the version already in the zip archive; unlike the update option (u) this will not add files that
are not already in the zip archive. For example:
zip -f foo
This command should be run from the same directory from which the original zip command was
run, since paths stored in zip archives are always relative.
Note that the timezone environment variable TZ should be set according to the local timezone in
order for the -f , -u and -o options to work correctly.
The reasons behind this are somewhat subtle but have to do with the differences between the
Unix-format file times (always in GMT) and most of the other operating systems (always local
time) and the necessity to compare the two. A typical TZ value is MET-1MEST (Middle European time with automatic adjustment for summertime or Daylight Savings Time).

Fix the zip archive. This option can be used if some portions of the archive are missing. It is not
guaranteed to work, so you MUST make a backup of the original archive first.
When doubled as in FF the compressed sizes given inside the damaged archive are not trusted
and zip scans for special signatures to identify the limits between the archive members. The single
F is more reliable if the archive is not too much damaged, for example if it has only been truncated, so try this option first.
Neither option will recover archives that have been incorrectly transferred in ascii mode instead of
binary. After the repair, the t option of unzip may show that some files have a bad CRC. Such
files cannot be recovered; you can remove them from the archive using the d option of zip.

Grow (append to) the specified zip archive, instead of creating a new one. If this operation fails,
zip attempts to restore the archive to its original state. If the restoration fails, the archive might
become corrupted. This option is ignored when theres no existing archive or when at least one
archive member must be updated or deleted.

Display the zip help information (this also appears if zip is run with no arguments).

i files Include only the specified files, as in:


zip -r foo . -i \.c
which will include only the files that end in .c in the current directory and its subdirectories. (Note

Info-ZIP

Last change: 14 August 1999 (v2.3)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIP ( 1L )

for PKZIP users: the equivalent command is


pkzip -rP foo .c
PKZIP does not allow recursion in directories other than the current one.) The backslash avoids
the shell filename substitution, so that the name matching is performed by zip at all directory levels.
Also possible:
zip -r foo

. -i@include.lst

which will only include the files in the current directory and its subdirectories that match the patterns in the file include.lst.
I

[Acorn RISC OS] Dont scan through Image files. When used, zip will not consider Image files
(eg. DOS partitions or Spark archives when SparkFS is loaded) as directories but will store them
as single files.
For example, if you have SparkFS loaded, zipping a Spark archive will result in a zipfile containing a directory (and its content) while using the I option will result in a zipfile containing a Spark
archive. Obviously this second case will also be obtained (without the I option) if SparkFS isnt
loaded.

Store just the name of a saved file (junk the path), and do not store directory names. By default, zip
will store the full path (relative to the current path).

jj

[MacOS] record Fullpath (+ Volname). The complete path including volume will be stored. By
default the relative path will be stored.

Strip any prepended data (e.g. a SFX stub) from the archive.

Attempt to convert the names and paths to conform to MSDOS, store only the MSDOS attribute
(just the user write attribute from UNIX), and mark the entry as made under MSDOS (even though
it was not); for compatibility with PKUNZIP under MSDOS which cannot handle certain names
such as those with two dots.

Translate the Unix end-of-line character LF into the MSDOS convention CR LF. This option
should not be used on binary files. This option can be used on Unix if the zip file is intended for
PKUNZIP under MSDOS. If the input files already contain CR LF, this option adds an extra CR.
This ensure that unzip -a on Unix will get back an exact copy of the original file, to undo the effect
of zip -l.

ll

Translate the MSDOS end-of-line CR LF into Unix LF. This option should not be used on binary
files. This option can be used on MSDOS if the zip file is intended for unzip under Unix.

Display the zip license.

Move the specified files into the zip archive; actually, this deletes the target directories/files after
making the specified zip archive. If a directory becomes empty after removal of the files, the directory is also removed. No deletions are done until zip has created the archive without error. This is
useful for conserving disk space, but is potentially dangerous so it is recommended to use it in
combination with T to test the archive before removing all input files.

n suffixes
Do not attempt to compress files named with the given suffixes. Such files are simply stored (0%
compression) in the output zip file, so that zip doesnt waste its time trying to compress them. The
suffixes are separated by either colons or semicolons. For example:
zip -rn .Z:.zip:.tiff:.gif:.snd

foo foo

will copy everything from foo into foo.zip, but will store any files that end in .Z, .zip, .tiff, .gif, or
.snd without trying to compress them (image and sound files often have their own specialized
compression methods). By default, zip does not compress files with extensions in the list

Info-ZIP

Last change: 14 August 1999 (v2.3)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIP ( 1L )

.Z:.zip:.zoo:.arc:.lzh:.arj. Such files are stored directly in the output archive. The environment
variable ZIPOPT can be used to change the default options. For example under Unix with csh:
setenv ZIPOPT "-n .gif:.zip"
To attempt compression on all files, use:
zip -n : foo
The maximum compression option 9 also attempts compression on all files regardless of extension.
On Acorn RISC OS systems the suffixes are actually filetypes (3 hex digit format). By default, zip
does not compress files with filetypes in the list DDC:D96:68E (i.e. Archives, CFS files and PackDir files).
N

[Amiga, MacOS] Save Amiga or MacOS filenotes as zipfile comments. They can be restored by
using the -N option of unzip. If -c is used also, you are prompted for comments only for those files
that do not have filenotes.

Set the "last modified" time of the zip archive to the latest (oldest) "last modified" time found
among the entries in the zip archive. This can be used without any other operations, if desired.
For example:
zip -o foo
will change the last modified time of foo.zip to the latest time of the entries in foo.zip.
In this case, all the files and directories in foo are saved in a zip archive named foo.zip, including
files with names starting with ".", since the recursion does not use the shells file-name substitution
mechanism. If you wish to include only a specific subset of the files in directory foo and its subdirectories, use the i option to specify the pattern of files to be included. You should not use r
with the name ".", since that matches ".." which will attempt to zip up the parent directory (probably not what was intended).

Travel the directory structure recursively starting at the current directory; for example:
zip -R foo .c
In this case, all the files matching .c in the tree starting at the current directory are stored into a
zip archive named foo.zip. Note for PKZIP users: the equivalent command is
pkzip -rP foo .c

[MSDOS, OS/2, WIN32 and ATARI] Include system and hidden files.
[MacOS] Includes finder invisible files, which are ignored otherwise.

t mmddyyyy
Do not operate on files modified prior to the specified date, where mm is the month (0-12), dd is
the day of the month (1-31), and yyyy is the year. The ISO 8601 date format yyyy-mm-dd is also
accepted. For example:
zip -rt 12071991 infamy foo
zip -rt 1991-12-07 infamy foo
will add all the files in foo and its subdirectories that were last modified on or after 7 December
1991, to the zip archive infamy.zip.
tt mmddyyyy
Do not operate on files modified after or at the specified date, where mm is the month (0-12), dd is
the day of the month (1-31), and yyyy is the year. The ISO 8601 date format yyyy-mm-dd is also
accepted. For example:
zip -rtt 11301995 infamy foo

Info-ZIP

Last change: 14 August 1999 (v2.3)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIP ( 1L )

zip -rtt 1995-11-30 infamy foo


will add all the files in foo and its subdirectories that were last modified before the 30 November
1995, to the zip archive infamy.zip.
T

Test the integrity of the new zip file. If the check fails, the old zip file is unchanged and (with the
-m option) no input files are removed.

Replace (update) an existing entry in the zip archive only if it has been modified more recently
than the version already in the zip archive. For example:
zip -u stuff
will add any new files in the current directory, and update any files which have been modified
since the zip archive stuff.zip was last created/modified (note that zip will not try to pack stuff.zip
into itself when you do this).
Note that the u option with no arguments acts like the f (freshen) option.

Verbose mode or print diagnostic version info.


Normally, when applied to real operations, this option enables the display of a progress indicator
during compression and requests verbose diagnostic info about zipfile structure oddities.
When v is the only command line argument, and stdout is not redirected to a file, a diagnostic
screen is printed. In addition to the help screen header with program name, version, and release
date, some pointers to the Info-ZIP home and distribution sites are given. Then, it shows information about the target environment (compiler type and version, OS version, compilation date and
the enabled optional features used to create the zip executable.

[VMS] Save VMS file attributes. zip archives created with this option will generally not be usable
on other systems.

[VMS] Append the version number of the files to the name, including multiple versions of files.
(default: use only the most recent version of a specified file).

x files Explicitly exclude the specified files, as in:


zip -r foo foo -x \.o
which will include the contents of foo in foo.zip while excluding all the files that end in .o. The
backslash avoids the shell filename substitution, so that the name matching is performed by zip at
all directory levels.
Also possible:
zip -r foo foo -x@exclude.lst
which will include the contents of foo in foo.zip while excluding all the files that match the patterns in the file exclude.lst.
X

Do not save extra file attributes (Extended Attributes on OS/2, uid/gid and file times on Unix).

Store symbolic links as such in the zip archive, instead of compressing and storing the file referred
to by the link (UNIX only).

Prompt for a multi-line comment for the entire zip archive. The comment is ended by a line containing just a period, or an end of file condition (D on UNIX, Z on MSDOS, OS/2, and
VAX/VMS). The comment can be taken from a file:
zip -z foo < foowhat

Info-ZIP

Regulate the speed of compression using the specified digit #, where 0 indicates no compression
(store all files), 1 indicates the fastest compression method (less compression) and 9 indicates
the slowest compression method (optimal compression, ignores the suffix list). The default
compression level is 6.

Last change: 14 August 1999 (v2.3)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIP ( 1L )

[WIN32] Use priviliges (if granted) to obtain all aspects of WinNT security.

Take the list of input files from standard input. Only one filename per line.

[MSDOS, OS/2, WIN32] Include the volume label for the the drive holding the first file to be
compressed. If you want to include only the volume label or to force a specific drive, use the drive
name as first file name, as in:
zip -$ foo a: c:bar

EXAMPLES

The simplest example:


zip stuff
creates the archive stuff.zip (assuming it does not exist) and puts all the files in the current directory in it, in
compressed form (the .zip suffix is added automatically, unless that archive name given contains a dot
already; this allows the explicit specification of other suffixes).
Because of the way the shell does filename substitution, files starting with "." are not included; to include
these as well:
zip stuff .
Even this will not include any subdirectories from the current directory.
To zip up an entire directory, the command:
zip -r foo foo
creates the archive foo.zip, containing all the files and directories in the directory foo that is contained
within the current directory.
You may want to make a zip archive that contains the files in foo, without recording the directory name,
foo. You can use the j option to leave off the paths, as in:
zip -j foo foo/
If you are short on disk space, you might not have enough room to hold both the original directory and the
corresponding compressed zip archive. In this case, you can create the archive in steps using the m
option. If foo contains the subdirectories tom, dick, and harry, you can:
zip -rm foo foo/tom
zip -rm foo foo/dick
zip -rm foo foo/harry
where the first command creates foo.zip, and the next two add to it. At the completion of each zip command, the last created archive is deleted, making room for the next zip command to function.
PATTERN MATCHING

This section applies only to UNIX. Watch this space for details on MSDOS and VMS operation.
The UNIX shells (sh(1) and csh(1)) do filename substitution on command arguments. The special characters are:
?

match any single character

match any number of characters (including none)

[]

match any character in the range indicated within the brackets (example: [af], [09]).

When these characters are encountered (without being escaped with a backslash or quotes), the shell will
look for files relative to the current path that match the pattern, and replace the argument with a list of the
names that matched.

Info-ZIP

Last change: 14 August 1999 (v2.3)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIP ( 1L )

The zip program can do the same matching on names that are in the zip archive being modified or, in the
case of the x (exclude) or i (include) options, on the list of files to be operated on, by using backslashes
or quotes to tell the shell not to do the name expansion. In general, when zip encounters a name in the list
of files to do, it first looks for the name in the file system. If it finds it, it then adds it to the list of files to
do. If it does not find it, it looks for the name in the zip archive being modified (if it exists), using the pattern matching characters described above, if present. For each match, it will add that name to the list of
files to be processed, unless this name matches one given with the x option, or does not match any name
given with the i option.
The pattern matching includes the path, and so patterns like \.o match names that end in ".o", no matter
what the path prefix is. Note that the backslash must precede every special character (i.e. ?[]), or the entire
argument must be enclosed in double quotes ("").
In general, use backslash to make zip do the pattern matching with the f (freshen) and d (delete) options,
and sometimes after the x (exclude) option when used with an appropriate operation (add, u, f, or d).
ENVIRONMENT

ZIPOPT
contains default options that will be used when running zip
ZIP

[Not on RISC OS and VMS] see ZIPOPT

Zip$Options
[RISC OS] see ZIPOPT
Zip$Exts
[RISC OS] contains extensions separated by a : that will cause native filenames with one of the
specified extensions to be added to the zip file with basename and extension swapped. zip
ZIP_OPTS
[VMS] see ZIPOPT
SEE ALSO

compress(1), shar(1L), tar(1), unzip(1L), gzip(1L)


DIAGNOSTICS

The exit status (or error level) approximates the exit codes defined by PKWARE and takes on the following
values, except under VMS:

Info-ZIP

normal; no errors or warnings detected.

unexpected end of zip file.

a generic error in the zipfile format was detected. Processing may have completed successfully anyway; some broken zipfiles created by other archivers have simple workarounds.

zip was unable to allocate memory for one or more buffers during program initialization.

a severe error in the zipfile format was detected. Processing probably failed immediately.

entry too large to be split with zipsplit

invalid comment format

zip -T failed or out of memory

the user aborted zip prematurely with control-C (or similar)

10

zip encountered an error while using a temp file

11

read or seek error

12

zip has nothing to do

13

missing or empty zip file

Last change: 14 August 1999 (v2.3)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

14

error writing to a file

15

zip was unable to create a file to write to

16

bad command line parameters

18

zip could not open a specified file to read

ZIP ( 1L )

VMS interprets standard Unix (or PC) return values as other, scarier-looking things, so zip instead maps
them into VMS-style status codes. The current mapping is as follows: 1 (success) for normal exit,
and (0x7fff000? + 16normal_zip_exit_status) for all errors, where the ? is 0 (warning) for zip value 12, 2
(error) for the zip values 3, 6, 7, 9, 13, 16, 18, and 4 (fatal error) for the remaining ones.
BUGS

zip 2.3 is not compatible with PKUNZIP 1.10. Use zip 1.1 to produce zip files which can be extracted by
PKUNZIP 1.10.
zip files produced by zip 2.3 must not be updated by zip 1.1 or PKZIP 1.10, if they contain encrypted
members or if they have been produced in a pipe or on a non-seekable device. The old versions of zip or
PKZIP would create an archive with an incorrect format. The old versions can list the contents of the zip
file but cannot extract it anyway (because of the new compression algorithm). If you do not use encryption
and use regular disk files, you do not have to care about this problem.
Under VMS, not all of the odd file formats are treated properly. Only stream-LF format zip files are
expected to work with zip. Others can be converted using Rahul Dhesis BILF program. This version of
zip handles some of the conversion internally. When using Kermit to transfer zip files from Vax to
MSDOS, type "set file type block" on the Vax. When transfering from MSDOS to Vax, type "set file type
fixed" on the Vax. In both cases, type "set file type binary" on MSDOS.
Under VMS, zip hangs for file specification that uses DECnet syntax foo::..
On OS/2, zip cannot match some names, such as those including an exclamation mark or a hash sign. This
is a bug in OS/2 itself: the 32-bit DosFindFirst/Next dont find such names. Other programs such as GNU
tar are also affected by this bug.
Under OS/2, the amount of Extended Attributes displayed by DIR is (for compatibility) the amount
returned by the 16-bit version of DosQueryPathInfo(). Otherwise OS/2 1.3 and 2.0 would report different
EA sizes when DIRing a file. However, the structure layout returned by the 32-bit DosQueryPathInfo() is a
bit different, it uses extra padding bytes and link pointers (its a linked list) to have all fields on 4-byte
boundaries for portability to future RISC OS/2 versions. Therefore the value reported by zip (which uses
this 32-bit-mode size) differs from that reported by DIR. zip stores the 32-bit format for portability, even
the 16-bit MS-C-compiled version running on OS/2 1.3, so even this one shows the 32-bit-mode size.
AUTHORS

Copyright (C) 1990-1997 Mark Adler, Richard B. Wales, Jean-loup Gailly, Onno van der Linden, Kai Uwe
Rommel, Igor Mandrichenko, John Bush and Paul Kienitz. Permission is granted to any individual or institution to use, copy, or redistribute this software so long as all of the original files are included, that it is not
sold for profit, and that this copyright notice is retained.
LIKE ANYTHING ELSE THATS FREE, ZIP AND ITS ASSOCIATED UTILITIES ARE PROVIDED
AS IS AND COME WITH NO WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED. IN
NO EVENT WILL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES RESULTING
FROM THE USE OF THIS SOFTWARE.
Please send bug reports and comments by email to: zipbugs@lists.wku.edu. For bug reports, please
include the version of zip (see ziph ), the make options used to compile it see zipv ), the machine and
operating system in use, and as much additional information as possible.
ACKNOWLEDGEMENTS

Thanks to R. P. Byrne for his Shrink.Pas program, which inspired this project, and from which the shrink
algorithm was stolen; to Phil Katz for placing in the public domain the zip file format, compression format,
and .ZIP filename extension, and for accepting minor changes to the file format; to Steve Burg for

Info-ZIP

Last change: 14 August 1999 (v2.3)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIP ( 1L )

clarifications on the deflate format; to Haruhiko Okumura and Leonid Broukhis for providing some useful
ideas for the compression algorithm; to Keith Petersen, Rich Wales, Hunter Goatley and Mark Adler for
providing a mailing list and ftp site for the Info-ZIP group to use; and most importantly, to the Info-ZIP
group itself (listed in the file infozip.who) without whose tireless testing and bug-fixing efforts a portable
zip would not have been possible. Finally we should thank (blame) the first Info-ZIP moderator, David
Kirschbaum, for getting us into this mess in the first place. The manual page was rewritten for UNIX by R.
P. C. Rodgers.

Info-ZIP

Last change: 14 August 1999 (v2.3)

10

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIPGREP ( 1L )

NAME

zipgrep search files in a ZIP archive for lines matching a pattern


SYNOPSIS

zipgrep [egrep_options] pattern file[.zip] [file(s) . . .] [x xfile(s) . . .]


DESCRIPTION

zipgrep will search files within a ZIP archive for lines matching the given string or pattern. zipgrep is a
shell script and requires egrep(1) and unzip(1L) to function. Its output is identical to that of egrep(1).
ARGUMENTS

All options prior to the ZIP archive filename are passed to egrep(1).
SEE ALSO

egrep(1), unzip(1L), zip(1L), funzip(1L), zipcloak(1L), zipinfo(1L), zipnote(1L), zipsplit(1L)


URL

The Info-ZIP home page is currently at h t t p : / / www. i n f o - z i p . o r g / p u b / i n f o z i p /


f t p: / / f t p. i nf o- z i p. or g/ pub/ i nf oz i p/ .

or

AUTHORS

zipgrep was written by Jean-loup Gailly.

Info-ZIP

Last change: 14 January 2001

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIPINFO ( 1L )

NAME

zipinfo list detailed information about a ZIP archive


SYNOPSIS

zipinfo [12smlvhMtTz] file[.zip] [file(s) . . .] [x xfile(s) . . .]


unzip Z [12smlvhMtTz] file[.zip] [file(s) . . .] [x xfile(s) . . .]
DESCRIPTION

zipinfo lists technical information about files in a ZIP archive, most commonly found on MS-DOS systems.
Such information includes file access permissions, encryption status, type of compression, version and
operating system or file system of compressing program, and the like. The default behavior (with no
options) is to list single-line entries for each file in the archive, with header and trailer lines providing summary information for the entire archive. The format is a cross between Unix l s l and u n z i p v
output. See DETAILED DESCRIPTION below. Note that zipinfo is the same program as unzip (under
Unix, a link to it); on some systems, however, zipinfo support may have been omitted when unzip was compiled.
ARGUMENTS

file[.zip]
Path of the ZIP archive(s). If the file specification is a wildcard, each matching file is processed in
an order determined by the operating system (or file system). Only the filename can be a wildcard;
the path itself cannot. Wildcard expressions are similar to Unix egrep(1) (regular) expressions and
may contain:

matches a sequence of 0 or more characters

matches exactly 1 character

[. . .]

matches any single character found inside the brackets; ranges are specified by a beginning character, a hyphen, and an ending character. If an exclamation point or a caret (!
or ) follows the left bracket, then the range of characters within the brackets is complemented (that is, anything except the characters inside the brackets is considered a match).

(Be sure to quote any character that might otherwise be interpreted or modified by the operating
system, particularly under Unix and VMS.) If no matches are found, the specification is assumed
to be a literal filename; and if that also fails, the suffix . z i p is appended. Note that selfextracting ZIP files are supported; just specify the . e x e suffix (if any) explicitly.
[file(s)] An optional list of archive members to be processed. Regular expressions (wildcards) may be
used to match multiple members; see above. Again, be sure to quote expressions that would otherwise be expanded or modified by the operating system.
[x xfile(s)]
An optional list of archive members to be excluded from processing.
OPTIONS

Info-ZIP

list filenames only, one per line. This option excludes all others; headers, trailers and zipfile comments are never printed. It is intended for use in Unix shell scripts.

list filenames only, one per line, but allow headers (h), trailers (t) and zipfile comments (z), as
well. This option may be useful in cases where the stored filenames are particularly long.

list zipfile info in short Unix l s l format. This is the default behavior; see below.

list zipfile info in medium Unix l s l format. Identical to the s output, except that the
compression factor, expressed as a percentage, is also listed.

list zipfile info in long Unix l s l format. As with m except that the compressed size (in
bytes) is printed instead of the compression ratio.

list zipfile information in verbose, multi-page format.

list header line. The archive name, actual size (in bytes) and total number of files is printed.

Last change: 14 January 2001 (v2.32)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIPINFO ( 1L )

pipe all output through an internal pager similar to the Unix more(1) command. At the end of a
screenful of output, zipinfo pauses with a More prompt; the next screenful may be viewed
by pressing the Enter (Return) key or the space bar. zipinfo can be terminated by pressing the q
key and, on some systems, the Enter/Return key. Unlike Unix more(1), there is no forwardsearching or editing capability. Also, zipinfo doesnt notice if long lines wrap at the edge of the
screen, effectively resulting in the printing of two or more lines and the likelihood that some text
will scroll off the top of the screen before being viewed. On some systems the number of available
lines on the screen is not detected, in which case zipinfo assumes the height is 24 lines.

list totals for files listed or for all files. The number of files listed, their uncompressed and
compressed total sizes, and their overall compression factor is printed; or, if only the totals line is
being printed, the values for the entire archive are given. Note that the total compressed (data) size
will never match the actual zipfile size, since the latter includes all of the internal zipfile headers in
addition to the compressed data.

print the file dates and times in a sortable decimal format (yymmdd.hhmmss). The default date
format is a more standard, human-readable version with abbreviated month names (see examples
below).

include the archive comment (if any) in the listing.

DETAILED DESCRIPTION

zipinfo has a number of modes, and its behavior can be rather difficult to fathom if one isnt familiar with
Unix ls(1) (or even if one is). The default behavior is to list files in the following format:
-rw-rws---

1.9 unx

2802 t- defX 11-Aug-91 13:48 perms.2660

The last three fields are the modification date and time of the file, and its name. The case of the filename is
respected; thus files that come from MS-DOS PKZIP are always capitalized. If the file was zipped with a
stored directory name, that is also displayed as part of the filename.
The second and third fields indicate that the file was zipped under Unix with version 1.9 of zip. Since it
comes from Unix, the file permissions at the beginning of the line are printed in Unix format. The
uncompressed file-size (2802 in this example) is the fourth field.
The fifth field consists of two characters, either of which may take on several values. The first character
may be either t or b, indicating that zip believes the file to be text or binary, respectively; but if the file is
encrypted, zipinfo notes this fact by capitalizing the character (T or B). The second character may also
take on four values, depending on whether there is an extended local header and/or an extra field associated with the file (fully explained in PKWares APPNOTE.TXT, but basically analogous to pragmas in
ANSI C--i.e., they provide a standard way to include non-standard information in the archive). If neither
exists, the character will be a hyphen (); if there is an extended local header but no extra field, l; if the
reverse, x; and if both exist, X. Thus the file in this example is (probably) a text file, is not encrypted,
and has neither an extra field nor an extended local header associated with it. The example below, on the
other hand, is an encrypted binary file with an extra field:
RWD,R,R

0.9 vms

168 Bx shrk

9-Aug-91 19:15 perms.0644

Extra fields are used for various purposes (see discussion of the v option below) including the storage of
VMS file attributes, which is presumably the case here. Note that the file attributes are listed in VMS format. Some other possibilities for the host operating system (which is actually a misnomer--host file system
is more correct) include OS/2 or NT with High Performance File System (HPFS), MS-DOS, OS/2 or NT
with File Allocation Table (FAT) file system, and Macintosh. These are denoted as follows:
-rw-a--r--ahs
--w-------

1.0 hpf
1.1 fat
1.0 mac

5358 Tl i4:3 4-Dec-91 11:33 longfilename.hpfs


4096 b- i4:2 14-Jul-91 12:58 EA DATA. SF
17357 bx i8:2 4-May-92 04:02 unzip.macr

File attributes in the first two cases are indicated in a Unix-like format, where the seven subfields indicate
whether the file: (1) is a directory, (2) is readable (always true), (3) is writable, (4) is executable (guessed
on the basis of the extension--.exe, .com, .bat, .cmd and .btm files are assumed to be so), (5) has its archive

Info-ZIP

Last change: 14 January 2001 (v2.32)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIPINFO ( 1L )

bit set, (6) is hidden, and (7) is a system file. Interpretation of Macintosh file attributes is unreliable
because some Macintosh archivers dont store any attributes in the archive.
Finally, the sixth field indicates the compression method and possible sub-method used. There are six
methods known at present: storing (no compression), reducing, shrinking, imploding, tokenizing (never
publicly released), and deflating. In addition, there are four levels of reducing (1 through 4); four types of
imploding (4K or 8K sliding dictionary, and 2 or 3 Shannon-Fano trees); and four levels of deflating (superfast, fast, normal, maximum compression). zipinfo represents these methods and their sub-methods as follows: stor; re:1, re:2, etc.; shrk; i4:2, i8:3, etc.; tokn; and defS, defF, defN, and defX.
The medium and long listings are almost identical to the short format except that they add information on
the files compression. The medium format lists the files compression factor as a percentage indicating the
amount of space that has been removed:
-rw-rws---

1.5 unx

2802 t- 81% defX 11-Aug-91 13:48 perms.2660

In this example, the file has been compressed by more than a factor of five; the compressed data are only
19% of the original size. The long format gives the compressed files size in bytes, instead:
-rw-rws---

1.5 unx

2802 t-

538 defX 11-Aug-91 13:48 perms.2660

Adding the T option changes the file date and time to decimal format:
-rw-rws---

1.5 unx

2802 t-

538 defX 910811.134804 perms.2660

Note that because of limitations in the MS-DOS format used to store file times, the seconds field is always
rounded to the nearest even second. For Unix files this is expected to change in the next major releases of
zip(1L) and unzip.
In addition to individual file information, a default zipfile listing also includes header and trailer lines:
Archive: OS2.zip
5453 bytes
5 files
,,rw,
1.0 hpf
730 b- i4:3 26-Jun-92
,,rw,
1.0 hpf
3710 b- i4:3 26-Jun-92
,,rw,
1.0 hpf
8753 b- i8:3 26-Jun-92
,,rw,
1.0 hpf
98 b- stor 21-Aug-91
,,rw,
1.0 hpf
95 b- stor 21-Aug-91
5 files, 13386 bytes uncompressed, 4951 bytes

23:40 Contents
23:33 makefile.os2
15:29 os2unzip.c
15:34 unzip.def
17:51 zipinfo.def
compressed: 63.0%

The header line gives the name of the archive, its total size, and the total number of files; the trailer gives
the number of files listed, their total uncompressed size, and their total compressed size (not including any
of zips internal overhead). If, however, one or more file(s) are provided, the header and trailer lines are not
listed. This behavior is also similar to that of Unixs ls l; it may be overridden by specifying the h
and t options explicitly. In such a case the listing format must also be specified explicitly, since h or t
(or both) in the absence of other options implies that ONLY the header or trailer line (or both) is listed. See
the EXAMPLES section below for a semi-intelligible translation of this nonsense.
The verbose listing is mostly self-explanatory. It also lists file comments and the zipfile comment, if any,
and the type and number of bytes in any stored extra fields. Currently known types of extra fields include
PKWAREs authentication (AV) info; OS/2 extended attributes; VMS filesystem info, both PKWARE
and Info-ZIP versions; Macintosh resource forks; Acorn/Archimedes SparkFS info; and so on. (Note that
in the case of OS/2 extended attributes--perhaps the most common use of zipfile extra fields--the size of the
stored EAs as reported by zipinfo may not match the number given by OS/2s dir command: OS/2 always
reports the number of bytes required in 16-bit format, whereas zipinfo always reports the 32-bit storage.)
ENVIRONMENT OPTIONS

Modifying zipinfos default behavior via options placed in an environment variable can be a bit complicated
to explain, due to zipinfos attempts to handle various defaults in an intuitive, yet Unix-like, manner. (Try
not to laugh.) Nevertheless, there is some underlying logic. In brief, there are three priority levels of
options: the default options; environment options, which can override or add to the defaults; and explicit
options given by the user, which can override or add to either of the above.

Info-ZIP

Last change: 14 January 2001 (v2.32)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIPINFO ( 1L )

The default listing format, as noted above, corresponds roughly to the "zipinfo hst" command
(except when individual zipfile members are specified). A user who prefers the long-listing format (l) can
make use of the zipinfos environment variable to change this default:
ZIPINFO=l; export ZIPINFO
setenv ZIPINFO l
set ZIPINFO=l
define ZIPINFO_OPTS "l"

Unix Bourne shell


Unix C shell
OS/2 or MS-DOS
VMS (quotes for lowercase)

If, in addition, the user dislikes the trailer line, zipinfos concept of negative options may be used to
override the default inclusion of the line. This is accomplished by preceding the undesired option with one
or more minuses: e.g., lt or tl, in this example. The first hyphen is the regular switch character, but the one before the t is a minus sign. The dual use of hyphens may seem a little awkward, but
its reasonably intuitive nonetheless: simply ignore the first hyphen and go from there. It is also consistent
with the behavior of the Unix command nice(1).
As suggested above, the default variable names are ZIPINFO_OPTS for VMS (where the symbol used to
install zipinfo as a foreign command would otherwise be confused with the environment variable), and
ZIPINFO for all other operating systems. For compatibility with zip(1L), ZIPINFOOPT is also accepted
(dont ask). If both ZIPINFO and ZIPINFOOPT are defined, however, ZIPINFO takes precedence. unzips
diagnostic option (v with no zipfile name) can be used to check the values of all four possible unzip and
zipinfo environment variables.
EXAMPLES

To get a basic, short-format listing of the complete contents of a ZIP archive storage.zip, with both header
and totals lines, use only the archive name as an argument to zipinfo:
zipinfo storage
To produce a basic, long-format listing (not verbose), including header and totals lines, use l:
zipinfo l storage
To list the complete contents of the archive without header and totals lines, either negate the h and t
options or else specify the contents explicitly:
zipinfo ht storage
zipinfo storage \
(where the backslash is required only if the shell would otherwise expand the wildcard, as in Unix when
globbing is turned on--double quotes around the asterisk would have worked as well). To turn off the totals
line by default, use the environment variable (C shell is assumed here):
setenv ZIPINFO t
zipinfo storage
To get the full, short-format listing of the first example again, given that the environment variable is set as
in the previous example, it is necessary to specify the s option explicitly, since the t option by itself
implies that ONLY the footer line is to be printed:
setenv ZIPINFO t
zipinfo t storage
zipinfo st storage

[only totals line]


[full listing]

The s option, like m and l, includes headers and footers by default, unless otherwise specified. Since
the environment variable specified no footers and that has a higher precedence than the default behavior of
s, an explicit t option was necessary to produce the full listing. Nothing was indicated about the header,
however, so the s option was sufficient. Note that both the h and t options, when used by themselves or
with each other, override any default listing of member files; only the header and/or footer are printed. This
behavior is useful when zipinfo is used with a wildcard zipfile specification; the contents of all zipfiles are
then summarized with a single command.

Info-ZIP

Last change: 14 January 2001 (v2.32)

Misc. Reference Manual Pages

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZIPINFO ( 1L )

To list information on a single file within the archive, in medium format, specify the filename explicitly:
zipinfo m storage unshrink.c
The specification of any member file, as in this example, will override the default header and totals lines;
only the single line of information about the requested file will be printed. This is intuitively what one
would expect when requesting information about a single file. For multiple files, it is often useful to know
the total compressed and uncompressed size; in such cases t may be specified explicitly:
zipinfo mt storage ".[ch]" Mak\
To get maximal information about the ZIP archive, use the verbose option. It is usually wise to pipe the
output into a filter such as Unix more(1) if the operating system allows it:
zipinfo v storage | more
Finally, to see the most recently modified files in the archive, use the T option in conjunction with an
external sorting utility such as Unix sort(1) (and tail(1) as well, in this example):
zipinfo T storage | sort -n +6 | tail -15
The n option to sort(1) tells it to sort numerically rather than in ASCII order, and the +6 option tells it to
sort on the sixth field after the first one (i.e., the seventh field). This assumes the default short-listing format; if m or l is used, the proper sort(1) option would be +7. The tail(1) command filters out all but the
last 15 lines of the listing. Future releases of zipinfo may incorporate date/time and filename sorting as
built-in options.
TIPS

The author finds it convenient to define an alias ii for zipinfo on systems that allow aliases (or, on other systems, copy/rename the executable, create a link or create a command file with the name ii). The ii usage
parallels the common ll alias for long listings in Unix, and the similarity between the outputs of the two
commands was intentional.
BUGS

As with unzip, zipinfos M (more) option is overly simplistic in its handling of screen output; as noted
above, it fails to detect the wrapping of long lines and may thereby cause lines at the top of the screen to be
scrolled off before being read. zipinfo should detect and treat each occurrence of line-wrap as one additional line printed. This requires knowledge of the screens width as well as its height. In addition, zipinfo
should detect the true screen geometry on all systems.
zipinfos listing-format behavior is unnecessarily complex and should be simplified. (This is not to say that
it will be.)
SEE ALSO

ls(1), funzip(1L), unzip(1L), unzipsfx(1L), zip(1L), zipcloak(1L), zipnote(1L), zipsplit(1L)


URL

The Info-ZIP home page is currently at http://www.info-zip.org/pub/infozip/ or


ftp://ftp.info-zip.org/pub/infozip/ .
AUTHOR

Greg Cave Newt Roelofs. ZipInfo contains pattern-matching code by Mark Adler and
fixes/improvements by many others. Please refer to the CONTRIBS file in the UnZip source distribution
for a more complete list.

Info-ZIP

Last change: 14 January 2001 (v2.32)

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHALL ( 1 )

NAME

zshall the Z shell metaman page


SYNOPSIS

Because zsh contains many features, the zsh manual has been split into a number of sections. This manual
page includes all the separate manual pages in the following order:
zshmisc Anything not fitting into the other sections
zshexpn Zsh command and parameter expansion
zshparam Zsh parameters
zshoptions Zsh options
zshbuiltins Zsh builtin functions
zshzle
Zsh command line editing
zshcompwid Zsh completion widgets
zshcompsys Zsh completion system
zshcompctl Zsh completion control
zshmodules Zsh loadable modules
zshzftpsys Zsh builtin FTP client
DESCRIPTION

Zsh is a UNIX command interpreter (shell) usable as an interactive login shell and as a shell script command processor. Of the standard shells, zsh most closely resembles ksh but includes many enhancements.
Zsh has command line editing, builtin spelling correction, programmable command completion, shell functions (with autoloading), a history mechanism, and a host of other features.
AUTHOR

Zsh was originally written by Paul Falstad <pf@zsh.org>. Zsh is now maintained by the members of the
zshworkers mailing list <zshworkers@sunsite.dk>. The development is currently coordinated by Peter
Stephenson <pws@zsh.org>. The coordinator can be contacted at <coordinator@zsh.org>, but matters
relating to the code should generally go to the mailing list.

AVAILABILITY

Zsh is available from the following anonymous FTP sites. These mirror sites are kept frequently up to date.
The sites marked with (H) may be mirroring ftp.cs.elte.hu instead of the primary site.
Primary site
ftp://ftp.zsh.org/pub/zsh/
http://www.zsh.org/pub/zsh/
Australia
ftp://ftp.zsh.org/pub/zsh/
http://www.zsh.org/pub/zsh/
ftp://ftp.ips.gov.au/pub/packages/zsh/ (H)
Denmark
ftp://sunsite.dk/pub/unix/shells/zsh/
Finland
ftp://ftp.funet.fi/pub/unix/shells/zsh/
France
ftp://ftp.cenatls.cena.dgac.fr/shells/zsh/
Germany
ftp://ftp.fuberlin.de/pub/unix/shells/zsh/ (H)
ftp://ftp.gmd.de/packages/zsh/
ftp://ftp.unitrier.de/pub/unix/shell/zsh/
Hungary
ftp://ftp.cs.elte.hu/pub/zsh/
http://www.cs.elte.hu/pub/zsh/

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHALL ( 1 )

ftp://ftp.kfki.hu/pub/packages/zsh/
Israel
ftp://ftp.math.technion.ac.il/pub/zsh/
http://www.math.technion.ac.il/pub/zsh/
Italy
ftp://ftp.unina.it/pub/Unix/pkgs/shell/zsh/
Japan
ftp://ftp.nisiq.net/pub/shells/zsh/ (H)
ftp://ftp.win.ne.jp/pub/shell/zsh/
Norway
ftp://ftp.uit.no/pub/unix/shells/zsh/
Poland
ftp://sunsite.icm.edu.pl/pub/unix/shells/zsh/
Romania
ftp://ftp.roedu.net/pub/mirrors/ftp.zsh.org/pub/zsh/
ftp://ftp.kappa.ro/pub/mirrors/ftp.zsh.org/pub/zsh/
Slovenia
ftp://ftp.siol.net/mirrors/zsh/
Sweden
ftp://ftp.lysator.liu.se/pub/unix/zsh/
UK
ftp://ftp.net.lut.ac.uk/zsh/
ftp://sunsite.org.uk/packages/zsh/
USA
ftp://uiarchive.uiuc.edu/pub/packages/shells/zsh/
ftp://ftp.rge.com/pub/shells/zsh/
ftp://foad.org/pub/zsh/
http://foad.org/zsh/
MAILING LISTS

Zsh has 3 mailing lists:


<zshannounce@sunsite.dk>
Announcements about releases, major changes in the shell and the monthly posting of the Zsh
FAQ. (moderated)
<zshusers@sunsite.dk>
User discussions.
<zshworkers@sunsite.dk>
Hacking, development, bug reports and patches.
To subscribe or unsubscribe, send mail to the associated administrative address for the mailing list.
<zshannouncesubscribe@sunsite.dk>
<zshuserssubscribe@sunsite.dk>
<zshworkerssubscribe@sunsite.dk>
<zshannounceunsubscribe@sunsite.dk>
<zshusersunsubscribe@sunsite.dk>
<zshworkersunsubscribe@sunsite.dk>
YOU ONLY NEED TO JOIN ONE OF THE MAILING LISTS AS THEY ARE NESTED. All submissions to zshannounce are automatically forwarded to zshusers. All submissions to zshusers are
automatically forwarded to zshworkers.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHALL ( 1 )

If you have problems subscribing/unsubscribing to any of the mailing lists, send mail to
<listmaster@zsh.org>. The mailing lists are maintained by Karsten Thygesen <karthy@kom.auc.dk>.
The mailing lists are archived; the archives can be accessed via the administrative addresses listed above.
There is also a hypertext archive, maintained by Geoff Wing <gcw@zsh.org>, available at
http://www.zsh.org/mla/.
THE ZSH FAQ

Zsh has a list of Frequently Asked Questions (FAQ), maintained by Peter Stephenson <pws@zsh.org>. It
is regularly posted to the newsgroup comp.unix.shell and the zshannounce mailing list. The latest version can be found at any of the Zsh FTP sites, or at http://www.zsh.org/FAQ/. The contact address for
FAQrelated matters is <faqmaster@zsh.org>.

THE ZSH WEB PAGE

Zsh has a web page which is located at http://www.zsh.org/. This is maintained by Karsten Thygesen
<karthy@zsh.org>, of SunSITE Denmark. The contact address for webrelated matters is
<webmaster@zsh.org>.
THE ZSH USERGUIDE

A userguide is currently in preparation. It is intended to complement the manual, with explanations and
hints on issues where the manual can be cabbalistic, hierographic, or downright mystifying (for example,
the word hierographic does not exist). It can be viewed in its current state at
http://zsh.sunsite.dk/Guide/. At the time of writing, chapters dealing with startup files and their contents
and the new completion system were essentially complete.
INVOCATION OPTIONS

The following flags are interpreted by the shell when invoked to determine where the shell will read commands from:
c

Take the first argument as a command to execute, rather than reading commands from a script or
standard input. If any further arguments are given, the first one is assigned to $0, rather than being
used as a positional parameter.

Force shell to be interactive.

Force shell to read commands from the standard input. If the s flag is not present and an argument is given, the first argument is taken to be the pathname of a script to execute.

After the first one or two arguments have been appropriated as described above, the remaining arguments
are assigned to the positional parameters.
For further options, which are common to invocation and the set builtin, see zshoptions(1).
Options may be specified by name using the o option. o acts like a singleletter option, but takes a following string as the option name. For example,
zsh x o shwordsplit scr
runs the script scr, setting the XTRACE option by the corresponding letter x and the
SH_WORD_SPLIT option by name. Options may be turned off by name by using +o instead of o. o
can be stacked up with preceding singleletter options, so for example xo shwordsplit or
xoshwordsplit is equivalent to x o shwordsplit.
Options may also be specified by name in GNU long option style, optionname. When this is done,
characters in the option name are permitted: they are translated into _, and thus ignored. So, for example,
zsh shwordsplit invokes zsh with the SH_WORD_SPLIT option turned on. Like other option syntaxes, options can be turned off by replacing the initial with a +; thus +shwordsplit is equivalent
to noshwordsplit. Unlike other option syntaxes, GNUstyle long options cannot be stacked with
any other options, so for example xshwordsplit is an error, rather than being treated like x
shwordsplit.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHALL ( 1 )

The special GNUstyle option version is handled; it sends to standard output the shells version information, then exits successfully. help is also handled; it sends to standard output a list of options that
can be used when invoking the shell, then exits successfully.
Option processing may be finished, allowing following arguments that start with or + to be treated as
normal arguments, in two ways. Firstly, a lone (or +) as an argument by itself ends option processing.
Secondly, a special option (or +), which may be specified on its own (which is the standard POSIX
usage) or may be stacked with preceding options (so x is equivalent to x ). Options are not permitted to be stacked after (so xf is an error), but note the GNUstyle option form discussed above,
where shwordsplit is permitted and does not end option processing.
Except when the sh/ksh emulation singleletter options are in effect, the option b (or +b) ends option
processing. b is like , except that further singleletter options can be stacked after the b and will
take effect as normal.
COMPATIBILITY

Zsh tries to emulate sh or ksh when it is invoked as sh or ksh respectively; more precisely, it looks at the
first letter of the name by which it was invoked, excluding any initial r (assumed to stand for restricted),
and if that is s or k it will emulate sh or ksh. Furthermore, if invoked as su (which happens on certain
systems when the shell is executed by the su command), the shell will try to find an alternative name from
the SHELL environment variable and perform emulation based on that.
In sh and ksh compatibility modes the following parameters are not special and not initialized by the shell:
ARGC, argv, cdpath, fignore, fpath, HISTCHARS, mailpath, MANPATH, manpath, path, prompt,
PROMPT, PROMPT2, PROMPT3, PROMPT4, psvar, status, watch.
The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by
$HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile
scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic
expansion before being interpreted as a pathname. Note that the PRIVILEGED option also affects the
execution of startup files.
The following options are set if the shell is invoked as sh or ksh: NO_BAD_PATTERN,
NO_BANG_HIST, NO_BG_NICE, NO_EQUALS, NO_FUNCTION_ARGZERO, GLOB_SUBST,
NO_GLOBAL_EXPORT,
NO_HUP,
INTERACTIVE_COMMENTS,
KSH_ARRAYS,
NO_MULTIOS, NO_NOMATCH, NO_NOTIFY, POSIX_BUILTINS, NO_PROMPT_PERCENT,
RM_STAR_SILENT,
SH_FILE_EXPANSION,
SH_GLOB,
SH_OPTION_LETTERS,
SH_WORD_SPLIT. Additionally the BSD_ECHO and IGNORE_BRACES options are set if zsh is
invoked as sh. Also, the KSH_OPTION_PRINT, LOCAL_OPTIONS, PROMPT_BANG,
PROMPT_SUBST and SINGLE_LINE_ZLE options are set if zsh is invoked as ksh.
RESTRICTED SHELL

When the basename of the command used to invoke zsh starts with the letter r or the r command line
option is supplied at invocation, the shell becomes restricted. Emulation mode is determined after stripping
the letter r from the invocation name. The following are disabled in restricted mode:

zsh 4.0.4

changing directories with the cd builtin

changing or unsetting the PATH, path, MODULE_PATH, module_path, SHELL, HISTFILE,


HISTSIZE, GID, EGID, UID, EUID, USERNAME, LD_LIBRARY_PATH,
LD_AOUT_LIBRARY_PATH, LD_PRELOAD and LD_AOUT_PRELOAD parameters

specifying command names containing /

specifying command pathnames using hash

redirecting output to files

using the exec builtin command to replace the shell with another command

using jobs Z to overwrite the shell process argument and environment space

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

using the ARGV0 parameter to override argv[0] for external commands

turning off restricted mode with set +r or unsetopt RESTRICTED

ZSHALL ( 1 )

These restrictions are enforced after processing the startup files. The startup files should set up PATH to
point to a directory of commands which can be safely invoked in the restricted environment. They may
also add further restrictions by disabling selected builtins.
Restricted mode can also be activated any time by setting the RESTRICTED option. This immediately
enables all the restrictions described above even if the shell still has not processed all startup files.
STARTUP/SHUTDOWN FILES

Commands are first read from /etc/zshenv; this cannot be overridden. Subsequent behaviour is modified by
the RCS and GLOBAL_RCS options; the former affects all startup files, while the second only affects
those in the /etc directory. If one of the options is unset at any point, any subsequent startup file(s) of the
corresponding type will not be read. It is also possible for a file in $ZDOTDIR to reenable
GLOBAL_RCS. Both RCS and GLOBAL_RCS are set by default.
Commands are then read from $ZDOTDIR/.zshenv. If the shell is a login shell, commands are read from
/etc/zprofile and then $ZDOTDIR/.zprofile. Then, if the shell is interactive, commands are read from
/etc/zshrc and then $ZDOTDIR/.zshrc. Finally, if the shell is a login shell, /etc/zlogin and
$ZDOTDIR/.zlogin are read.
When a login shell exits, the files $ZDOTDIR/.zlogout and then /etc/zlogout are read. This happens with
either an explicit exit via the exit or logout commands, or an implicit exit by reading endoffile from the
terminal. However, if the shell terminates due to execing another process, the logout files are not read.
These are also affected by the RCS and GLOBAL_RCS options. Note also that the RCS option affects the
saving of history files, i.e. if RCS is unset when the shell exits, no history file will be saved.
If ZDOTDIR is unset, HOME is used instead. Those files listed above as being in /etc may be in another
directory, depending on the installation.
As /etc/zshenv is run for all instances of zsh, it is important that it be kept as small as possible. In particular, it is a good idea to put code that does not need to be run for every single shell behind a test of the form
if [[ o rcs ]]; then ... so that it will not be executed when zsh is invoked with the f option.
Any of these files may be precompiled with the zcompile builtin command (see zshbuiltins(1)). If a compiled file exists (named for the original file plus the .zwc extension) and it is newer than the original file, the
compiled file will be used instead.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

NAME

zshmisc everything and then some


SIMPLE COMMANDS & PIPELINES

A simple command is a sequence of optional parameter assignments followed by blankseparated words,


with optional redirections interspersed. The first word is the command to be executed, and the remaining
words, if any, are arguments to the command. If a command name is given, the parameter assignments
modify the environment of the command when it is executed. The value of a simple command is its exit
status, or 128 plus the signal number if terminated by a signal. For example,
echo foo
is a simple command with arguments.
A pipeline is either a simple command, or a sequence of two or more simple commands where each command is separated from the next by or &. Where commands are separated by , the standard output
of the first command is connected to the standard input of the next. & is shorthand for 2>&1 , which
connects both the standard output and the standard error of the command to the standard input of the next.
The value of a pipeline is the value of the last command, unless the pipeline is preceded by ! in which
case the value is the logical inverse of the value of the last command. For example,
echo foo sed s/foo/bar/
is a pipeline, where the output (foo plus a newline) of the first command will be passed to the input of the
second.
If a pipeline is preceded by coproc, it is executed as a coprocess; a twoway pipe is established between it
and the parent shell. The shell can read from or write to the coprocess by means of the >&p and <&p
redirection operators or with print p and read p. A pipeline cannot be preceded by both coproc
and !. If job control is active, the coprocess can be treated in other than input and output as an ordinary
background job.
A sublist is either a single pipeline, or a sequence of two or more pipelines separated by && or . If
two pipelines are separated by &&, the second pipeline is executed only if the first succeeds (returns a
zero value). If two pipelines are separated by , the second is executed only if the first fails (returns a
nonzero value). Both operators have equal precedence and are left associative. The value of the sublist is
the value of the last pipeline executed. For example,
dmesg grep panic && print yes
is a sublist consisting of two pipelines, the second just a simple command which will be executed if and
only if the grep command returns a zero value. If it does not, the value of the sublist is that return value,
else it is the value returned by the print (almost certainly zero).
A list is a sequence of zero or more sublists, in which each sublist is terminated by ;, &, &, &!, or a
newline. This terminator may optionally be omitted from the last sublist in the list when the list appears as
a complex command inside (...) or {...}. When a sublist is terminated by ; or newline, the shell waits
for it to finish before executing the next sublist. If a sublist is terminated by a &, &, or &!, the shell
executes the last pipeline in it in the background, and does not wait for it to finish (note the difference from
other shells which execute the whole sublist in the background). A backgrounded pipeline returns a status
of zero.
More generally, a list can be seen as a set of any shell commands whatsoever, including the complex commands below; this is implied wherever the word list appears in later descriptions. For example, the commands in a shell function form a special sort of list.
PRECOMMAND MODIFIERS

A simple command may be preceded by a precommand modifier, which will alter how the command is
interpreted. These modifiers are shell builtin commands with the exception of nocorrect which is a
reserved word.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

The command is executed with a prepended to its argv[0] string.

noglob Filename generation (globbing) is not performed on any of the words.


nocorrect
Spelling correction is not done on any of the words. This must appear before any other precommand modifier, as it is interpreted immediately, before any parsing is done. It has no effect in
noninteractive shells.
exec

The command is executed in the parent shell without forking.

command
The command word is taken to be the name of an external command, rather than a shell function
or builtin.
builtin The command word is taken to be the name of a builtin command, rather than a shell function or
external command.
COMPLEX COMMANDS

A complex command in zsh is one of the following:


if list then list [ elif list then list ] ... [ else list ] fi
The if list is executed, and if it returns a zero exit status, the then list is executed. Otherwise, the
elif list is executed and if its value is zero, the then list is executed. If each elif list returns
nonzero, the else list is executed.
for name [ in word ... term ] do list done
where term is at least one newline or ;. Expand the list of words, and set the parameter name to
each of them in turn, executing list each time. If the in word is omitted, use the positional parameters instead of the words.
for (( [expr1] ; [expr2] ; [expr3] )) do list done
The arithmetic expression expr1 is evaluated first (see the section Arithmetic Evaluation). The
arithmetic expression expr2 is repeatedly evaluated until it evaluates to zero and when nonzero,
list is executed and the arithmetic expression expr3 evaluated. If any expression is omitted, then it
behaves as if it evaluated to 1.
while list do list done
Execute the do list as long as the while list returns a zero exit status.
until list do list done
Execute the do list as long as until list returns a nonzero exit status.
repeat word do list done
word is expanded and treated as an arithmetic expression, which must evaluate to a number n. list
is then executed n times.
case word in [ [(] pattern [ pattern ] ... ) list (;;;&) ] ... esac
Execute the list associated with the first pattern that matches word, if any. The form of the patterns is the same as that used for filename generation. See the section Filename Generation. If
the list that is executed is terminated with ;& rather than ;;, the following list is also executed.
This continues until either a list is terminated with ;; or the esac is reached.
select name [ in word ... term ] do list done
where term is one or more newline or ; to terminate the words. Print the set of words, each preceded by a number. If the in word is omitted, use the positional parameters. The PROMPT3
prompt is printed and a line is read from the line editor if the shell is interactive and that is active,
or else standard input. If this line consists of the number of one of the listed words, then the
parameter name is set to the word corresponding to this number. If this line is empty, the selection
list is printed again. Otherwise, the value of the parameter name is set to null. The contents of the
line read from standard input is saved in the parameter REPLY. list is executed for each selection
until a break or endoffile is encountered.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

( list )

Execute list in a subshell. Traps set by the trap builtin are reset to their default values while executing list.

{ list }

Execute list.

function word ... [ () ] [ term ] { list }


word ... () [ term ] { list }
word ... () [ term ] command
where term is one or more newline or ;. Define a function which is referenced by any one of word.
Normally, only one word is provided; multiple words are usually only useful for setting traps. The
body of the function is the list between the { and }. See the section Functions.
If the option SH_GLOB is set for compatibility with other shells, then whitespace may appear
between between the left and right parentheses when there is a single word; otherwise, the
parentheses will be treated as forming a globbing pattern in that case.
time [ pipeline ]
The pipeline is executed, and timing statistics are reported on the standard error in the form
specified by the TIMEFMT parameter. If pipeline is omitted, print statistics about the shell process and its children.
[[ exp ]] Evaluates the conditional expression exp and return a zero exit status if it is true. See the section
Conditional Expressions for a description of exp.
ALTERNATE FORMS FOR COMPLEX COMMANDS

Many of zshs complex commands have alternate forms. These particular versions of complex commands
should be considered deprecated and may be removed in the future. The versions in the previous section
should be preferred instead.
The short versions below only work if sublist is of the form { list } or if the SHORT_LOOPS option is
set. For the if, while and until commands, in both these cases the test part of the loop must also be suitably
delimited, such as by [[ ... ]] or (( ... )), else the end of the test will not be recognized. For the for,
repeat, case and select commands no such special form for the arguments is necessary, but the other condition (the special form of sublist or use of the SHORT_LOOPS option) still applies.
if list { list } [ elif list { list } ] ... [ else { list } ]
An alternate form of if. The rules mean that
if [[ o ignorebraces ]] {
print yes
}
works, but
if true { # Does not work!
print yes
}
does not, since the test is not suitably delimited.
if list sublist
A short form of the alternate if. The same limitations on the form of list apply as for the previous form.
for name ( word ... ) sublist
A short form of for.
for name [ in word ... term ] sublist
where term is at least one newline or ;. Another short form of for.
for (( [expr1] ; [expr2] ; [expr3] )) sublist
A short form of the arithmetic for command.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

foreach name ( word ... ) list end


Another form of for.
while list { list }
An alternative form of while. Note the limitations on the form of list mentioned above.
until list { list }
An alternative form of until. Note the limitations on the form of list mentioned above.
repeat word sublist
This is a short form of repeat.
case word { [ [(] pattern [ pattern ] ... ) list (;;;&) ] ... }
An alternative form of case.
select name [ in word term ] sublist
where term is at least one newline or ;. A short form of select.
RESERVED WORDS

The following words are recognized as reserved words when used as the first word of a command unless
quoted or disabled using disable r:
do done esac then elif else fi for case if while function repeat time until select coproc nocorrect
foreach end ! [[ { }
Additionally, } is recognized in any position if the IGNORE_BRACES option is not set.
COMMENTS

In noninteractive shells, or in interactive shells with the INTERACTIVE_COMMENTS option set, a


word beginning with the third character of the histchars parameter (# by default) causes that word and all
the following characters up to a newline to be ignored.
ALIASING

Every token in the shell input is checked to see if there is an alias defined for it. If so, it is replaced by the
text of the alias if it is in command position (if it could be the first word of a simple command), or if the
alias is global. If the text ends with a space, the next word in the shell input is treated as though it were in
command position for purposes of alias expansion. An alias is defined using the alias builtin; global aliases
may be defined using the g option to that builtin.
Alias expansion is done on the shell input before any other expansion except history expansion. Therefore,
if an alias is defined for the word foo, alias expansion may be avoided by quoting part of the word, e.g.
\foo. But there is nothing to prevent an alias being defined for \foo as well.
QUOTING

A character may be quoted (that is, made to stand for itself) by preceding it with a \. \ followed by a
newline is ignored.
A string enclosed between $ and is processed the same way as the string arguments of the print builtin, and the resulting string is considered to be entirely quoted. A literal character can be included in the
string by using the \ escape.
All characters enclosed between a pair of single quotes () that is not preceded by a $ are quoted. A single quote cannot appear within single quotes unless the option RC_QUOTES is set, in which case a pair of
single quotes are turned into a single quote. For example,
print
outputs nothing apart from a newline if RC_QUOTES is not set, but one single quote if it is set.
Inside double quotes (" " ), parameter and command substitution occur, and \ quotes the characters \, ,
" , and $.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHMISC ( 1 )

REDIRECTION

If a command is followed by & and job control is not active, then the default standard input for the command is the empty file /dev/null. Otherwise, the environment for the execution of a command contains the
file descriptors of the invoking shell as modified by input/output specifications.
The following may appear anywhere in a simple command or may precede or follow a complex command.
Expansion occurs before word or digit is used except as noted below. If the result of substitution on word
produces more than one filename, redirection occurs for each separate filename in turn.
< word Open file word for reading as standard input.
<> word
Open file word for reading and writing as standard input. If the file does not exist then it is
created.
> word Open file word for writing as standard output. If the file does not exist then it is created. If the file
exists, and the CLOBBER option is unset, this causes an error; otherwise, it is truncated to zero
length.
> word
>! word Same as >, except that the file is truncated to zero length if it exists, even if CLOBBER is unset.
>> word
Open file word for writing in append mode as standard output. If the file does not exist, and the
CLOBBER option is unset, this causes an error; otherwise, the file is created.
>> word
>>! word
Same as >>, except that the file is created if it does not exist, even if CLOBBER is unset.
<<[] word
The shell input is read up to a line that is the same as word, or to an endoffile. No parameter
expansion, command substitution or filename generation is performed on word. The resulting
document, called a heredocument, becomes the standard input.
If any character of word is quoted with single or double quotes or a \, no interpretation is placed
upon the characters of the document. Otherwise, parameter and command substitution occurs, \
followed by a newline is removed, and \ must be used to quote the characters \, $, and the
first character of word.
If << is used, then all leading tabs are stripped from word and from the document.
<< < word
Perform shell expansion on word and pass the result to standard input. This is known as a
herestring.
<& number
>& number
The standard input/output is duplicated from file descriptor number (see dup2(2)).
<&
>&

Close the standard input/output.

<& p
>& p

The input/output from/to the coprocess is moved to the standard input/output.

>& word
&> word
(Except where >& word matches one of the above syntaxes; &> can always be used to avoid
this ambiguity.) Redirects both standard output and standard error (file descriptor 2) in the manner
of > word. Note that this does not have the same effect as > word 2>&1 in the presence of
multios (see the section below).

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

>& word
>&! word
&> word
&>! word
Redirects both standard output and standard error (file descriptor 2) in the manner of > word.
>>& word
&>> word
Redirects both standard output and standard error (file descriptor 2) in the manner of >> word.
>>& word
>>&! word
&>> word
&>>! word
Redirects both standard output and standard error (file descriptor 2) in the manner of >> word.
If one of the above is preceded by a digit, then the file descriptor referred to is that specified by the digit
instead of the default 0 or 1. The order in which redirections are specified is significant. The shell evaluates each redirection in terms of the (file descriptor, file) association at the time of evaluation. For example:
... 1>fname 2>&1
first associates file descriptor 1 with file fname. It then associates file descriptor 2 with the file associated
with file descriptor 1 (that is, fname). If the order of redirections were reversed, file descriptor 2 would be
associated with the terminal (assuming file descriptor 1 had been) and then file descriptor 1 would be associated with file fname.
MULTIOS

If the user tries to open a file descriptor for writing more than once, the shell opens the file descriptor as a
pipe to a process that copies its input to all the specified outputs, similar to tee, provided the MULTIOS
option is set, as it is by default. Thus:
date >foo >bar
writes the date to two files, named foo and bar. Note that a pipe is an implicit redirection; thus
date >foo cat
writes the date to the file foo, and also pipes it to cat.
If the MULTIOS option is set, the word after a redirection operator is also subjected to filename generation
(globbing). Thus
:>
will truncate all files in the current directory, assuming theres at least one. (Without the MULTIOS
option, it would create an empty file called .) Similarly, you can do
echo exit 0 >> .sh
If the user tries to open a file descriptor for reading more than once, the shell opens the file descriptor as a
pipe to a process that copies all the specified inputs to its output in the order specified, similar to cat, provided the MULTIOS option is set. Thus
sort <foo <fubar
or even
sort <f{oo,ubar}
is equivalent to cat foo fubar sort.
Note that a pipe is an implicit redirection; thus

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

cat bar sort <foo


is equivalent to cat bar foo sort (note the order of the inputs).
If the MULTIOS option is unset, each redirection replaces the previous redirection for that file descriptor.
However, all files redirected to are actually opened, so
echo foo > bar > baz
when MULTIOS is unset will truncate bar, and write foo into baz.
REDIRECTIONS WITH NO COMMAND

When a simple command consists of one or more redirection operators and zero or more parameter assignments, but no command name, zsh can behave in several ways.
If the parameter NULLCMD is not set or the option CSH_NULLCMD is set, an error is caused. This is
the csh behavior and CSH_NULLCMD is set by default when emulating csh.
If the option SH_NULLCMD is set, the builtin : is inserted as a command with the given redirections.
This is the default when emulating sh or ksh.
Otherwise, if the parameter NULLCMD is set, its value will be used as a command with the given redirections. If both NULLCMD and READNULLCMD are set, then the value of the latter will be used instead
of that of the former when the redirection is an input. The default for NULLCMD is cat and for READNULLCMD is more. Thus
< file
shows the contents of file on standard output, with paging if that is a terminal. NULLCMD and READNULLCMD may refer to shell functions.
COMMAND EXECUTION

If a command name contains no slashes, the shell attempts to locate it. If there exists a shell function by
that name, the function is invoked as described in the section Functions. If there exists a shell builtin by
that name, the builtin is invoked.
Otherwise, the shell searches each element of $path for a directory containing an executable file by that
name. If the search is unsuccessful, the shell prints an error message and returns a nonzero exit status.
If execution fails because the file is not in executable format, and the file is not a directory, it is assumed to
be a shell script. /bin/sh is spawned to execute it. If the program is a file beginning with #!, the
remainder of the first line specifies an interpreter for the program. The shell will execute the specified interpreter on operating systems that do not handle this executable format in the kernel.
FUNCTIONS

Shell functions are defined with the function reserved word or the special syntax funcname (). Shell functions are read in and stored internally. Alias names are resolved when the function is read. Functions are
executed like commands with the arguments passed as positional parameters. (See the section Command
Execution.)
Functions execute in the same process as the caller and share all files and present working directory with
the caller. A trap on EXIT set inside a function is executed after the function completes in the environment
of the caller.
The return builtin is used to return from function calls.
Function identifiers can be listed with the functions builtin. Functions can be undefined with the unfunction builtin.
AUTOLOADING FUNCTIONS

A function can be marked as undefined using the autoload builtin (or functions u or typeset fu).
Such a function has no body. When the function is first executed, the shell searches for its definition using
the elements of the fpath variable. Thus to define functions for autoloading, a typical sequence is:

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHMISC ( 1 )

fpath=(/myfuncs $fpath)
autoload myfunc1 myfunc2 ...
The usual alias expansion during reading will be suppressed if the autoload builtin or its equivalent is
given the option U. This is recommended for the use of functions supplied with the zsh distribution. Note
that for functions precompiled with the zcompile builtin command the flag U must be provided when the
.zwc file is created, as the corresponding information is compiled into the latter.
For each element in fpath, the shell looks for three possible files, the newest of which is used to load the
definition for the function:
element.zwc
A file created with the zcompile builtin command, which is expected to contain the definitions for
all functions in the directory named element. The file is treated in the same manner as a directory
containing files for functions and is searched for the definition of the function. If the definition is
not found, the search for a definition proceeds with the other two possibilities described below.
If element already includes a .zwc extension (i.e. the extension was explicitly given by the user),
element is searched for the definition of the function without comparing its age to that of other
files; in fact, there does not need to be any directory named element without the suffix. Thus
including an element such as /usr/local/funcs.zwc in fpath will speed up the search for functions, with the disadvantage that functions included must be explicitly recompiled by hand before
the shell notices any changes.
element/function.zwc
A file created with zcompile, which is expected to contain the definition for function. It may
include other function definitions as well, but those are neither loaded nor executed; a file found in
this way is searched only for the definition of function.
element/function
A file of zsh command text, taken to be the definition for function.
In summary, the order of searching is, first, in the parents of directories in fpath for the newer of either a
compiled directory or a directory in fpath; second, if more than one of these contains a definition for the
function that is sought, the leftmost in the fpath is chosen; and third, within a directory, the newer of either
a compiled function or an ordinary function definition is used.
If the KSH_AUTOLOAD option is set, or the file contains only a simple definition of the function, the
files contents will be executed. This will normally define the function in question, but may also perform
initialization, which is executed in the context of the function execution, and may therefore define local
parameters. It is an error if the function is not defined by loading the file.
Otherwise, the function body (with no surrounding funcname() {...}) is taken to be the complete contents
of the file. This form allows the file to be used directly as an executable shell script. If processing of the
file results in the function being redefined, the function itself is not reexecuted. To force the shell to perform initialization and then call the function defined, the file should contain initialization code (which will
be executed then discarded) in addition to a complete function definition (which will be retained for subsequent calls to the function), and a call to the shell function, including any arguments, at the end.
For example, suppose the autoload file func contains
func() { print This is func; }
print func is initialized
then func; func with KSH_AUTOLOAD set will produce both messages on the first call, but only the
message This is func on the second and subsequent calls. Without KSH_AUTOLOAD set, it will produce the initialization message on the first call, and the other message on the second and subsequent calls.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

It is also possible to create a function that is not marked as autoloaded, but which loads its own definition
by searching fpath, by using autoload X within a shell function. For example, the following are
equivalent:
myfunc() {
autoload X
}
myfunc args...
and
unfunction myfunc # if myfunc was defined
autoload myfunc
myfunc args...
In fact, the functions command outputs builtin autoload X as the body of an autoloaded function. A
true autoloaded function can be identified by the presence of the comment # undefined in the body,
because all comments are discarded from defined functions. This is done so that
eval " $(functions)"
produces a reasonable result.
To load the definition of an autoloaded function myfunc without executing myfunc, use:
autoload +X myfunc
SPECIAL FUNCTIONS

The following functions, if defined, have special meaning to the shell:


chpwd Executed whenever the current working directory is changed.
periodic
If the parameter PERIOD is set, this function is executed every $PERIOD seconds, just before a
prompt.
precmd Executed before each prompt.
preexec Executed just after a command has been read and is about to be executed. If the history mechanism is active (and the line was not discarded from the history buffer), the string that the user typed
is passed as the first argument, otherwise it is an empty string. The actual command that will be
executed (including expanded aliases) is passed in two different forms: the second argument is a
singleline, sizelimited version of the command (with things like function bodies elided); the
third argument contains the full text what what is being executed.
TRAPNAL
If defined and nonnull, this function will be executed whenever the shell catches a signal SIGNAL, where NAL is a signal name as specified for the kill builtin. The signal number will be
passed as the first parameter to the function.
If a function of this form is defined and null, the shell and processes spawned by it will ignore
SIGNAL.
TRAPDEBUG
Executed after each command.
TRAPEXIT
Executed when the shell exits, or when the current function exits if defined inside a function.
TRAPZERR
Executed whenever a command has a nonzero exit status. However, the function is not executed
if the command occurred in a sublist followed by && or ; only the final command in a sublist
of this type causes the trap to be executed.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

The functions beginning TRAP may alternatively be defined with the trap builtin: this may be preferable
for some uses, as they are then run in the environment of the calling process, rather than in their own function environment. Apart from the difference in calling procedure and the fact that the function form appears
in lists of functions, the forms
TRAPNAL() {
# code
}
and
trap
# code
are equivalent.
JOBS

If the MONITOR option is set, an interactive shell associates a job with each pipeline. It keeps a table of
current jobs, printed by the jobs command, and assigns them small integer numbers. When a job is started
asynchronously with &, the shell prints a line which looks like:
[1] 1234
indicating that the job which was started asynchronously was job number 1 and had one (toplevel) process, whose process ID was 1234.
If a job is started with & or &!, then that job is immediately disowned. After startup, it does not have a
place in the job table, and is not subject to the job control features described here.
If you are running a job and wish to do something else you may hit the key Z (controlZ) which sends a
TSTP signal to the current job: this key may be redefined by the susp option of the external stty command. The shell will then normally indicate that the job has been suspended, and print another prompt.
You can then manipulate the state of this job, putting it in the background with the bg command, or run
some other commands and then eventually bring the job back into the foreground with the foreground command fg. A Z takes effect immediately and is like an interrupt in that pending output and unread input are
discarded when it is typed.
A job being run in the background will suspend if it tries to read from the terminal. Background jobs are
normally allowed to produce output, but this can be disabled by giving the command stty tostop. If you
set this tty option, then background jobs will suspend when they try to produce output like they do when
they try to read input.
When a command is suspended and continued later with the fg or wait builtins, zsh restores tty modes that
were in effect when it was suspended. This (intentionally) does not apply if the command is continued via
kill CONT, nor when it is continued with bg.
There are several ways to refer to jobs in the shell. A job can be referred to by the process ID of any process of the job or by one of the following:
%number
The job with the given number.
%string
Any job whose command line begins with string.
%?string
Any job whose command line contains string.
%%
Current job.
%+
Equivalent to %%.
%
Previous job.
The shell learns immediately whenever a process changes state. It normally informs you whenever a job
becomes blocked so that no further progress is possible. If the NOTIFY option is not set, it waits until just
before it prints a prompt before it informs you.

zsh 4.0.4

Last change: October 26, 2001

10

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

When the monitor mode is on, each background job that completes triggers any trap set for CHLD.
When you try to leave the shell while jobs are running or suspended, you will be warned that You have
suspended (running) jobs. You may use the jobs command to see what they are. If you do this or immediately try to exit again, the shell will not warn you a second time; the suspended jobs will be terminated, and
the running jobs will be sent a SIGHUP signal, if the HUP option is set.
To avoid having the shell terminate the running jobs, either use the nohup command (see nohup(1)) or the
disown builtin.
SIGNALS

The INT and QUIT signals for an invoked command are ignored if the command is followed by & and
the MONITOR option is not active. Otherwise, signals have the values inherited by the shell from its
parent (but see the TRAPNAL special functions in the section Functions).
ARITHMETIC EVALUATION

The shell can perform integer and floating point arithmetic, either using the builtin let, or via a substitution
of the form $((...)). For integers, the shell is usually compiled to use 8byte precision where this is available, otherwise precision is 4 bytes. This can be tested, for example, by giving the command print $((
12345678901 )); if the number appears unchanged, the precision is at least 8 bytes. Floating point arithmetic is always double precision.
The let builtin command takes arithmetic expressions as arguments; each is evaluated separately. Since
many of the arithmetic operators, as well as spaces, require quoting, an alternative form is provided: for any
command which begins with a ((, all the characters until a matching )) are treated as a quoted expression
and arithmetic expansion performed as for an argument of let. More precisely, ((...)) is equivalent to let
" ..." . For example, the following statement
(( val = 2 + 1 ))
is equivalent to
let " val = 2 + 1"
both assigning the value 3 to the shell variable var and returning a zero status.
Integers can be in bases other than 10. A leading 0x or 0X denotes hexadecimal. Integers may also be
of the form base#n, where base is a decimal number between two and thirtysix representing the arithmetic base and n is a number in that base (for example, 16#ff is 255 in hexadecimal). The base# may also
be omitted, in which case base 10 is used. For backwards compatibility the form [base]n is also accepted.
It is also possible to specify a base to be used for output in the form [#base], for example [#16]. This is
used when outputting arithmetical substitutions or when assigning to scalar parameters, but an explicitly
defined integer or floating point parameter will not be affected. If an integer variable is implicitly defined
by an arithmetic expression, any base specified in this way will be set as the variables output arithmetic
base as if the option i base to the typeset builtin had been used. The expression has no precedence and if
it occurs more than once in a mathematical expression, the last encountered is used. For clarity it is recommended that it appear at the beginning of an expression. As an example:
typeset i 16 y
print $(( [#8] x = 32, y = 32 ))
print $x $y
outputs first 8#40, the rightmost value in the given output base, and then 8#40 16#20, because y has
been explicitly declared to have output base 16, while x (assuming it does not already exist) is implicitly
typed by the arithmetic evaluation, where it acquires the output base 8.
When an output base is specified using the [#base] syntax, an appropriate base prefix will be output if
necessary, so that the value output is valid syntax for input. If the # is doubled, for example [##16], then
no base prefix is output.

zsh 4.0.4

Last change: October 26, 2001

11

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

Floating point constants are recognized by the presence of a decimal point or an exponent. The decimal
point may be the first character of the constant, but the exponent character e or E may not, as it will be
taken for a parameter name.
An arithmetic expression uses nearly the same syntax, precedence, and associativity of expressions in C.
The following operators are supported (listed in decreasing order of precedence):
+ ! ++
unary plus/minus, logical NOT, complement, {pre,post}{in,de}crement
<< >> bitwise shift left, right
&
bitwise AND

bitwise XOR
bitwise OR

exponentiation
/ % multiplication, division, modulus (remainder)
+
addition, subtraction
< > <= >=
comparison
== != equality and inequality
&&
logical AND
logical OR, XOR

?:
ternary operator
= += = = /= %= &= = = <<= >>= &&= = = =
assignment
,
comma operator
The operators &&, , &&=, and = are shortcircuiting, and only one of the latter two expressions in
a ternary operator is evaluated. Note the precedence of the bitwise AND, OR, and XOR operators.
Mathematical functions can be called with the syntax func(args), where the function decides if the args is
used as a string or a commaseparated list of arithmetic expressions. The shell currently defines no
mathematical functions by default, but the module zsh/mathfunc may be loaded with the zmodload builtin
to provide standard floating point mathematical functions.
An expression of the form ##x where x is any character sequence such as a, A, or \M\Cx gives the
ASCII value of this character and an expression of the form #foo gives the ASCII value of the first character of the value of the parameter foo. Note that this is different from the expression $#foo, a standard
parameter substitution which gives the length of the parameter foo. #\ is accepted instead of ##, but its
use is deprecated.
Named parameters and subscripted arrays can be referenced by name within an arithmetic expression
without using the parameter expansion syntax. For example,
((val2 = val1 2))
assigns twice the value of $val1 to the parameter named val2.
An internal integer representation of a named parameter can be specified with the integer builtin. Arithmetic evaluation is performed on the value of each assignment to a named parameter declared integer in
this manner. Assigning a floating point number to an integer results in rounding down to the next integer.
Likewise, floating point numbers can be declared with the float builtin; there are two types, differing only
in their output format, as described for the typeset builtin. The output format can be bypassed by using
arithmetic substitution instead of the parameter substitution, i.e. ${float} uses the defined format, but
$((float)) uses a generic floating point format.
Promotion of integer to floating point values is performed where necessary. In addition, if any operator
which requires an integer (, &, , , %, <<, >> and their equivalents with assignment) is given a
floating point argument, it will be silently rounded down to the next integer.

zsh 4.0.4

Last change: October 26, 2001

12

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

Scalar variables can hold integer or floating point values at different times; there is no memory of the
numeric type in this case.
If a variable is first assigned in a numeric context without previously being declared, it will be implicitly
typed as integer or float and retain that type either until the type is explicitly changed or until the end of the
scope. This can have unforeseen consequences. For example, in the loop
for (( f = 0; f < 1; f += 0.1 )); do
# use $f
done
if f has not already been declared, the first assignment will cause it to be created as an integer, and consequently the operation f += 0.1 will always cause the result to be truncated to zero, so that the loop will
fail. A simple fix would be to turn the initialization into f = 0.0. It is therefore best to declare numeric
variables with explicit types.
CONDITIONAL EXPRESSIONS

A conditional expression is used with the [[ compound command to test attributes of files and to compare
strings. Each expression can be constructed from one or more of the following unary or binary expressions:
a file

true if file exists.

b file

true if file exists and is a block special file.

c file

true if file exists and is a character special file.

d file

true if file exists and is a directory.

e file

true if file exists.

f file

true if file exists and is a regular file.

g file

true if file exists and has its setgid bit set.

h file

true if file exists and is a symbolic link.

k file

true if file exists and has its sticky bit set.

n string
true if length of string is nonzero.
o option
true if option named option is on. option may be a single character, in which case it is a single
letter option name. (See the section Specifying Options.)
p file

true if file exists and is a FIFO special file (named pipe).

r file

true if file exists and is readable by current process.

s file

true if file exists and has size greater than zero.

t fd

true if file descriptor number fd is open and associated with a terminal device. (note: fd is not
optional)

u file

true if file exists and has its setuid bit set.

w file true if file exists and is writable by current process.


x file

true if file exists and is executable by current process. If file exists and is a directory, then the
current process has permission to search in the directory.

z string
true if length of string is zero.
L file true if file exists and is a symbolic link.
O file true if file exists and is owned by the effective user ID of this process.
G file true if file exists and its group matches the effective group ID of this process.

zsh 4.0.4

Last change: October 26, 2001

13

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

S file

ZSHMISC ( 1 )

true if file exists and is a socket.

N file true if file exists and its access time is not newer than its modification time.
file1 nt file2
true if file1 exists and is newer than file2.
file1 ot file2
true if file1 exists and is older than file2.
file1 ef file2
true if file1 and file2 exist and refer to the same file.
string = pattern
string == pattern
true if string matches pattern. The == form is the preferred one. The = form is for backward
compatibility and should be considered obsolete.
string != pattern
true if string does not match pattern.
string1 < string2
true if string1 comes before string2 based on ASCII value of their characters.
string1 > string2
true if string1 comes after string2 based on ASCII value of their characters.
exp1 eq exp2
true if exp1 is numerically equal to exp2.
exp1 ne exp2
true if exp1 is numerically not equal to exp2.
exp1 lt exp2
true if exp1 is numerically less than exp2.
exp1 gt exp2
true if exp1 is numerically greater than exp2.
exp1 le exp2
true if exp1 is numerically less than or equal to exp2.
exp1 ge exp2
true if exp1 is numerically greater than or equal to exp2.
( exp )

true if exp is true.

! exp

true if exp is false.

exp1 && exp2


true if exp1 and exp2 are both true.
exp1 exp2
true if either exp1 or exp2 is true.
Normal shell expansion is performed on the file, string and pattern arguments, but the result of each expansion is constrained to be a single word, similar to the effect of double quotes. However, pattern metacharacters are active for the pattern arguments; the patterns are the same as those used for filename generation,
see zshexpn(1), but there is no special behaviour of / nor initial dots, and no glob qualifiers are allowed.
In each of the above expressions, if file is of the form /dev/fd/n, where n is an integer, then the test applied
to the open file whose descriptor number is n, even if the underlying system does not support the /dev/fd
directory.

zsh 4.0.4

Last change: October 26, 2001

14

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

In the forms which do numeric comparison, the expressions exp undergo arithmetic expansion as if they
were enclosed in $((...)).
For example, the following:
[[ ( f foo f bar ) && $report = y ]] && print File exists.
tests if either file foo or file bar exists, and if so, if the value of the parameter report begins with y; if the
complete condition is true, the message File exists. is printed.
PROMPT EXPANSION

Prompt sequences undergo a special form of expansion. This type of expansion is also available using the
P option to the print builtin.
If the PROMPT_SUBST option is set, the prompt string is first subjected to parameter expansion, command substitution and arithmetic expansion. See zshexpn(1).
Certain escape sequences may be recognised in the prompt string.
If the PROMPT_BANG option is set, a ! in the prompt is replaced by the current history event number.
A literal ! may then be represented as !!.
If the PROMPT_PERCENT option is set, certain escape sequences that start with % are expanded.
Some escapes take an optional integer argument, which should appear between the % and the next character of the sequence. The following escape sequences are recognized:
%%

A %.

%)

A ).

%d
%/

Present working directory ($PWD). If an integer follows the %, it specifies a number of trailing
components of $PWD to show; zero means the whole path. A negative integer specifies leading
components, i.e. %1d specifies the first component.
As %d and %/, but if $PWD has a named directory as its prefix, that part is replaced by a followed by the name of the directory. If it starts with $HOME, that part is replaced by a .

%h
%!

Current history event number.

%L

The current value of $SHLVL.

%M

The full machine hostname.

%m

The hostname up to the first .. An integer may follow the % to specify how many components
of the hostname are desired. With a negative integer, trailing components of the hostname are
shown.

%S (%s)
Start (stop) standout mode.
%U (%u)
Start (stop) underline mode.
%B (%b)
Start (stop) boldface mode.

zsh 4.0.4

%t
%@

Current time of day, in 12hour, am/pm format.

%T

Current time of day, in 24hour format.

Current time of day in 24hour format, with seconds.

%n

$USERNAME.

Last change: October 26, 2001

15

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMISC ( 1 )

%N

The name of the script, sourced file, or shell function that zsh is currently executing, whichever
was started most recently. If there is none, this is equivalent to the parameter $0. An integer may
follow the % to specify a number of trailing path components to show; zero means the full path.
A negative integer specifies leading components.

%i

The line number currently being executed in the script, sourced file, or shell function given by
%N. This is most useful for debugging as part of $PS4.

%w

The date in daydd format.

%W

The date in mm/dd/yy format.

%D

The date in yymmdd format.

%D{string}
string is formatted using the strftime function. See strftime(3) for more details. Three additional
codes are available: %f prints the day of the month, like %e but without any preceding space if
the day is a single digit, and %K/%L correspond to %k/%l for the hour of the day (24/12 hour
clock) in the same way.
%l

The line (tty) the user is logged in on without /dev/ prefix. If name starts with /dev/tty this is
stripped.

%y

The line (tty) the user is logged in on without /dev/ prefix. It does not treat /dev/tty specially.

%?

The return code of the last command executed just before the prompt.

%_

The status of the parser, i.e. the shell constructs (like if and for) that have been started on the
command line. If given an integer number that many strings will be printed; zero or negative or no
integer means print as many as there are. This is most useful in prompts PS2 for continuation
lines and PS4 for debugging with the XTRACE option; in the latter case it will also work
noninteractively.

%E

Clears to end of line.

%#

A # if the shell is running with privileges, a % if not. Equivalent to %(!.#.%%). The


definition of privileged, for these purposes, is that either the effective user ID is zero, or, if
POSIX.1e capabilities are supported, that at least one capability is raised in either the Effective or
Inheritable capability vectors.

%v

The value of the first element of the psvar array parameter. Following the % with an integer
gives that element of the array. Negative integers count from the end of the array.

%{...%}
Include a string as a literal escape sequence. The string within the braces should not change the
cursor position. Brace pairs can nest.
%(x.truetext.falsetext)
Specifies a ternary expression. The character following the x is arbitrary; the same character is
used to separate the text for the true result from that for the false result. This separator may not
appear in the truetext, except as part of a %escape sequence. A ) may appear in the falsetext
as %). truetext and falsetext may both contain arbitrarilynested escape sequences, including
further ternary expressions.
The left parenthesis may be preceded or followed by a positive integer n, which defaults to zero.
A negative integer will be multiplied by 1. The test character x may be any of the following:
c
.

/
C
t

zsh 4.0.4

True if the current path, with prefix replacement, has at least n elements.
True if the current absolute path has at least n elements.
True if the time in minutes is equal to n.

Last change: October 26, 2001

16

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

T
d
D
w
?
#
g
l
L
S
v
_
!

ZSHMISC ( 1 )

True if the time in hours is equal to n.


True if the day of the month is equal to n.
True if the month is equal to n (January = 0).
True if the day of the week is equal to n (Sunday = 0).
True if the exit status of the last command was n.
True if the effective uid of the current process is n.
True if the effective gid of the current process is n.
True if at least n characters have already been printed on the current line.
True if the SHLVL parameter is at least n.
True if the SECONDS parameter is at least n.
True if the array psvar has at least n elements.
True if at least n shell constructs were started.
True if the shell is running with privileges.

%<string<
%>string>
%[xstring]
Specifies truncation behaviour for the remainder of the prompt string. The third, deprecated, form
is equivalent to %xstringx, i.e. x may be < or >. The numeric argument, which in the third
form may appear immediately after the [, specifies the maximum permitted length of the various
strings that can be displayed in the prompt. The string will be displayed in place of the truncated
portion of any string; note this does not undergo prompt expansion.
The forms with < truncate at the left of the string, and the forms with > truncate at the right of
the string. For example, if the current directory is /home/pike, the prompt %8<..<%/ will
expand to ..e/pike. In this string, the terminating character (<, > or ]), or in fact any character, may be quoted by a preceding \; note when using print P, however, that this must be doubled as the string is also subject to standard print processing, in addition to any backslashes
removed by a double quoted string: the worst case is therefore print P " %<\\\\<<..." .
If the string is longer than the specified truncation length, it will appear in full, completely replacing the truncated string.
The part of the prompt string to be truncated runs to the end of the string, or to the end of the next
enclosing group of the %( construct, or to the next truncation encountered at the same grouping
level (i.e. truncations inside a %( are separate), which ever comes first. In particular, a truncation with argument zero (e.g. %<<) marks the end of the range of the string to be truncated while
turning off truncation from there on. For example, the prompt %10<...<%%<<%# will print a
truncated representation of the current directory, followed by a % or #, followed by a space.
Without the %<<, those two characters would be included in the string to be truncated.
%c
%.
%C

zsh 4.0.4

Trailing component of $PWD. An integer may follow the % to get more than one component.
Unless %C is used, tilde contraction is performed first. These are deprecated as %c and %C are
equivalent to %1 and %1/, respectively, while explicit positive integers have the same effect as
for the latter two sequences.

Last change: October 26, 2001

17

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHEXPN ( 1 )

NAME

zshexpn zsh expansion and substitution


DESCRIPTION

The following types of expansions are performed in the indicated order in five steps:
History Expansion
This is performed only in interactive shells.
Alias Expansion
Aliases are expanded immediately before the command line is parsed as explained under Aliasing
in zshmisc(1).
Process Substitution
Parameter Expansion
Command Substitution
Arithmetic Expansion
Brace Expansion
These five are performed in one step in lefttoright fashion. After these expansions, all unquoted
occurrences of the characters \, and " are removed.
Filename Expansion
If the SH_FILE_EXPANSION option is set, the order of expansion is modified for compatibility
with sh and ksh. In that case filename expansion is performed immediately after alias expansion,
preceding the set of five expansions mentioned above.
Filename Generation
This expansion, commonly referred to as globbing, is always done last.
The following sections explain the types of expansion in detail.
HISTORY EXPANSION

History expansion allows you to use words from previous command lines in the command line you are typing. This simplifies spelling corrections and the repetition of complicated commands or arguments.
Immediately before execution, each command is saved in the history list, the size of which is controlled by
the HISTSIZE parameter. The one most recent command is always retained in any case. Each saved command in the history list is called a history event and is assigned a number, beginning with 1 (one) when the
shell starts up. The history number that you may see in your prompt (see Prompt Expansion in zshmisc(1))
is the number that is to be assigned to the next command.
Overview

A history expansion begins with the first character of the histchars parameter, which is ! by default, and
may occur anywhere on the command line; history expansions do not nest. The ! can be escaped with \
or can be enclosed between a pair of single quotes () to suppress its special meaning. Double quotes will
not work for this. Following this history character is an optional event designator (see the section Event
Designators) and then an optional word designator (the section Word Designators); if neither of these
designators is present, no history expansion occurs.
Input lines containing history expansions are echoed after being expanded, but before any other expansions
take place and before the command is executed. It is this expanded form that is recorded as the history
event for later references.
By default, a history reference with no event designator refers to the same event as any preceding history
reference on that command line; if it is the only history reference in a command, it refers to the previous
command. However, if the option CSH_JUNKIE_HISTORY is set, then every history reference with no
event specification always refers to the previous command.
For example, ! is the event designator for the previous command, so !!:1 always refers to the first word
of the previous command, and !!$ always refers to the last word of the previous command. With
CSH_JUNKIE_HISTORY set, then !:1 and !$ function in the same manner as !!:1 and !!$, respectively. Conversely, if CSH_JUNKIE_HISTORY is unset, then !:1 and !$ refer to the first and last

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

words, respectively, of the same event referenced by the nearest other history reference preceding them on
the current command line, or to the previous command if there is no preceding reference.
The character sequence foobar (where is actually the second character of the histchars parameter)
repeats the last command, replacing the string foo with bar. More precisely, the sequence foobar is
synonymous with !!:sfoobar, hence other modifiers (see the section Modifiers) may follow the final
.
If the shell encounters the character sequence !" in the input, the history mechanism is temporarily disabled until the current list (see zshmisc(1)) is fully parsed. The !" is removed from the input, and any
subsequent ! characters have no special significance.
A less convenient but more comprehensible form of command history support is provided by the fc builtin.
Event Designators

An event designator is a reference to a commandline entry in the history list. In the list below, remember
that the initial ! in each item may be changed to another character by setting the histchars parameter.
!

Start a history expansion, except when followed by a blank, newline, = or (. If followed


immediately by a word designator (see the section Word Designators), this forms a history reference with no event designator (see the section Overview).

!!

Refer to the previous command. By itself, this expansion repeats the previous command.

!n

Refer to commandline n.

!n

Refer to the current commandline minus n.

!str

Refer to the most recent command starting with str.

!?str[?] Refer to the most recent command containing str. The trailing ? is necessary if this reference is
to be followed by a modifier or followed by any text that is not to be considered part of str.
!#

Refer to the current command line typed in so far. The line is treated as if it were complete up to
and including the word before the one with the !# reference.

!{...}

Insulate a history reference from adjacent characters (if necessary).

Word Designators

A word designator indicates which word or words of a given command line are to be included in a history
reference. A : usually separates the event specification from the word designator. It may be omitted only
if the word designator begins with a , $, , or %. Word designators include:
0
n

$
%
xy

x
x

The first input word (command).


The nth argument.
The first argument. That is, 1.
The last argument.
The word matched by (the most recent) ?str search.
A range of words; x defaults to 0.
All the arguments, or a null value if there are none.
Abbreviates x$.
Like x but omitting word $.

Note that a % word designator works only when used in one of !%, !:% or !?str?:%, and only when
used after a !? expansion (possibly in an earlier command). Anything else results in an error, although the
error may not be the most obvious one.
Modifiers

After the optional word designator, you can add a sequence of one or more of the following modifiers, each
preceded by a :. These modifiers also work on the result of filename generation and parameter expansion, except where noted.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

Remove a trailing pathname component, leaving the head. This works like dirname.

Remove a filename extension of the form .xxx, leaving the root name.

Remove all but the extension.

Remove all leading pathname components, leaving the tail. This works like basename.

Print the new command but do not execute it. Only works with history expansion.

Quote the substituted words, escaping further substitutions. Works with history expansion and
parameter expansion, though for parameters it is only useful if the resulting text is to be
reevaluated such as by eval.

Remove one level of quotes from the substituted words.

Like q, but break into words at whitespace. Does not work with parameter expansion.

Convert the words to all lowercase.

Convert the words to all uppercase.

s/l/r[/]

Substitute r for l as described below. Unless preceded immediately by a g, with no colon between,
the substitution is done only for the first string that matches l. For arrays and for filename generation, this applies to each word of the expanded text.

&

Repeat the previous s substitution. Like s, may be preceded immediately by a g. In parameter


expansion the & must appear inside braces, and in filename generation it must be quoted with a
backslash.

The s/l/r/ substitution works as follows. The lefthand side of substitutions are not regular expressions, but
character strings. Any character can be used as the delimiter in place of /. A backslash quotes the delimiter character. The character &, in the righthandside r, is replaced by the text from the lefthandside l.
The & can be quoted with a backslash. A null l uses the previous string either from the previous l or from
the contextual scan string s from !?s. You can omit the rightmost delimiter if a newline immediately follows r; the rightmost ? in a context scan can similarly be omitted. Note the same record of the last l and r
is maintained across all forms of expansion.
The following f, F, w and W modifiers work only with parameter expansion and filename generation. They
are listed here to provide a single point of reference for all modifiers.
f

Repeats the immediately (without a colon) following modifier until the resulting word doesnt
change any more.

F:expr: Like f, but repeats only n times if the expression expr evaluates to n. Any character can be used
instead of the :; if (, [, or { is used as the opening delimiter, the closing delimiter should be
), ], or }, respectively.
w

Makes the immediately following modifier work on each word in the string.

W:sep: Like w but words are considered to be the parts of the string that are separated by sep. Any character can be used instead of the :; opening parentheses are handled specially, see above.
PROCESS SUBSTITUTION

Each command argument of the form <(list), >(list) or =(list) is subject to process substitution. In the
case of the < or > forms, the shell runs process list asynchronously. If the system supports the /dev/fd
mechanism, the command argument is the name of the device file corresponding to a file descriptor; otherwise, if the system supports named pipes (FIFOs), the command argument will be a named pipe. If the
form with > is selected then writing on this special file will provide input for list. If < is used, then the file
passed as an argument will be connected to the output of the list process. For example,
paste <(cut f1 file1) <(cut f3 file2)
tee >(process1) >(process2) >/dev/null

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

cuts fields 1 and 3 from the files file1 and file2 respectively, pastes the results together, and sends it to the
processes process1 and process2.
Both the /dev/fd and the named pipe implementation have drawbacks. In the former case, some programmes may automatically close the file descriptor in question before examining the file on the command
line, particularly if this is necessary for security reasons such as when the programme is running setuid. In
the second case, if the programme does not actually open the file, the subshell attempting to read from or
write to the pipe will (in a typical implementation, different operating systems may have different
behaviour) block for ever and have to be killed explicitly. In both cases, the shell actually supplies the
information using a pipe, so that programmes that expect to lseek (see lseek(2)) on the file will not work.
Also note that the previous example can be more compactly and efficiently written (provided the MULTIOS option is set) as:
paste <(cut f1 file1) <(cut f3 file2) \
> >(process1) > >(process2)
The shell uses pipes instead of FIFOs to implement the latter two process substitutions in the above example.
If = is used, then the file passed as an argument will be the name of a temporary file containing the output
of the list process. This may be used instead of the < form for a program that expects to lseek (see lseek(2))
on the input file.
PARAMETER EXPANSION

The character $ is used to introduce parameter expansions. See zshparam(1) for a description of parameters, including arrays, associative arrays, and subscript notation to access individual array elements.
In the expansions discussed below that require a pattern, the form of the pattern is the same as that used for
filename generation; see the section Filename Generation. Note that these patterns, along with the
replacement text of any substitutions, are themselves subject to parameter expansion, command substitution, and arithmetic expansion. In addition to the following operations, the colon modifiers described in the
section Modifiers in the section History Expansion can be applied: for example, ${i:s/foo/bar/} performs string substitution on the expansion of parameter $i.
${name}
The value, if any, of the parameter name is substituted. The braces are required if the expansion is
to be followed by a letter, digit, or underscore that is not to be interpreted as part of name. In addition, more complicated forms of substitution usually require the braces to be present; exceptions,
which only apply if the option KSH_ARRAYS is not set, are a single subscript or any colon
modifiers appearing after the name, or any of the characters , =, , # or + appearing before
the name, all of which work with or without braces.
If name is an array parameter, and the KSH_ARRAYS option is not set, then the value of each
element of name is substituted, one element per word. Otherwise, the expansion results in one
word only; with KSH_ARRAYS, this is the first element of an array. No field splitting is done on
the result unless the SH_WORD_SPLIT option is set.
${+name}
If name is the name of a set parameter 1 is substituted, otherwise 0 is substituted.
${name:word}
If name is set and is nonnull then substitute its value; otherwise substitute word. If name is missing, substitute word.
${name:=word}
${name::=word}
In the first form, if name is unset or is null then set it to word; in the second form, unconditionally
set name to word. In both forms, the value of the parameter is then substituted.
${name:?word}

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

If name is set and is nonnull then substitute its value; otherwise, print word and exit from the
shell. Interactive shells instead return to the prompt. If word is omitted, then a standard message
is printed.
${name:+word}
If name is set and is nonnull then substitute word; otherwise substitute nothing.
If the colon is omitted from one of the above expressions containing a colon, then the shell only checks
whether name is set, not whether its value is null.
In the following expressions, when name is an array and the substitution is not quoted, or if the (@) flag
or the name[@] syntax is used, matching and replacement is performed on each array element separately.
${name#pattern}
${name##pattern}
If the pattern matches the beginning of the value of name, then substitute the value of name with
the matched portion deleted; otherwise, just substitute the value of name. In the first form, the
smallest matching pattern is preferred; in the second form, the largest matching pattern is preferred.
${name%pattern}
${name%%pattern}
If the pattern matches the end of the value of name, then substitute the value of name with the
matched portion deleted; otherwise, just substitute the value of name. In the first form, the smallest matching pattern is preferred; in the second form, the largest matching pattern is preferred.
${name:#pattern}
If the pattern matches the value of name, then substitute the empty string; otherwise, just substitute the value of name. If name is an array the matching array elements are removed (use the
(M) flag to remove the nonmatched elements).
${name/pattern/repl}
${name//pattern/repl}
Replace the longest possible match of pattern in the expansion of parameter name by string repl.
The first form replaces just the first occurrence, the second form all occurrences. Both pattern and
repl are subject to doublequoted substitution, so that expressions like ${name/$opat/$npat} will
work, but note the usual rule that pattern characters in $opat are not treated specially unless either
the option GLOB_SUBST is set, or $opat is instead substituted as ${opat}.
The pattern may begin with a #, in which case the pattern must match at the start of the string, or
%, in which case it must match at the end of the string. The repl may be an empty string, in
which case the final / may also be omitted. To quote the final / in other cases it should be preceded by two backslashes (i.e., a quoted backslash); this is not necessary if the / occurs inside a
substituted parameter. Note also that the # and % are not active if they occur inside a substituted parameter, even at the start.
The first / may be preceded by a :, in which case the match will only succeed if it matches the
entire word. Note also the effect of the I and S parameter expansion flags below; however, the
flags M, R, B, E and N are not useful.
For example,
foo=" twinkle twinkle little star" sub=" te" rep=" spy"
print ${foo//${sub}/$rep}
print ${(S)foo//${sub}/$rep}
Here, the ensures that the text of $sub is treated as a pattern rather than a plain string. In the
first case, the longest match for te is substituted and the result is spy star, while in the second
case, the shortest matches are taken and the result is spy spy lispy star.
${#spec}

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

If spec is one of the above substitutions, substitute the length in characters of the result instead of
the result itself. If spec is an array expression, substitute the number of elements of the result.
Note that , =, and , below, must appear to the left of # when these forms are combined.
${spec}
Turn on the RC_EXPAND_PARAM option for the evaluation of spec; if the is doubled, turn it
off. When this option is set, array expansions of the form foo${xx}bar, where the parameter xx is
set to (a b c), are substituted with fooabar foobbar foocbar instead of the default fooa b cbar.
Internally, each such expansion is converted into the equivalent list for brace expansion. E.g.,
${var} becomes {$var[1],$var[2],...}, and is processed as described in the section Brace Expansion below. If word splitting is also in effect the $var[N] may themselves be split into different
list elements.
${=spec}
Perform word splitting using the rules for SH_WORD_SPLIT during the evaluation of spec, but
regardless of whether the parameter appears in double quotes; if the = is doubled, turn it off.
This forces parameter expansions to be split into separate words before substitution, using IFS as a
delimiter. This is done by default in most other shells.
Note that splitting is applied to word in the assignment forms of spec before the assignment to
name is performed. This affects the result of array assignments with the A flag.
${spec}
Turn on the GLOB_SUBST option for the evaluation of spec; if the is doubled, turn it off.
When this option is set, the string resulting from the expansion will be interpreted as a pattern anywhere that is possible, such as in filename expansion and filename generation and
patternmatching contexts like the right hand side of the = and != operators in conditions.
If a ${...} type parameter expression or a $(...) type command substitution is used in place of name above, it
is expanded first and the result is used as if it were the value of name. Thus it is possible to perform nested
operations: ${${foo#head}%tail} substitutes the value of $foo with both head and tail deleted. The
form with $(...) is often useful in combination with the flags described next; see the examples below. Each
name or nested ${...} in a parameter expansion may also be followed by a subscript expression as described
in Array Parameters in zshparam(1).
Note that double quotes may appear around nested expressions, in which case only the part inside is treated
as quoted; for example, ${(f)" $(foo)" } quotes the result of $(foo), but the flag (f) (see below) is applied
using the rules for unquoted expansions. Note further that quotes are themselves nested in this context; for
example, in " ${(@f)" $(foo)" }" , there are two sets of quotes, one surrounding the whole expression, the
other (redundant) surrounding the $(foo) as before.
Parameter Expansion Flags

If the opening brace is directly followed by an opening parenthesis, the string up to the matching closing
parenthesis will be taken as a list of flags. In cases where repeating a flag is meaningful, the repetitions
need not be consecutive; for example, (q%q%q) means the same thing as the more readable
(%%qqq). The following flags are supported:

zsh 4.0.4

Expand all % escapes in the resulting words in the same way as in in prompts (see the section
Prompt Expansion). If this flag is given twice, full prompt expansion is done on the resulting
words, depending on the setting of the PROMPT_PERCENT, PROMPT_SUBST and
PROMPT_BANG options.

In double quotes, array elements are put into separate words. E.g., " ${(@)foo}" is equivalent to
" ${foo[@]}" and " ${(@)foo[1,2]}" is the same as " $foo[1]" " $foo[2]" . This is distinct
from field splitting by the the f, s or z flags, which still applies within each array element.

Create an array parameter with ${...=...}, ${...:=...} or ${...::=...}. If this flag is repeated (as in
AA), create an associative array parameter. Assignment is made before sorting or padding. The
name part may be a subscripted range for ordinary arrays; the word part must be converted to an

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

array, for example by using ${(AA)=name=...} to activate field splitting, when creating an associative array.
c

With ${#name}, count the total number of characters in an array, as if the elements were concatenated with spaces between them.

Capitalize the resulting words. Words in this case refers to sequences of alphanumeric characters
separated by nonalphanumerics, not to words that result from field splitting.

Perform parameter expansion, command substitution and arithmetic expansion on the result. Such
expansions can be nested but too deep recursion may have unpredictable effects.

Split the result of the expansion to lines. This is a shorthand for ps:\n:.

Join the words of arrays together using newline as a separator. This is a shorthand for pj:\n:.

With o or O, sort caseindependently.

If name refers to an associative array, substitute the keys (element names) rather than the values of
the elements. Used with subscripts (including ordinary arrays), force indices or keys to be substituted even if the subscript form refers to values. However, this flag may not be combined with
subscript ranges.

Convert all letters in the result to lower case.

Sort the resulting words in ascending order.

Sort the resulting words in descending order.

This forces the value of the parameter name to be interpreted as a further parameter name, whose
value will be used where appropriate. If used with a nested parameter or command substitution,
the result of that will be taken as a parameter name in the same way. For example, if you have
foo=bar and bar=baz, the strings ${(P)foo}, ${(P)${foo}}, and ${(P)$(echo bar)} will be
expanded to baz.

Quote the resulting words with backslashes. If this flag is given twice, the resulting words are
quoted in single quotes and if it is given three times, the words are quoted in double quotes. If it is
given four times, the words are quoted in single quotes preceded by a $.

Remove one level of quotes from the resulting words.

Use a string describing the type of the parameter where the value of the parameter would usually
appear. This string consists of keywords separated by hyphens (). The first keyword in the
string describes the main type, it can be one of scalar, array, integer, float or association. The other keywords describe the type in more detail:
local

for local parameters

left

for left justified parameters

right_blanks
for right justified parameters with leading blanks
right_zeros
for right justified parameters with leading zeros
lower

for parameters whose value is converted to all lower case when it is expanded

upper

for parameters whose value is converted to all upper case when it is expanded

readonly
for readonly parameters
tag

for tagged parameters

export for exported parameters


unique for arrays which keep only the first occurrence of duplicated values

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

hide

ZSHEXPN ( 1 )

for parameters with the hide flag

special for special parameters defined by the shell


U

Convert all letters in the result to upper case.

Used with k, substitute (as two consecutive words) both the key and the value of each associative
array element. Used with subscripts, force values to be substituted even if the subscript form
refers to indices or keys.

Make any special characters in the resulting words visible.

With ${#name}, count words in arrays or strings; the s flag may be used to set a word delimiter.

Similar to w with the difference that empty words between repeated delimiters are also counted.

With this flag parsing errors occurring with the Q and e flags or the pattern matching forms such
as ${name#pattern} are reported. Without the flag they are silently ignored.

Split the result of the expansion into words using shell parsing to find the words, i.e. taking into
account any quoting in the value.
Note that this is done very late, as for the (s) flag. So to access single words in the result, one has
to use nested expansions as in ${${(z)foo}[2]}. Likewise, to remove the quotes in the resulting
words one would do: ${(Q)${(z)foo}}.

The following flags (except p) are followed by one or more arguments as shown. Any character, or the
matching pairs (...), {...}, [...], or <...>, may be used in place of a colon as delimiters, but note that
when a flag takes more than one argument, a matched pair of delimiters must surround each argument.
p

Recognize the same escape sequences as the print builtin in string arguments to any of the flags
described below.

j:string:
Join the words of arrays together using string as a separator. Note that this occurs before field
splitting by the SH_WORD_SPLIT option.
l:expr::string1::string2:
Pad the resulting words on the left. Each word will be truncated if required and placed in a field
expr characters wide. The space to the left will be filled with string1 (concatenated as often as
needed) or spaces if string1 is not given. If both string1 and string2 are given, this string is
inserted once directly to the left of each word, before padding.
r:expr::string1::string2:
As l, but pad the words on the right and insert string2 on the right.
s:string:
Force field splitting (see the option SH_WORD_SPLIT) at the separator string. Note that a
string of two or more characters means all must all match in sequence; this differs from the treatment of two or more characters in the IFS parameter.
The following flags are meaningful with the ${...#...} or ${...%...} forms. The S and I flags may also be
used with the ${.../...} forms.
S

Search substrings as well as beginnings or ends; with # start from the beginning and with % start
from the end of the string. With substitution via ${.../...} or ${...//...}, specifies nongreedy matching, i.e. that the shortest instead of the longest match should be replaced.

I:expr: Search the exprth match (where expr evaluates to a number). This only applies when searching for
substrings, either with the S flag, or with ${.../...} (only the exprth match is substituted) or ${...//...}
(all matches from the exprth on are substituted). The default is to take the first match.
The exprth match is counted such that there is either one or zero matches from each starting position in the string, although for global substitution matches overlapping previous replacements are
ignored. With the ${...%...} and ${...%%...} forms, the starting position for the match moves

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHEXPN ( 1 )

backwards from the end as the index increases, while with the other forms it moves forward from
the start.
Hence with the string
which switch is the right switch for Ipswich?
substitutions of the form ${(SI:N:)string#wch} as N increases from 1 will match and remove
which, witch, witch and wich; the form using ## will match and remove which switch is
the right switch for Ipswich, witch is the right switch for Ipswich, witch for Ipswich and
wich. The form using % will remove the same matches as for #, but in reverse order, and the
form using %% will remove the same matches as for ## in reverse order.
B

Include the index of the beginning of the match in the result.

Include the index of the end of the match in the result.

Include the matched portion in the result.

Include the length of the match in the result.

Include the unmatched portion in the result (the Rest).

Rules

Here is a summary of the rules for substitution; this assumes that braces are present around the substitution,
i.e. ${...}. Some particular examples are given below. Note that the Zsh Development Group accepts no
responsibility for any brain damage which may occur during the reading of the following rules.
1. Nested Substitution
If multiple nested ${...} forms are present, substitution is performed from the inside outwards. At
each level, the substitution takes account of whether the current value is a scalar or an array,
whether the whole substitution is in double quotes, and what flags are supplied to the current level
of substitution, just as if the nested substitution were the outermost. The flags are not propagated
up to enclosing substitutions; the nested substitution will return either a scalar or an array as determined by the flags, possibly adjusted for quoting. All the following steps take place where applicable at all levels of substitution. Note that, unless the (P) flag is present, the flags and any subscripts apply directly to the value of the nested substitution; for example, the expansion ${${foo}}
behaves exactly the same as ${foo}.
2. Parameter Subscripting
If the value is a raw parameter reference with a subscript, such as ${var[3]}, the effect of subscripting is applied directly to the parameter. Subscripts are evaluated left to right; subsequent subscripts apply to the scalar or array value yielded by the previous subscript. Thus if var is an array,
${var[1][2]} is the second character of the first word, but ${var[2,4][2]} is the entire third word
(the second word of the range of words two through four of the original array). Any number of
subscripts may appear.
3. Parameter Name Replacement
The effect of any (P) flag, which treats the value so far as a parameter name and replaces it with
the corresponding value, is applied.
4. DoubleQuoted Joining
If the value after this process is an array, and the substitution appears in double quotes, and no (@)
flag is present at the current level, the words of the value are joined with the first character of the
parameter $IFS, by default a space, between each word (single word arrays are not modified). If
the (j) flag is present, that is used for joining instead of $IFS.
5. Nested Subscripting
Any remaining subscripts (i.e. of a nested substitution) are evaluated at this point, based on
whether the value is an array or a scalar. As with 2., multiple subscripts can appear. Note that
${foo[2,4][2]} is thus equivalent to ${${foo[2,4]}[2]} and also to " ${${(@)foo[2,4]}[2]}" (the
nested substitution returns an array in both cases), but not to " ${${foo[2,4]}[2]}" (the nested substitution returns a scalar because of the quotes).

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHEXPN ( 1 )

6. Modifiers
Any modifiers, as specified by a trailing #, %, / (possibly doubled) or by a set of modifiers of
the form :... (see the section Modifiers in the section History Expansion), are applied to the
words of the value at this level.
7. Forced Joining
If the (j) flag is present, or no (j) flag is present but the string is to be split as given by rules 8.
or 9., and joining did not take place at step 4., any words in the value are joined together using the
given string or the first character of $IFS if none. Note that the (F) flag implicitly supplies a
string for joining in this manner.
8. Forced Splitting
If one of the (s), (f) or (z) flags are present, or the = specifier was present (e.g. ${=var}), the
word is split on occurrences of the specified string, or (for = with neither of the two flags present)
any of the characters in $IFS.
9. Shell Word Splitting
If no (s), (f) or = was given, but the word is not quoted and the option SH_WORD_SPLIT is
set, the word is split on occurrences of any of the characters in $IFS. Note this step, too, takes
place at all levels of a nested substitution.
10. ReEvaluation
Any (e) flag is applied to the value, forcing it to be reexamined for new parameter substitutions,
but also for command and arithmetic substitutions.
11. Padding
Any padding of the value by the (l.fill.) or (r.fill.) flags is applied.
12. Semantic Joining
In contexts where expansion semantics requires a single word to result, all words are rejoined with
the first character of IFS between. So in ${(P)${(f)lines}} the value of ${lines} is split at newlines, but then must be joined again before the P flag can be applied.
If a single word is not required, this rule is skipped.
Examples

The flag f is useful to split a doublequoted substitution line by line. For example, ${(f)" $(<file)" } substitutes the contents of file divided so that each line is an element of the resulting array. Compare this with the
effect of $(<file) alone, which divides the file up by words, or the same inside double quotes, which makes
the entire content of the file a single string.
The following illustrates the rules for nested parameter expansions. Suppose that $foo contains the array
(bar baz):
" ${(@)${foo}[1]}"
This produces the result b. First, the inner substitution " ${foo}" , which has no array (@) flag,
produces a single word result " bar baz" . The outer substitution " ${(@)...[1]}" detects that this is
a scalar, so that (despite the (@) flag) the subscript picks the first character.
" ${${(@)foo}[1]}"
This produces the result bar. In this case, the inner substitution " ${(@)foo}" produces the array
(bar baz). The outer substitution " ${...[1]}" detects that this is an array and picks the first word.
This is similar to the simple case " ${foo[1]}" .

As an example of the rules for word splitting and joining, suppose $foo contains the array (ax1 bx1).
Then
${(s/x/)foo}
produces the words a, 1 b and 1.
${(j/x/s/x/)foo}
produces a, 1, b and 1.

zsh 4.0.4

Last change: October 26, 2001

10

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHEXPN ( 1 )

${(s/x/)foo%%1}
produces a and b (note the extra space). As substitution occurs before either joining or splitting, the operation first generates the modified array (ax bx), which is joined to give " ax bx" , and
then split to give a, b and . The final empty string will then be elided, as it is not in double
quotes.
COMMAND SUBSTITUTION

A command enclosed in parentheses preceded by a dollar sign, like $(...), or quoted with grave accents,
like ..., is replaced with its standard output, with any trailing newlines deleted. If the substitution is not
enclosed in double quotes, the output is broken into words using the IFS parameter. The substitution $(cat
foo) may be replaced by the equivalent but faster $(<foo). In either case, if the option GLOB_SUBST is
set, the output is eligible for filename generation.
ARITHMETIC EXPANSION

A string of the form $[exp] or $((exp)) is substituted with the value of the arithmetic expression exp. exp
is subjected to parameter expansion, command substitution and arithmetic expansion before it is evaluated.
See the section Arithmetic Evaluation.
BRACE EXPANSION

A string of the form foo{xx,yy,zz}bar is expanded to the individual words fooxxbar, fooyybar and
foozzbar. Lefttoright order is preserved. This construct may be nested. Commas may be quoted in
order to include them literally in a word.
An expression of the form {n1..n2}, where n1 and n2 are integers, is expanded to every number between
n1 and n2 inclusive. If either number begins with a zero, all the resulting numbers will be padded with
leading zeroes to that minimum width. If the numbers are in decreasing order the resulting sequence will
also be in decreasing order.
If a brace expression matches none of the above forms, it is left unchanged, unless the BRACE_CCL
option is set. In that case, it is expanded to a sorted list of the individual characters between the braces, in
the manner of a search set. is treated specially as in a search set, but or ! as the first character is
treated normally.
Note that brace expansion is not part of filename generation (globbing); an expression such as /{foo,bar}
is split into two separate words /foo and /bar before filename generation takes place. In particular, note
that this is liable to produce a no match error if either of the two expressions does not match; this is to be
contrasted with /(foobar), which is treated as a single pattern but otherwise has similar effects.
FILENAME EXPANSION

Each word is checked to see if it begins with an unquoted . If it does, then the word up to a /, or the end
of the word if there is no /, is checked to see if it can be substituted in one of the ways described here. If
so, then the and the checked portion are replaced with the appropriate substitute value.
A by itself is replaced by the value of $HOME. A followed by a + or a is replaced by the value
of $PWD or $OLDPWD, respectively.
A followed by a number is replaced by the directory at that position in the directory stack. 0 is
equivalent to +, and 1 is the top of the stack. + followed by a number is replaced by the directory at
that position in the directory stack. +0 is equivalent to +, and +1 is the top of the stack. followed by a number is replaced by the directory that many positions from the bottom of the stack. 0 is
the bottom of the stack. The PUSHD_MINUS option exchanges the effects of + and where they are
followed by a number.
A followed by anything not already covered is looked up as a named directory, and replaced by the
value of that named directory if found. Named directories are typically home directories for users on the
system. They may also be defined if the text after the is the name of a string shell parameter whose
value begins with a /. It is also possible to define directory names using the d option to the hash builtin.

zsh 4.0.4

Last change: October 26, 2001

11

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

In certain circumstances (in prompts, for instance), when the shell prints a path, the path is checked to see if
it has a named directory as its prefix. If so, then the prefix portion is replaced with a followed by the
name of the directory. The shortest way of referring to the directory is used, with ties broken in favour of
using a named directory, except when the directory is / itself. The parameters $PWD and $OLDPWD are
never abbreviated in this fashion.
If a word begins with an unquoted = and the EQUALS option is set, the remainder of the word is taken as
the name of a command or alias. If a command exists by that name, the word is replaced by the full pathname of the command. If an alias exists by that name, the word is replaced with the text of the alias.
Filename expansion is performed on the right hand side of a parameter assignment, including those appearing after commands of the typeset family. In this case, the right hand side will be treated as a
colonseparated list in the manner of the PATH parameter, so that a or an = following a : is eligible
for expansion. All such behaviour can be disabled by quoting the , the =, or the whole expression (but
not simply the colon); the EQUALS option is also respected.
If the option MAGIC_EQUAL_SUBST is set, any unquoted shell argument in the form
identifier=expression becomes eligible for file expansion as described in the previous paragraph. Quoting
the first = also inhibits this.
FILENAME GENERATION

If a word contains an unquoted instance of one of the characters , (, , <, [, or ?, it is regarded as


a pattern for filename generation, unless the GLOB option is unset. If the EXTENDED_GLOB option is
set, the and # characters also denote a pattern; otherwise they are not treated specially by the shell.
The word is replaced with a list of sorted filenames that match the pattern. If no matching pattern is found,
the shell gives an error message, unless the NULL_GLOB option is set, in which case the word is deleted;
or unless the NOMATCH option is unset, in which case the word is left unchanged.

In filename generation, the character / must be matched explicitly; also, a . must be matched explicitly at
the beginning of a pattern or after a /, unless the GLOB_DOTS option is set. No filename generation pattern matches the files . or ... In other instances of pattern matching, the / and . are not treated specially.
Glob Operators

Matches any string, including the null string.

Matches any character.

[...]

Matches any of the enclosed characters. Ranges of characters can be specified by separating two
characters by a . A or ] may be matched by including it as the first character in the list.
There are also several named classes of characters, in the form [:name:] with the following
meanings: [:alnum:] alphanumeric, [:alpha:] alphabetic, [:blank:] space or tab, [:cntrl:]
control character, [:digit:] decimal digit, [:graph:] printable character except whitespace,
[:lower:] lowercase letter, [:print:] printable character, [:punct:] printable character neither
alphanumeric nor whitespace, [:space:] whitespace character, [:upper:] uppercase letter,
[:xdigit:] hexadecimal digit. These use the macros provided by the operating system to test for
the given character combinations, including any modifications due to local language settings: see
ctype(3). Note that the square brackets are additional to those enclosing the whole set of characters, so to test for a single alphanumeric character you need [[:alnum:]]. Named character sets
can be used alongside other types, e.g. [[:alpha:]09].

[...]
[!...]

Like [...], except that it matches any character which is not in the given set.

<[x][y]>
Matches any number in the range x to y, inclusive. Either of the numbers may be omitted to make
the range openended; hence <> matches any number. To match individual digits, the [...] form
is more efficient.

zsh 4.0.4

Last change: October 26, 2001

12

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

Be careful when using other wildcards adjacent to patterns of this form; for example, <09> will
actually match any number whatsoever at the start of the string, since the <09> will match the
first digit, and the will match any others. This is a trap for the unwary, but is in fact an inevitable consequence of the rule that the longest possible match always succeeds. Expressions such as
<09>[[:digit:]] can be used instead.
(...)

Matches the enclosed pattern. This is used for grouping. If the KSH_GLOB option is set, then a
@, , +, ? or ! immediately preceding the ( is treated specially, as detailed below. The
option SH_GLOB prevents bare parentheses from being used in this way, though the
KSH_GLOB option is still available.
Note that grouping cannot extend over multiple directories: it is an error to have a / within a
group (this only applies for patterns used in filename generation). There is one exception: a group
of the form (pat/)# appearing as a complete path segment can match a sequence of directories. For
example, foo/(a/)#bar matches foo/bar, foo/any/bar, foo/any/anyother/bar, and so on.

xy

Matches either x or y. This operator has lower precedence than any other. The character must
be within parentheses, to avoid interpretation as a pipeline.

(Requires EXTENDED_GLOB to be set.) Matches anything except the pattern x. This has a
higher precedence than /, so foo/bar will search directories in . except ./foo for a file named
bar.

xy

(Requires EXTENDED_GLOB to be set.) Match anything that matches the pattern x but does
not match y. This has lower precedence than any operator except , so /foo/bar will search
for all files in all directories in . and then exclude foo/bar if there was such a match. Multiple
patterns can be excluded by foobarbaz. In the exclusion pattern (y), / and . are not treated
specially the way they usually are in globbing.

x#

(Requires EXTENDED_GLOB to be set.) Matches zero or more occurrences of the pattern x.


This operator has high precedence; 12# is equivalent to 1(2#), rather than (12)#. It is an error
for an unquoted # to follow something which cannot be repeated; this includes an empty string, a
pattern already followed by ##, or parentheses when part of a KSH_GLOB pattern (for example,
!(foo)# is invalid and must be replaced by (!(foo))).

x##

(Requires EXTENDED_GLOB to be set.) Matches one or more occurrences of the pattern x.


This operator has high precedence; 12## is equivalent to 1(2##), rather than (12)##. No more
than two active # characters may appear together.

kshlike Glob Operators

If the KSH_GLOB option is set, the effects of parentheses can be modified by a preceding @, , +, ?
or !. This character need not be unquoted to have special effects, but the ( must be.
@(...)

Match the pattern in the parentheses. (Like (...).)

(...)

Match any number of occurrences. (Like (...)#.)

+(...)

Match at least one occurrence. (Like (...)##.)

?(...)

Match zero or one occurrence. (Like (...).)

!(...)

Match anything but the expression in parentheses. (Like ((...)).)

Precedence

The precedence of the operators given above is (highest) , /, , (lowest); the remaining operators are
simply treated from left to right as part of a string, with # and ## applying to the shortest possible
preceding unit (i.e. a character, ?, [...], <...>, or a parenthesised expression). As mentioned above, a /
used as a directory separator may not appear inside parentheses, while a must do so; in patterns used in
other contexts than filename generation (for example, in case statements and tests within [[...]]), a / is
not special; and / is also not special after a appearing outside parentheses in a filename pattern.

zsh 4.0.4

Last change: October 26, 2001

13

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

Globbing Flags

There are various flags which affect any text to their right up to the end of the enclosing group or to the end
of the pattern; they require the EXTENDED_GLOB option. All take the form (#X) where X may have one
of the following forms:
i

Case insensitive: upper or lower case characters in the pattern match upper or lower case characters.

Lower case characters in the pattern match upper or lower case characters; upper case characters in
the pattern still only match upper case characters.

Case sensitive: locally negates the effect of i or l from that point on.

Activate backreferences for parenthesised groups in the pattern; this does not work in filename
generation. When a pattern with a set of active parentheses is matched, the strings matched by the
groups are stored in the array $match, the indices of the beginning of the matched parentheses in
the array $mbegin, and the indices of the end in the array $mend, with the first element of each
array corresponding to the first parenthesised group, and so on. These arrays are not otherwise
special to the shell. The indices use the same convention as does parameter substitution, so that
elements of $mend and $mbegin may be used in subscripts; the KSH_ARRAYS option is
respected. Sets of globbing flags are not considered parenthesised groups; only the first nine
active parentheses can be referenced.
For example,
foo=" a string with a message"
if [[ $foo = (aan) (#b)() ]]; then
print ${foo[$mbegin[1],$mend[1]]}
fi
prints string with a. Note that the first parenthesis is before the (#b) and does not create a
backreference.
Backreferences work with all forms of pattern matching other than filename generation, but note
that when performing matches on an entire array, such as ${array#pattern}, or a global substitution, such as ${param//pat/repl}, only the data for the last match remains available. In the case of
global replacements this may still be useful. See the example for the m flag below.
The numbering of backreferences strictly follows the order of the opening parentheses from left to
right in the pattern string, although sets of parentheses may be nested. There are special rules for
parentheses followed by # or ##. Only the last match of the parenthesis is remembered: for
example, in [[ abab = (#b)([ab])# ]], only the final b is stored in match[1]. Thus extra
parentheses may be necessary to match the complete segment: for example, use X((abcd)#)Y to
match a whole string of either ab or cd between X and Y, using the value of $match[1]
rather than $match[2].
If the match fails none of the parameters is altered, so in some cases it may be necessary to initialise them beforehand. If some of the backreferences fail to match which happens if they are in
an alternate branch which fails to match, or if they are followed by # and matched zero times
then the matched string is set to the empty string, and the start and end indices are set to 1.
Pattern matching with backreferences is slightly slower than without.

zsh 4.0.4

Deactivate backreferences, negating the effect of the b flag from that point on.

Set references to the match data for the entire string matched; this is similar to backreferencing and
does not work in filename generation. The flag must be in effect at the end of the pattern, i.e. not
local to a group. The parameters $MATCH, $MBEGIN and $MEND will be set to the string
matched and to the indices of the beginning and end of the string, respectively. This is most useful
in parameter substitutions, as otherwise the string matched is obvious.

Last change: October 26, 2001

14

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

For example,
arr=(veldt jynx grimps waqf zho buck)
print ${arr//(#m)[aeiou]/${(U)MATCH}}
forces all the matches (i.e. all vowels) into uppercase, printing vEldt jynx grImps wAqf zhO
bUck.
Unlike backreferences, there is no speed penalty for using match references, other than the extra
substitutions required for the replacement strings in cases such as the example shown.
M

Deactivate the m flag, hence no references to match data will be created.

anum

Approximate matching: num errors are allowed in the string matched by the pattern. The rules for
this are described in the next subsection.

s, e

Unlike the other flags, these have only a local effect, and each must appear on its own: (#s) and
(#e) are the only valid forms. The (#s) flag succeeds only at the start of the test string, and the
(#e) flag succeeds only at the end of the test string; they correspond to and $ in standard regular expressions. They are useful for matching path segments in patterns other than those in
filename generation (where path segments are in any case treated separately). For example,
((#s)/)test((#e)/) matches a path segment test in any of the following strings: test,
test/at/start, at/end/test, in/test/middle.
Another use is in parameter substitution; for example ${array/(#s)AZ(#e)} will remove only
elements of an array which match the complete pattern AZ. There are other ways of performing many operations of this type, however the combination of the substitution operations / and
// with the (#s) and (#e) flags provides a single simple and memorable method.
Note that assertions of the form ((#s)) also work, i.e. match anywhere except at the start of the
string, although this actually means anything except a zerolength portion at the start of the
string; you need to use (" " (#s)) to match a zerolength portion of the string not at the start.

For example, the test string fooxx can be matched by the pattern (#i)FOOXX, but not by (#l)FOOXX,
(#i)FOO(#I)XX or ((#i)FOOX)X. The string (#ia2)readme specifies caseinsensitive matching of
readme with up to two errors.
When using the ksh syntax for grouping both KSH_GLOB and EXTENDED_GLOB must be set and the
left parenthesis should be preceded by @. Note also that the flags do not affect letters inside [...] groups, in
other words (#i)[az] still matches only lowercase letters. Finally, note that when examining whole paths
caseinsensitively every directory must be searched for all files which match, so that a pattern of the form
(#i)/foo/bar/... is potentially slow.
Approximate Matching

When matching approximately, the shell keeps a count of the errors found, which cannot exceed the
number specified in the (#anum) flags. Four types of error are recognised:
1.

Different characters, as in fooxbar and fooybar.

2.

Transposition of characters, as in banana and abnana.

3.

A character missing in the target string, as with the pattern road and target string rod.

4.

An extra character appearing in the target string, as with stove and strove.

Thus, the pattern (#a3)abcd matches dcba, with the errors occurring by using the first rule twice and the
second once, grouping the string as [d][cb][a] and [a][bc][d].
Nonliteral parts of the pattern must match exactly, including characters in character ranges: hence
(#a1)??? matches strings of length four, by applying rule 4 to an empty part of the pattern, but not strings
of length two, since all the ? must match. Other characters which must match exactly are initial dots in
filenames (unless the GLOB_DOTS option is set), and all slashes in filenames, so that a/bc is two errors
from ab/c (the slash cannot be transposed with another character). Similarly, errors are counted separately
for noncontiguous strings in the pattern, so that (abcd)ef is two errors from aebf.

zsh 4.0.4

Last change: October 26, 2001

15

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

When using exclusion via the operator, approximate matching is treated entirely separately for the
excluded part and must be activated separately. Thus, (#a1)READMEREAD_ME matches READ.ME
but not READ_ME, as the trailing READ_ME is matched without approximation. However,
(#a1)README(#a1)READ_ME does not match any pattern of the form READ?ME as all such forms
are now excluded.
Apart from exclusions, there is only one overall error count; however, the maximum errors allowed may be
altered locally, and this can be delimited by grouping. For example, (#a1)cat((#a0)dog)fox allows one
error in total, which may not occur in the dog section, and the pattern (#a1)cat(#a0)dog(#a1)fox is
equivalent. Note that the point at which an error is first found is the crucial one for establishing whether to
use approximation; for example, (#a1)abc(#a0)xyz will not match abcdxyz, because the error occurs at the
x, where approximation is turned off.
Entire path segments may be matched approximately, so that (#a1)/foo/d/is/available/at/the/bar allows
one error in any path segment. This is much less efficient than without the (#a1), however, since every
directory in the path must be scanned for a possible approximate match. It is best to place the (#a1) after
any path segments which are known to be correct.
Recursive Globbing

A pathname component of the form (foo/)# matches a path consisting of zero or more directories matching the pattern foo.
As a shorthand, / is equivalent to (/)#; note that this therefore matches files in the current directory as
well as subdirectories. Thus:
ls (/)#bar
or
ls /bar
does a recursive directory search for files named bar (potentially including the file bar in the current
directory). This form does not follow symbolic links; the alternative form / does, but is otherwise
identical. Neither of these can be combined with other forms of globbing within the same path segment; in
that case, the operators revert to their usual effect.
Glob Qualifiers

Patterns used for filename generation may end in a list of qualifiers enclosed in parentheses. The qualifiers
specify which filenames that otherwise match the given pattern will be inserted in the argument list.
If the option BARE_GLOB_QUAL is set, then a trailing set of parentheses containing no or ( characters (or if it is special) is taken as a set of glob qualifiers. A glob subexpression that would normally be
taken as glob qualifiers, for example (x), can be forced to be treated as part of the glob pattern by doubling the parentheses, in this case producing ((x)).
A qualifier may be any one of the following:

zsh 4.0.4

directories

plain files

symbolic links

sockets

named pipes (FIFOs)

executable plain files (0100)

device files (character or block special)

%b

block special files

%c

character special files

ownerreadable files (0400)

Last change: October 26, 2001

16

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

ownerwritable files (0200)

ownerexecutable files (0100)

groupreadable files (0040)

groupwritable files (0020)

groupexecutable files (0010)

worldreadable files (0004)

worldwritable files (0002)

worldexecutable files (0001)

setuid files (04000)

setgid files (02000)

files with the sticky bit (01000)

fspec

files with access rights matching spec. This spec may be a octal number optionally preceded by a
=, a +, or a . If none of these characters is given, the behavior is the same as for =. The
octal number describes the mode bits to be expected, if combined with a =, the value given must
match the filemodes exactly, with a +, at least the bits in the given number must be set in the
filemodes, and with a , the bits in the number must not be set. Giving a ? instead of a octal
digit anywhere in the number ensures that the corresponding bits in the filemodes are not
checked, this is only useful in combination with =.
If the qualifier f is followed by any other character anything up to the next matching character
([, {, and < match ], }, and > respectively, any other character matches itself) is taken as a
list of commaseparated subspecs. Each subspec may be either a octal number as described
above or a list of any of the characters u, g, o, and a, followed by a =, a +, or a , followed by a list of any of the characters r, w, x, s, and t, or a octal digit. The first list of
characters specify which access rights are to be checked. If a u is given, those for the owner of
the file are used, if a g is given, those of the group are checked, a o means to test those of other
users, and the a says to test all three groups. The =, +, and again says how the modes are
to be checked and have the same meaning as described for the first form above. The second list of
characters finally says which access rights are to be expected: r for read access, w for write
access, x for the right to execute the file (or to search a directory), s for the setuid and setgid
bits, and t for the sticky bit.
Thus, (f70?) gives the files for which the owner has read, write, and execute permission, and for
which other group members have no rights, independent of the permissions for other users. The
pattern (f100) gives all files for which the owner does not have execute permission, and
(f:gu+w,orx:) gives the files for which the owner and the other members of the group have at
least write permission, and for which other users dont have read or execute permission.

estring The string will be executed as shell code. The filename will be included in the list if and only if
the code returns a zero status (usually the status of the last command). The first character after the
e will be used as a separator and anything up to the next matching separator will be taken as the
string; [, {, and < match ], }, and >, respectively, while any other character matches
itself. Note that expansions must be quoted in the string to prevent them from being expanded
before globbing is done.
During the execution of string the filename currently being tested is available in the parameter
REPLY; the parameter may be altered to a string to be inserted into the list instead of the original
filename. In addition, the parameter reply may be set to an array or a string, which overrides the
value of REPLY. If set to an array, the latter is inserted into the command line word by word.

zsh 4.0.4

Last change: October 26, 2001

17

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHEXPN ( 1 )

For example, suppose a directory contains a single file lonely. Then the expression
(e:reply=(${REPLY}{1,2}):) will cause the words lonely1 lonely2 to be inserted into the
command line. Note the quotation marks.
ddev

files on the device dev

l[+]ct files having a link count less than ct (), greater than ct (+), or equal to ct
U

files owned by the effective user ID

files owned by the effective group ID

uid

files owned by user ID id if it is a number, if not, than the character after the u will be used as a
separator and the string between it and the next matching separator ([, {, and < match ], },
and > respectively, any other character matches itself) will be taken as a user name, and the user
ID of this user will be taken (e.g. u:foo: or u[foo] for user foo)

gid

like uid but with group IDs or names

a[Mwhms][+]n
files accessed exactly n days ago. Files accessed within the last n days are selected using a negative value for n (n). Files accessed more than n days ago are selected by a positive n value (+n).
Optional unit specifiers M, w, h, m or s (e.g. ah5) cause the check to be performed with
months (of 30 days), weeks, hours, minutes or seconds instead of days, respectively. For instance,
echo (ah5) would echo files accessed within the last five hours.
m[Mwhms][+]n
like the file access qualifier, except that it uses the file modification time.
c[Mwhms][+]n
like the file access qualifier, except that it uses the file inode change time.
L[+]n files less than n bytes (), more than n bytes (+), or exactly n bytes in length. If this flag is directly
followed by a k (K), m (M), or p (P) (e.g. Lk50) the check is performed with kilobytes, megabytes, or blocks (of 512 bytes) instead.

zsh 4.0.4

negates all qualifiers following it

toggles between making the qualifiers work on symbolic links (the default) and the files they point
to

sets the MARK_DIRS option for the current pattern

appends a trailing qualifier mark to the filenames, analogous to the LIST_TYPES option, for the
current pattern (overrides M)

sets the NULL_GLOB option for the current pattern

sets the GLOB_DOTS option for the current pattern

sets the NUMERIC_GLOB_SORT option for the current pattern

oc

specifies how the names of the files should be sorted. If c is n they are sorted by name (the
default); if it is L they are sorted depending on the size (length) of the files; if l they are sorted by
the number of links; if a, m, or c they are sorted by the time of the last access, modification, or
inode change respectively; if d, files in subdirectories appear before those in the current directory
at each level of the search this is best combined with other criteria, for example odon to sort
on names for files within the same directory. Note that a, m, and c compare the age against the
current time, hence the first name in the list is the youngest file. Also note that the modifiers and
are used, so (oL) gives a list of all files sorted by file size in descending order, following
any symbolic links.

Oc

like o, but sorts in descending order; i.e. (oc) is the same as (Oc) and (Oc) is the same
as (oc); Od puts files in the current directory before those in subdirectories at each level of the
search.

Last change: October 26, 2001

18

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHEXPN ( 1 )

[beg[,end]]
specifies which of the matched filenames should be included in the returned list. The syntax is the
same as for array subscripts. beg and the optional end may be mathematical expressions. As in
parameter subscripting they may be negative to make them count from the last match backward.
E.g.: (OL[1,3]) gives a list of the names of the three largest files.
More than one of these lists can be combined, separated by commas. The whole list matches if at least one
of the sublists matches (they are ored, the qualifiers in the sublists are anded). Some qualifiers, however, affect all matches generated, independent of the sublist in which they are given. These are the
qualifiers M, T, N, D, n, o, O and the subscripts given in brackets ([...]).
If a : appears in a qualifier list, the remainder of the expression in parenthesis is interpreted as a modifier
(see the section Modifiers in the section History Expansion). Note that each modifier must be introduced by a separate :. Note also that the result after modification does not have to be an existing file. The
name of any existing file can be followed by a modifier of the form (:..) even if no actual filename generation is performed. Thus:
ls (/)
lists all directories and symbolic links that point to directories, and
ls (%W)
lists all worldwritable device files in the current directory, and
ls (W,X)
lists all files in the current directory that are worldwritable or worldexecutable, and
echo /tmp/foo(u0@:t)
outputs the basename of all rootowned files beginning with the string foo in /tmp, ignoring symlinks,
and
ls .(lexparse).[ch](Dl1)
lists all files having a link count of one whose names contain a dot (but not those starting with a dot, since
GLOB_DOTS is explicitly switched off) except for lex.c, lex.h, parse.c and parse.h.

zsh 4.0.4

Last change: October 26, 2001

19

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHPARAM ( 1 )

NAME

zshparam zsh parameters


DESCRIPTION

A parameter has a name, a value, and a number of attributes. A name may be any sequence of
alphanumeric characters and underscores, or the single characters , @, #, ?, , $, or !. The
value may be a scalar (a string), an integer, an array (indexed numerically), or an associative array (an
unordered set of namevalue pairs, indexed by name). To declare the type of a parameter, or to assign a
scalar or integer value to a parameter, use the typeset builtin.
The value of a scalar or integer parameter may also be assigned by writing:
name=value
If the integer attribute, i, is set for name, the value is subject to arithmetic evaluation. See the section
Array Parameters for additional forms of assignment.
To refer to the value of a parameter, write $name or ${name}. See Parameter Expansion in zshexpn(1)
for complete details.
In the parameter lists that follow, the mark <S> indicates that the parameter is special. Special parameters
cannot have their type changed, and they stay special even if unset. <Z> indicates that the parameter does
not exist when the shell initializes in sh or ksh emulation mode.
ARRAY PARAMETERS

To assign an array value, write one of:


set A name value ...
name=(value ...)
If no parameter name exists, an ordinary array parameter is created. If the parameter name exists and is a
scalar, it is replaced by a new array. Ordinary array parameters may also be explicitly declared with:
typeset a name
Associative arrays must be declared before assignment, by using:
typeset A name
When name refers to an associative array, the list in an assignment is interpreted as alternating keys and
values:
set A name key value ...
name=(key value ...)
Every key must have a value in this case. Note that this assigns to the entire array, deleting any elements
that do not appear in the list.
To create an empty array (including associative arrays), use one of:
set A name
name=()
Array Subscripts

Individual elements of an array may be selected using a subscript. A subscript of the form [exp] selects
the single element exp, where exp is an arithmetic expression which will be subject to arithmetic expansion
as if it were surrounded by $((...)). The elements are numbered beginning with 1, unless the
KSH_ARRAYS option is set in which case they are numbered from zero.
Subscripts may be used inside braces used to delimit a parameter name, thus ${foo[2]} is equivalent to
$foo[2]. If the KSH_ARRAYS option is set, the braced form is the only one that works, as bracketed
expressions otherwise are not treated as subscripts.
The same subscripting syntax is used for associative arrays, except that no arithmetic expansion is applied
to exp. However, the parsing rules for arithmetic expressions still apply, which affects the way that certain

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHPARAM ( 1 )

special characters must be protected from interpretation. See Subscript Parsing below for details.
A subscript of the form [] or [@] evaluates to all elements of an array; there is no difference between
the two except when they appear within double quotes. " $foo[]" evaluates to " $foo[1] $foo[2] ..." ,
whereas " $foo[@]" evaluates to " $foo[1]" " $foo[2]" .... For associative arrays, [] or [@] evaluate
to all the values (not the keys, but see Subscript Flags below), in no particular order. When an array
parameter is referenced as $name (with no subscript) it evaluates to $name[], unless the
KSH_ARRAYS option is set in which case it evaluates to ${name[0]} (for an associative array, this
means the value of the key 0, which may not exist even if there are values for other keys).
A subscript of the form [exp1,exp2] selects all elements in the range exp1 to exp2, inclusive. (Associative
arrays are unordered, and so do not support ranges.) If one of the subscripts evaluates to a negative number,
say n, then the nth element from the end of the array is used. Thus $foo[3] is the third element from the
end of the array foo, and $foo[1,1] is the same as $foo[].
Subscripting may also be performed on nonarray values, in which case the subscripts specify a substring
to be extracted. For example, if FOO is set to foobar, then echo $FOO[2,5] prints ooba.
Array Element Assignment

A subscript may be used on the left side of an assignment like so:


name[exp]=value
In this form of assignment the element or range specified by exp is replaced by the expression on the right
side. An array (but not an associative array) may be created by assignment to a range or element. Arrays
do not nest, so assigning a parenthesized list of values to an element or range changes the number of elements in the array, shifting the other elements to accommodate the new values. (This is not supported for
associative arrays.)
This syntax also works as an argument to the typeset command:
typeset " name[exp]" =value
The value may not be a parenthesized list in this case; only singleelement assignments may be made with
typeset. Note that quotes are necessary in this case to prevent the brackets from being interpreted as
filename generation operators. The noglob precommand modifier could be used instead.
To delete an element of an ordinary array, assign () to that element. To delete an element of an associative array, use the unset command:
unset " name[exp]"
Subscript Flags

If the opening bracket, or the comma in a range, in any subscript expression is directly followed by an
opening parenthesis, the string up to the matching closing one is considered to be a list of flags, as in
name[(flags)exp]. The flags currently understood are:
w

If the parameter subscripted is a scalar than this flag makes subscripting work on words instead of
characters. The default word separator is whitespace.

s:string:
This gives the string that separates words (for use with the w flag).

zsh 4.0.4

Recognize the same escape sequences as the print builtin in the string argument of a subsequent
s flag.

If the parameter subscripted is a scalar than this flag makes subscripting work on lines instead of
characters, i.e. with elements separated by newlines. This is a shorthand for pws:\n:.

Reverse subscripting: if this flag is given, the exp is taken as a pattern and the result is the first
matching array element, substring or word (if the parameter is an array, if it is a scalar, or if it is a
scalar and the w flag is given, respectively). The subscript used is the number of the matching
element, so that pairs of subscripts such as $foo[(r)??,3] and $foo[(r)??,(r)f] are possible. If
the parameter is an associative array, only the value part of each pair is compared to the pattern,

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHPARAM ( 1 )

and the result is that value. Reverse subscripts may be used for assigning to ordinary array elements, but not for assigning to associative arrays.
R

Like r, but gives the last match. For associative arrays, gives all possible matches.

Like r, but gives the index of the match instead; this may not be combined with a second argument. On the left side of an assignment, behaves like r. For associative arrays, the key part of
each pair is compared to the pattern, and the first matching key found is the result.

Like i, but gives the index of the last match, or all possible matching keys in an associative array.

If used in a subscript on an associative array, this flag causes the keys to be interpreted as patterns,
and returns the value for the first key found where exp is matched by the key. This flag does not
work on the left side of an assignment to an associative array element. If used on another type of
parameter, this behaves like r.

On an associative array this is like k but returns all values where exp is matched by the keys. On
other types of parameters this has the same effect as R.

n:expr: If combined with r, R, i or I, makes them give the nth or nth last match (if expr evaluates to
n). This flag is ignored when the array is associative.
b:expr: If combined with r, R, i or I, makes them begin at the nth or nth last element, word, or character (if expr evaluates to n). This flag is ignored when the array is associative.
e

This flag has no effect and for ordinary arrays is retained for backward compatibility only. For
associative arrays, this flag can be used to force or @ to be interpreted as a single key rather than
as a reference to all values. This flag may be used on the left side of an assignment.

See Parameter Expansion Flags (zshexpn(1)) for additional ways to manipulate the results of array subscripting.
Subscript Parsing

This discussion applies mainly to associative array key strings and to patterns used for reverse subscripting
(the r, R, i, etc. flags), but it may also affect parameter substitutions that appear as part of an arithmetic
expression in an ordinary subscript.
The basic rule to remember when writing a subscript expression is that all text between the opening [ and
the closing ] is interpreted as if it were in double quotes (see zshmisc(1)). However, unlike double quotes
which normally cannot nest, subscript expressions may appear inside doublequoted strings or inside other
subscript expressions (or both!), so the rules have two important differences.
The first difference is that brackets ([ and ]) must appear as balanced pairs in a subscript expression
unless they are preceded by a backslash (\). Therefore, within a subscript expression (and unlike true
doublequoting) the sequence \[ becomes [, and similarly \] becomes ]. This applies even in cases
where a backslash is not normally required; for example, the pattern [[] (to match any character other
than an open bracket) should be written [\[] in a reversesubscript pattern. However, note that \[\[\]
and even \[[] mean the same thing, because backslashes are always stripped when they appear before
brackets!
The same rule applies to parentheses (( and )) and braces ({ and }): they must appear either in balanced pairs or preceded by a backslash, and backslashes that protect parentheses or braces are removed during parsing. This is because parameter expansions may be surrounded balanced braces, and subscript flags
are introduced by balanced parenthesis.
The second difference is that a doublequote (" ) may appear as part of a subscript expression without
being preceded by a backslash, and therefore that the two characters \" remain as two characters in the
subscript (in true doublequoting, \" becomes " ). However, because of the standard shell quoting rules,
any doublequotes that appear must occur in balanced pairs unless preceded by a backslash. This makes it
more difficult to write a subscript expression that contains an odd number of doublequote characters, but
the reason for this difference is so that when a subscript expression appears inside true doublequotes, one
can still write \" (rather than \\\" ) for " .

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHPARAM ( 1 )

To use an odd number of double quotes as a key in an assignment, use the typeset builtin and an enclosing
pair of double quotes; to refer to the value of that key, again use double quotes:
typeset A aa
typeset " aa[one\" two\" three\" quotes]" =QQQ
print " $aa[one\" two\" three\" quotes]"
It is important to note that the quoting rules do not change when a parameter expansion with a subscript is
nested inside another subscript expression. That is, it is not necessary to use additional backslashes within
the inner subscript expression; they are removed only once, from the innermost subscript outwards. Parameters are also expanded from the innermost subscript first, as each expansion is encountered left to right in
the outer expression.
A further complication arises from a way in which subscript parsing is not different from double quote parsing. As in true doublequoting, the sequences \, and \@ remain as two characters when they appear in
a subscript expression. To use a literal or @ as an associative array key, the e flag must be used:
typeset A aa
aa[(e)]=star
print $aa[(e)]
A last detail must be considered when reverse subscripting is performed. Parameters appearing in the subscript expression are first expanded and then the complete expression is interpreted as a pattern. This has
two effects: first, parameters behave as if GLOB_SUBST were on (and it cannot be turned off); second,
backslashes are interpreted twice, once when parsing the array subscript and again when parsing the pattern.
In a reverse subscript, its necessary to use four backslashes to cause a single backslash to match literally in
the pattern. For complex patterns, it is often easiest to assign the desired pattern to a parameter and then
refer to that parameter in the subscript, because then the backslashes, brackets, parentheses, etc., are seen
only when the complete expression is converted to a pattern. To match the value of a parameter literally in
a reverse subscript, rather than as a pattern, use ${(q)name} (see zshexpn(1)) to quote the expanded value.
Note that the k and K flags are reverse subscripting for an ordinary array, but are not reverse subscripting for an associative array! (For an associative array, the keys in the array itself are interpreted as patterns
by those flags; the subscript is a plain string in that case.)
One final note, not directly related to subscripting: the numeric names of positional parameters (described
below) are parsed specially, so for example $2foo is equivalent to ${2}foo. Therefore, to use subscript
syntax to extract a substring from a positional parameter, the expansion must be surrounded by braces; for
example, ${2[3,5]} evaluates to the third through fifth characters of the second positional parameter, but
$2[3,5] is the entire second parameter concatenated with the filename generation pattern [3,5].
POSITIONAL PARAMETERS

The positional parameters provide access to the commandline arguments of a shell function, shell script,
or the shell itself; see the section Invocation, and also the section Functions. The parameter n, where n
is a number, is the nth positional parameter. The parameters , @ and argv are arrays containing all the
positional parameters; thus $argv[n], etc., is equivalent to simply $n.
Positional parameters may be changed after the shell or function starts by using the set builtin, by assigning
to the argv array, or by direct assignment of the form n=value where n is the number of the positional
parameter to be changed. This also creates (with empty values) any of the positions from 1 to n that do not
already have values. Note that, because the positional parameters form an array, an array assignment of the
form n=(value ...) is allowed, and has the effect of shifting all the values at positions greater than n by as
many positions as necessary to accommodate the new values.
LOCAL PARAMETERS

Shell function executions delimit scopes for shell parameters. (Parameters are dynamically scoped.) The
typeset builtin, and its alternative forms declare, integer, local and readonly (but not export), can be used
to declare a parameter as being local to the innermost scope.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHPARAM ( 1 )

When a parameter is read or assigned to, the innermost existing parameter of that name is used. (That is,
the local parameter hides any lesslocal parameter.) However, assigning to a nonexistent parameter, or
declaring a new parameter with export, causes it to be created in the outermost scope.
Local parameters disappear when their scope ends. unset can be used to delete a parameter while it is still
in scope; any outer parameter of the same name remains hidden.
Special parameters may also be made local; they retain their special attributes unless either the existing or
the newlycreated parameter has the h (hide) attribute. This may have unexpected effects: there is no
default value, so if there is no assignment at the point the variable is made local, it will be set to an empty
value (or zero in the case of integers). The following:
typeset PATH=/new/directory:$PATH
is valid for temporarily allowing the shell or programmes called from it to find the programs in
/new/directory inside a function.
Note that the restriction in older versions of zsh that local parameters were never exported has been
removed.
PARAMETERS SET BY THE SHELL

The following parameters are automatically set by the shell:


! <S>

The process ID of the last background command invoked.

# <S>

The number of positional parameters in decimal. Note that some confusion may occur with the
syntax $#param which substitutes the length of param. Use ${#} to resolve ambiguities. In particular, the sequence $#... in an arithmetic expression is interpreted as the length of the parameter , q.v.

ARGC <S> <Z>


Same as #.
$ <S>

The process ID of this shell.

<S>

Flags supplied to the shell on invocation or by the set or setopt commands.

<S>

An array containing the positional parameters.

argv <S> <Z>


Same as . Assigning to argv changes the local positional parameters, but argv is not itself a local
parameter. Deleting argv with unset in any function deletes it everywhere, although only the
innermost positional parameter array is deleted (so and @ in other scopes are not affected).
@ <S> Same as argv[@], even when argv is not set.
? <S>

The exit value returned by the last command.

0 <S>

The name used to invoke the current shell. If the FUNCTION_ARGZERO option is set, this is
set temporarily within a shell function to the name of the function, and within a sourced script to
the name of the script.

status <S> <Z>


Same as ?.
pipestatus <S> <Z>
An array containing the exit values returned by all commands in the last pipeline.
_ <S>

The last argument of the previous command. Also, this parameter is set in the environment of
every command executed to the full pathname of the command.

CPUTYPE
The machine type (microprocessor class or machine model), as determined at run time.
EGID <S>
The effective group ID of the shell process. If you have sufficient privileges, you may change the

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHPARAM ( 1 )

effective group ID of the shell process by assigning to this parameter. Also (assuming sufficient
privileges), you may start a single command with a different effective group ID by (EGID=gid;
command)
EUID <S>
The effective user ID of the shell process. If you have sufficient privileges, you may change the
effective user ID of the shell process by assigning to this parameter. Also (assuming sufficient
privileges), you may start a single command with a different effective user ID by (EUID=uid;
command)
ERRNO <S>
The value of errno (see errno(3)) as set by the most recently failed system call. This value is system dependent and is intended for debugging purposes.
GID <S>
The real group ID of the shell process. If you have sufficient privileges, you may change the group
ID of the shell process by assigning to this parameter. Also (assuming sufficient privileges), you
may start a single command under a different group ID by (GID=gid; command)
HOST The current hostname.
LINENO <S>
The line number of the current line within the current script, sourced file, or shell function being
executed, whichever was started most recently. Note that in the case of shell functions the line
number refers to the function as it appeared in the original definition, not necessarily as displayed
by the functions builtin.
LOGNAME
If the corresponding variable is not set in the environment of the shell, it is initialized to the login
name corresponding to the current login session. This parameter is exported by default but this can
be disabled using the typeset builtin.
MACHTYPE
The machine type (microprocessor class or machine model), as determined at compile time.
OLDPWD
The previous working directory. This is set when the shell initializes and whenever the directory
changes.
OPTARG <S>
The value of the last option argument processed by the getopts command.
OPTIND <S>
The index of the last option argument processed by the getopts command.
OSTYPE
The operating system, as determined at compile time.
PPID <S>
The process ID of the parent of the shell.
PWD

The present working directory. This is set when the shell initializes and whenever the directory
changes.

RANDOM <S>
A random integer from 0 to 32767, newly generated each time this parameter is referenced. The
random number generator can be seeded by assigning a numeric value to RANDOM.
SECONDS <S>
The number of seconds since shell invocation. If this parameter is assigned a value, then the value
returned upon reference will be the value that was assigned plus the number of seconds since the
assignment.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHPARAM ( 1 )

SHLVL <S>
Incremented by one each time a new shell is started.
signals An array containing the names of the signals.
TTY

The name of the tty associated with the shell, if any.

TTYIDLE <S>
The idle time of the tty associated with the shell in seconds or 1 if there is no such tty.
UID <S>
The real user ID of the shell process. If you have sufficient privileges, you may change the user ID
of the shell by assigning to this parameter. Also (assuming sufficient privileges), you may start a
single command under a different user ID by (UID=uid; command)
USERNAME <S>
The username corresponding to the real user ID of the shell process. If you have sufficient
privileges, you may change the username (and also the user ID and group ID) of the shell by
assigning to this parameter. Also (assuming sufficient privileges), you may start a single command under a different username (and user ID and group ID) by (USERNAME=username; command)
VENDOR
The vendor, as determined at compile time.
ZSH_NAME
Expands to the basename of the command used to invoke this instance of zsh.
ZSH_VERSION
The version number of this zsh.
PARAMETERS USED BY THE SHELL

The following parameters are used by the shell.


In cases where there are two parameters with an upper and lowercase form of the same name, such as path
and PATH, the lowercase form is an array and the uppercase form is a scalar with the elements of the array
joined together by colons. These are similar to tied parameters created via typeset T. The normal use
for the colonseparated form is for exporting to the environment, while the array form is easier to manipulate within the shell. Note that unsetting either of the pair will unset the other; they retain their special properties when recreated, and recreating one of the pair will recreate the other.
ARGV0
If exported, its value is used as the argv[0] of external commands. Usually used in constructs like
ARGV0=emacs nethack.
BAUD The baud rate of the current connection. Used by the line editor update mechanism to compensate
for a slow terminal by delaying updates until necessary. This may be profitably set to a lower
value in some circumstances, e.g. for slow modems dialing into a communications server which is
connected to a host via a fast link; in this case, this variable would be set by default to the speed of
the fast link, and not the modem. This parameter should be set to the baud rate of the slowest part
of the link for best performance. The compensation mechanism can be turned off by setting the
variable to zero.
cdpath <S> <Z> (CDPATH <S>)
An array (colonseparated list) of directories specifying the search path for the cd command.
COLUMNS <S>
The number of columns for this terminal session. Used for printing select lists and for the line editor.
DIRSTACKSIZE
The maximum size of the directory stack. If the stack gets larger than this, it will be truncated

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHPARAM ( 1 )

automatically. This is useful with the AUTO_PUSHD option.


FCEDIT
The default editor for the fc builtin.
fignore <S> <Z> (FIGNORE <S>)
An array (colon separated list) containing the suffixes of files to be ignored during filename completion. However, if the completion generates only files which would match if this variable would
be ignored, than these files are completed anyway.
fpath <S> <Z> (FPATH <S>)
An array (colon separated list) of directories specifying the search path for function definitions.
This path is searched when a function with the u attribute is referenced. If an executable file is
found, then it is read and executed in the current environment.
histchars <S>
Three characters used by the shells history and lexical analysis mechanism. The first character
signals the start of a history expansion (default !). The second character signals the start of a
quick history substitution (default ). The third character is the comment character (default #).
HISTCHARS <S> <Z>
Same as histchars. (Deprecated.)
HISTFILE
The file to save the history in when an interactive shell exits. If unset, the history is not saved.
HISTSIZE <S>
The maximum number of events stored in the internal history list. If you use the
HIST_EXPIRE_DUPS_FIRST option, setting this value larger than the SAVEHIST size will
give you the difference as a cushion for saving duplicated history events.
HOME <S>
The default argument for the cd command.
IFS <S>
Internal field separators (by default space, tab, newline and NUL), that are used to separate words
which result from command or parameter expansion and words read by the read builtin. Any
characters from the set space, tab and newline that appear in the IFS are called IFS white space.
One or more IFS white space characters or one nonIFS white space character together with any
adjacent IFS white space character delimit a field. If an IFS white space character appears twice
consecutively in the IFS, this character is treated as if it were not an IFS white space character.
KEYTIMEOUT
The time the shell waits, in hundredths of seconds, for another key to be pressed when reading
bound multicharacter sequences.
LANG <S>
This variable determines the locale category for any category not specifically selected via a variable starting with LC_.
LC_ALL <S>
This variable overrides the value of the LANG variable and the value of any of the other variables starting with LC_.
LC_COLLATE <S>
This variable determines the locale category for character collation information within ranges in
glob brackets and for sorting.
LC_CTYPE <S>
This variable determines the locale category for character handling functions.
LC_MESSAGES <S>

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHPARAM ( 1 )

This variable determines the language in which messages should be written. Note that zsh does
not use message catalogs.
LC_NUMERIC <S>
This variable affects the decimal point character and thousands separator character for the formatted input/output functions and string conversion functions. Note that zsh ignores this setting when
parsing floating point mathematical expressions.
LC_TIME <S>
This variable determines the locale category for date and time formatting in prompt escape
sequences.
LINES <S>
The number of lines for this terminal session. Used for printing select lists and for the line editor.
LISTMAX
In the line editor, the number of matches to list without asking first. If the value is negative, the list
will be shown if it spans at most as many lines as given by the absolute value. If set to zero, the
shell asks only if the top of the listing would scroll off the screen.
LOGCHECK
The interval in seconds between checks for login/logout activity using the watch parameter.
MAIL If this parameter is set and mailpath is not set, the shell looks for mail in the specified file.
MAILCHECK
The interval in seconds between checks for new mail.
mailpath <S> <Z> (MAILPATH <S>)
An array (colonseparated list) of filenames to check for new mail. Each filename can be followed
by a ? and a message that will be printed. The message will undergo parameter expansion, command substitution and arithmetic expansion with the variable $_ defined as the name of the file
that has changed. The default message is You have new mail. If an element is a directory
instead of a file the shell will recursively check every file in every subdirectory of the element.
manpath <S> <Z> (MANPATH <S> <Z>)
An array (colonseparated list) whose value is not used by the shell. The manpath array can be
useful, however, since setting it also sets MANPATH, and vice versa.
module_path <S> <Z> (MODULE_PATH <S>)
An array (colonseparated list) of directories that zmodload searches for dynamically loadable
modules.
This
is
initialized
to
a
standard
pathname,
usually
/usr/local/lib/zsh/$ZSH_VERSION. (The /usr/local/lib part varies from installation to installation.) For security reasons, any value set in the environment when the shell is started will be
ignored.
These parameters only exist if the installation supports dynamic module loading.
NULLCMD <S>
The command name to assume if a redirection is specified with no command. Defaults to cat. For
sh/ksh behavior, change this to :. For cshlike behavior, unset this parameter; the shell will print
an error message if null commands are entered.
path <S> <Z> (PATH <S>)
An array (colonseparated list) of directories to search for commands. When this parameter is set,
each directory is scanned and all files found are put in a hash table.
POSTEDIT <S>
This string is output whenever the line editor exits. It usually contains termcap strings to reset the
terminal.
PROMPT <S> <Z>

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHPARAM ( 1 )

PROMPT2 <S> <Z>


PROMPT3 <S> <Z>
PROMPT4 <S> <Z>
Same as PS1, PS2, PS3 and PS4, respectively.
prompt <S> <Z>
Same as PS1.
PS1 <S>
The primary prompt string, printed before a command is read. the default is %m%# . It undergoes a special form of expansion before being displayed; see the section Prompt Expansion.
PS2 <S>
The secondary prompt, printed when the shell needs more information to complete a command. It
is expanded in the same way as PS1. The default is %_> , which displays any shell constructs or
quotation marks which are currently being processed.
PS3 <S>
Selection prompt used within a select loop. It is expanded in the same way as PS1. The default is
?# .
PS4 <S>
The execution trace prompt. Default is +%N:%i> , which displays the name of the current shell
structure and the line number within it. In sh or ksh emulation, the default is + .
psvar <S> <Z> (PSVAR <S>)
An array (colonseparated list) whose first nine values can be used in PROMPT strings. Setting
psvar also sets PSVAR, and vice versa.
READNULLCMD <S>
The command name to assume if a single input redirection is specified with no command.
Defaults to more.
REPORTTIME
If nonnegative, commands whose combined user and system execution times (measured in
seconds) are greater than this value have timing statistics printed for them.
REPLY
This parameter is reserved by convention to pass string values between shell scripts and shell builtins in situations where a function call or redirection are impossible or undesirable. The read builtin and the select complex command may set REPLY, and filename generation both sets and
examines its value when evaluating certain expressions. Some modules also employ REPLY for
similar purposes.
reply

As REPLY, but for array values rather than strings.

RPROMPT <S>
RPS1 <S>
This prompt is displayed on the righthand side of the screen when the primary prompt is being
displayed on the left. This does not work if the SINGLELINEZLE option is set. It is expanded
in the same way as PS1.
SAVEHIST
The maximum number of history events to save in the history file.
SPROMPT <S>
The prompt used for spelling correction. The sequence %R expands to the string which presumably needs spelling correction, and %r expands to the proposed correction. All other prompt
escapes are also allowed.
STTY If this parameter is set in a commands environment, the shell runs the stty command with the
value of this parameter as arguments in order to set up the terminal before executing the command.

zsh 4.0.4

Last change: October 26, 2001

10

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHPARAM ( 1 )

The modes apply only to the command, and are reset when it finishes or is suspended. If the command is suspended and continued later with the fg or wait builtins it will see the modes specified
by STTY, as if it were not suspended. This (intentionally) does not apply if the command is continued via kill CONT. STTY is ignored if the command is run in the background, or if it is in
the environment of the shell but not explicitly assigned to in the input line. This avoids running
stty at every external command by accidentally exporting it. Also note that STTY should not be
used for window size specifications; these will not be local to the command.
TERM <S>
The type of terminal in use. This is used when looking up termcap sequences. An assignment to
TERM causes zsh to reinitialize the terminal, even if the value does not change (e.g.,
TERM=$TERM). It is necessary to make such an assignment upon any change to the terminal
definition database or terminal type in order for the new settings to take effect.
TIMEFMT
The format of process time reports with the time keyword. The default is %E real %U user
%S system %P %J. Recognizes the following escape sequences:
%%
%U
%S
%E
%P
%J

A %.
CPU seconds spent in user mode.
CPU seconds spent in kernel mode.
Elapsed time in seconds.
The CPU percentage, computed as (%U+%S)/%E.
The name of this job.

A star may be inserted between the percent sign and flags printing time. This cause the time to be
printed in hh:mm:ss.ttt format (hours and minutes are only printed if they are not zero).
TMOUT
If this parameter is nonzero, the shell will receive an ALRM signal if a command is not entered
within the specified number of seconds after issuing a prompt. If there is a trap on SIGALRM, it
will be executed and a new alarm is scheduled using the value of the TMOUT parameter after
executing the trap. If no trap is set, and the idle time of the terminal is not less than the value of
the TMOUT parameter, zsh terminates. Otherwise a new alarm is scheduled to TMOUT seconds
after the last keypress.
TMPPREFIX
A pathname prefix which the shell will use for all temporary files. Note that this should include an
initial part for the file name as well as any directory names. The default is /tmp/zsh.
watch <S> <Z> (WATCH <S>)
An array (colonseparated list) of login/logout events to report. If it contains the single word all,
then all login/logout events are reported. If it contains the single word notme, then all events are
reported as with all except $USERNAME. An entry in this list may consist of a username, an
@ followed by a remote hostname, and a % followed by a line (tty). Any or all of these components may be present in an entry; if a login/logout event matches all of them, it is reported.
WATCHFMT
The format of login/logout reports if the watch parameter is set. Default is %n has %a %l from
%m. Recognizes the following escape sequences:

zsh 4.0.4

%n

The name of the user that logged in/out.

%a

The observed action, i.e. "logged on" or "logged off".

%l

The line (tty) the user is logged in on.

%M

The full hostname of the remote host.

%m

The hostname up to the first .. If only the IP address is available or the utmp field contains the name of an Xwindows display, the whole name is printed.

Last change: October 26, 2001

11

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHPARAM ( 1 )

NOTE: The %m and %M escapes will work only if there is a host name field in the
utmp on your machine. Otherwise they are treated as ordinary strings.
%S (%s)
Start (stop) standout mode.
%U (%u)
Start (stop) underline mode.
%B (%b)
Start (stop) boldface mode.
%t
%@

The time, in 12hour, am/pm format.

%T

The time, in 24hour format.

%w

The date in daydd format.

%W

The date in mm/dd/yy format.

%D

The date in yymmdd format.

%(x:truetext:falsetext)
Specifies a ternary expression. The character following the x is arbitrary; the same character is used to separate the text for the "true" result from that for the "false" result. Both
the separator and the right parenthesis may be escaped with a backslash. Ternary expressions may be nested.
The test character x may be any one of l, n, m or M, which indicate a true result
if the corresponding escape sequence would return a nonempty value; or it may be a,
which indicates a true result if the watched user has logged in, or false if he has logged
out. Other characters evaluate to neither true nor false; the entire expression is omitted in
this case.
If the result is true, then the truetext is formatted according to the rules above and
printed, and the falsetext is skipped. If false, the truetext is skipped and the falsetext
is formatted and printed. Either or both of the branches may be empty, but both separators must be present in any case.
WORDCHARS <S>
A list of nonalphanumeric characters considered part of a word by the line editor.
ZBEEP
If set, this gives a string of characters, which can use all the same codes as the bindkey command as
described in the zsh/zle module entry in zshmodules(1), that will be output to the terminal instead of beeping. This may have a visible instead of an audible effect; for example, the string \e[?5h\e[?5l on a vt100
or xterm will have the effect of flashing reverse video on and off (if you usually use reverse video, you
should use the string \e[?5l\e[?5h instead). This takes precedence over the NOBEEP option.
ZDOTDIR
The directory to search for shell startup files (.zshrc, etc), if not $HOME.

zsh 4.0.4

Last change: October 26, 2001

12

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHOPTIONS ( 1 )

NAME

zshoptions zsh options


SPECIFYING OPTIONS

Options are primarily referred to by name. These names are case insensitive and underscores are ignored.
For example, allexport is equivalent to A__lleXP_ort.
The sense of an option name may be inverted by preceding it with no, so setopt No_Beep is equivalent
to unsetopt beep. This inversion can only be done once, so nonobeep is not a synonym for beep.
Similarly, tify is not a synonym for nonotify (the inversion of notify).
Some options also have one or more single letter names. There are two sets of single letter options: one
used by default, and another used to emulate sh/ksh (used when the SH_OPTION_LETTERS option is
set). The single letter options can be used on the shell command line, or with the set, setopt and unsetopt
builtins, as normal Unix options preceded by .
The sense of the single letter options may be inverted by using + instead of . Some of the single letter
option names refer to an option being off, in which case the inversion of that name refers to the option
being on. For example, +n is the short name of exec, and n is the short name of its inversion,
noexec.
In strings of single letter options supplied to the shell at startup, trailing whitespace will be ignored; for
example the string f will be treated just as f, but the string f i is an error. This is because many
systems which implement the #! mechanism for calling scripts do not strip trailing whitespace.
DESCRIPTION OF OPTIONS

In the following list, options set by default in all emulations are marked <D>; those set by default only in
csh, ksh, sh, or zsh emulations are marked <C>, <K>, <S>, <Z> as appropriate. When listing options (by
setopt, unsetopt, set o or set +o), those turned on by default appear in the list prefixed with no.
Hence (unless KSH_OPTION_PRINT is set), setopt shows all options whose settings are changed from
the default.
ALIASES <D>
Expand aliases.
ALL_EXPORT (a, ksh: a)
All parameters subsequently defined are automatically exported.
ALWAYS_LAST_PROMPT <D>
If unset, key functions that list completions try to return to the last prompt if given a numeric argument. If set these functions try to return to the last prompt if given no numeric argument.
ALWAYS_TO_END
If a completion is performed with the cursor within a word, and a full completion is inserted, the
cursor is moved to the end of the word. That is, the cursor is moved to the end of the word if
either a single match is inserted or menu completion is performed.
APPEND_HISTORY <D>
If this is set, zsh sessions will append their history list to the history file, rather than overwrite it.
Thus, multiple parallel zsh sessions will all have their history lists added to the history file, in the
order they are killed.
AUTO_CD (J)
If a command is issued that cant be executed as a normal command, and the command is the
name of a directory, perform the cd command to that directory.
AUTO_LIST (9) <D>
Automatically list choices on an ambiguous completion.
AUTO_MENU <D>
Automatically use menu completion after the second consecutive request for completion, for
example by pressing the tab key repeatedly. This option is overridden by MENU_COMPLETE.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHOPTIONS ( 1 )

AUTO_NAME_DIRS
Any parameter that is set to the absolute name of a directory immediately becomes a name for that
directory, that will be used by the % and related prompt sequences, and will be available when
completion is performed on a word starting with . (Otherwise, the parameter must be used in
the form param first.)
AUTO_PARAM_KEYS <D>
If a parameter name was completed and a following character (normally a space) automatically
inserted, and the next character typed is one of those that have to come directly after the name (like
}, :, etc.), the automatically added character is deleted, so that the character typed comes
immediately after the parameter name. Completion in a brace expansion is affected similarly: the
added character is a ,, which will be removed if } is typed next.
AUTO_PARAM_SLASH <D>
If a parameter is completed whose content is the name of a directory, then add a trailing slash
instead of a space.
AUTO_PUSHD (N)
Make cd push the old directory onto the directory stack.
AUTO_REMOVE_SLASH <D>
When the last character resulting from a completion is a slash and the next character typed is a
word delimiter, a slash, or a character that ends a command (such as a semicolon or an ampersand), remove the slash.
AUTO_RESUME (W)
Treat single word simple commands without redirection as candidates for resumption of an existing job.
BAD_PATTERN (+2) <C> <Z>
If a pattern for filename generation is badly formed, print an error message. (If this option is
unset, the pattern will be left unchanged.)
BANG_HIST (+K) <C> <Z>
Perform textual history expansion, cshstyle, treating the character ! specially.
BARE_GLOB_QUAL <Z>
In a glob pattern, treat a trailing set of parentheses as a qualifier list, if it contains no , ( or (if
special) characters. See the section Filename Generation.
BASH_AUTO_LIST
On an ambiguous completion, automatically list choices when the completion function is called
twice in succession. This takes precedence over AUTO_LIST. The setting of
LIST_AMBIGUOUS is respected. If AUTO_MENU is set, the menu behaviour will then start
with the third press. Note that this will not work with MENU_COMPLETE, since repeated completion calls immediately cycle through the list in that case.
BEEP (+B) <D>
Beep on error in ZLE.
BG_NICE (6) <C> <Z>
Run all background jobs at a lower priority. This option is set by default.
BRACE_CCL
Expand expressions in braces which would not otherwise undergo brace expansion to a lexically
ordered list of all the characters. See the section Brace Expansion.
BSD_ECHO <S>
Make the echo builtin compatible with the BSD echo(1) command. This disables backslashed
escape sequences in echo strings unless the e option is specified.
C_BASES

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHOPTIONS ( 1 )

Output hexadecimal numbers in the standard C format, for example 0xFF instead of the usual
16#FF. If the option OCTAL_ZEROES is also set (it is not by default), octal numbers will be
treated similarly and hence appear as 077 instead of 8#77. This option has no effect on the
choice of the output base, nor on the output of bases other than hexadecimal and octal. Note that
these formats will be understood on input irrespective of the setting of C_BASES.
CDABLE_VARS (T)
If the argument to a cd command (or an implied cd with the AUTO_CD option set) is not a directory, and does not begin with a slash, try to expand the expression as if it were preceded by a
(see the section Filename Expansion).
CHASE_DOTS
When changing to a directory containing a path segment .. which would otherwise be treated as
canceling the previous segment in the path (in other words, foo/.. would be removed from the
path, or if .. is the first part of the path, the last part of $PWD would be deleted), instead resolve
the path to the physical directory. This option is overridden by CHASE_LINKS.
For example, suppose /foo/bar is a link to the directory /alt/rod. Without this option set, cd
/foo/bar/.. changes to /foo; with it set, it changes to /alt. The same applies if the current directory
is /foo/bar and cd .. is used. Note that all other symbolic links in the path will also be resolved.
CHASE_LINKS (w)
Resolve symbolic links to their true values when changing directory. This also has the effect of
CHASE_DOTS, i.e. a .. path segment will be treated as referring to the physical parent, even if
the preceding path segment is a symbolic link.
CHECK_JOBS <Z>
Report the status of background and suspended jobs before exiting a shell with job control; a
second attempt to exit the shell will succeed. NO_CHECK_JOBS is best used only in combination with NO_HUP, else such jobs will be killed automatically.
The check is omitted if the commands run from the previous command line included a jobs command, since it is assumed the user is aware that there are background or suspended jobs. A jobs
command run from the precmd function is not counted for this purpose.
CLOBBER (+C, ksh: +C) <D>
Allows > redirection to truncate existing files, and >> to create files. Otherwise >! or >
must be used to truncate a file, and >>! or >> to create a file.
COMPLETE_ALIASES
Prevents aliases on the command line from being internally substituted before completion is
attempted. The effect is to make the alias a distinct command for completion purposes.
COMPLETE_IN_WORD
If unset, the cursor is set to the end of the word if completion is started. Otherwise it stays there
and completion is done from both ends.
CORRECT (0)
Try to correct the spelling of commands.
CORRECT_ALL (O)
Try to correct the spelling of all arguments in a line.
CSH_JUNKIE_HISTORY <C>
A history reference without an event specifier will always refer to the previous command. Without
this option, such a history reference refers to the same event as the previous history reference,
defaulting to the previous command.
CSH_JUNKIE_LOOPS <C>
Allow loop bodies to take the form list; end instead of do list; done.
CSH_JUNKIE_QUOTES <C>

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHOPTIONS ( 1 )

Changes the rules for single and doublequoted text to match that of csh. These require that
embedded newlines be preceded by a backslash; unescaped newlines will cause an error message.
In doublequoted strings, it is made impossible to escape $, or " (and \ itself no longer
needs escaping). Command substitutions are only expanded once, and cannot be nested.
CSH_NULLCMD <C>
Do not use the values of NULLCMD and READNULLCMD when running redirections with no
command. This make such redirections fail (see the section Redirection).
CSH_NULL_GLOB <C>
If a pattern for filename generation has no matches, delete the pattern from the argument list; do
not report an error unless all the patterns in a command have no matches. Overrides NOMATCH.
DVORAK
Use the Dvorak keyboard instead of the standard qwerty keyboard as a basis for examining spelling mistakes for the CORRECT and CORRECT_ALL options and the spellword editor command.
EQUALS <Z>
Perform = filename expansion. (See the section Filename Expansion.)
ERR_EXIT (e, ksh: e)
If a command has a nonzero exit status, execute the ZERR trap, if set, and exit. This is disabled
while running initialization scripts.
EXEC (+n, ksh: +n) <D>
Do execute commands. Without this option, commands are read and checked for syntax errors,
but not executed. This option cannot be turned off in an interactive shell, except when n is supplied to the shell at startup.
EXTENDED_GLOB
Treat the #, and characters as part of patterns for filename generation, etc. (An initial
unquoted always produces named directory expansion.)
EXTENDED_HISTORY <C>
Save each commands beginning timestamp (in seconds since the epoch) and the duration (in
seconds) to the history file. The format of this prefixed data is:
:< beginning time> :< elapsed seconds> :< command> .
FLOW_CONTROL <D>
If this option is unset, output flow control via start/stop characters (usually assigned to S/Q) is
disabled in the shells editor.
FUNCTION_ARGZERO <C> <Z>
When executing a shell function or sourcing a script, set $0 temporarily to the name of the
function/script.
GLOB (+F, ksh: +f) <D>
Perform filename generation (globbing). (See the section Filename Generation.)
GLOBAL_EXPORT (<Z>)
If this option is set, passing the x flag to the builtins declare, float, integer, readonly and
typeset (but not local) will also set the g flag; hence parameters exported to the environment will
not be made local to the enclosing function, unless they were already or the flag +g is given explicitly. If the option is unset, exported parameters will be made local in just the same way as any
other parameter.
This option is set by default for backward compatibility; it is not recommended that its behaviour
be relied upon. Note that the builtin export always sets both the x and g flags, and hence its
effect extends beyond the scope of the enclosing function; this is the most portable way to achieve
this behaviour.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHOPTIONS ( 1 )

GLOBAL_RCS (d) <D>


If this option is unset, the startup files /etc/zprofile, /etc/zshrc, /etc/zlogin and /etc/zlogout will
not be run. It can be disabled and reenabled at any time, including inside local startup files
(.zshrc, etc.).
GLOB_ASSIGN <C>
If this option is set, filename generation (globbing) is performed on the right hand side of scalar
parameter assignments of the form name=pattern (e.g. foo=). If the result has more than one
word the parameter will become an array with those words as arguments. This option is provided
for backwards compatibility only: globbing is always performed on the right hand side of array
assignments of the form name=(value) (e.g. foo=()) and this form is recommended for clarity;
with this option set, it is not possible to predict whether the result will be an array or a scalar.
GLOB_COMPLETE
When the current word has a glob pattern, do not insert all the words resulting from the expansion
but generate matches as for completion and cycle through them like MENU_COMPLETE. The
matches are generated as if a was added to the end of the word, or inserted at the cursor when
COMPLETE_IN_WORD is set. This actually uses pattern matching, not globbing, so it works
not only for files but for any completion, such as options, user names, etc.
GLOB_DOTS (4)
Do not require a leading . in a filename to be matched explicitly.
GLOB_SUBST <C> <K> <S>
Treat any characters resulting from parameter expansion as being eligible for file expansion and
filename generation, and any characters resulting from command substitution as being eligible for
filename generation. Braces (and commas in between) do not become eligible for expansion.
HASH_CMDS <D>
Note the location of each command the first time it is executed. Subsequent invocations of the
same command will use the saved location, avoiding a path search. If this option is unset, no path
hashing is done at all. However, when CORRECT is set, commands whose names do not appear
in the functions or aliases hash tables are hashed in order to avoid reporting them as spelling
errors.
HASH_DIRS <D>
Whenever a command name is hashed, hash the directory containing it, as well as all directories
that occur earlier in the path. Has no effect if neither HASH_CMDS nor CORRECT is set.
HASH_LIST_ALL <D>
Whenever a command completion is attempted, make sure the entire command path is hashed first.
This makes the first completion slower.
HIST_ALLOW_CLOBBER
Add to output redirections in the history. This allows history references to clobber files even
when CLOBBER is unset.
HIST_BEEP <D>
Beep when an attempt is made to access a history entry which isnt there.
HIST_EXPIRE_DUPS_FIRST
If the internal history needs to be trimmed to add the current command line, setting this option will
cause the oldest history event that has a duplicate to be lost before losing a unique event from the
list. You should be sure to set the value of HISTSIZE to a larger number than SAVEHIST in
order to give you some room for the duplicated events, otherwise this option will behave just like
HIST_IGNORE_ALL_DUPS once the history fills up with unique events.
HIST_FIND_NO_DUPS
When searching for history entries in the line editor, do not display duplicates of a line previously
found, even if the duplicates are not contiguous.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHOPTIONS ( 1 )

HIST_IGNORE_ALL_DUPS
If a new command line being added to the history list duplicates an older one, the older command
is removed from the list (even if it is not the previous event).
HIST_IGNORE_DUPS (h)
Do not enter command lines into the history list if they are duplicates of the previous event.
HIST_IGNORE_SPACE (g)
Remove command lines from the history list when the first character on the line is a space, or
when one of the expanded aliases contains a leading space. Note that the command lingers in the
internal history until the next command is entered before it vanishes, allowing you to briefly reuse
or edit the line. If you want to make it vanish right away without entering another command, type
a space and press return.
HIST_NO_FUNCTIONS
Remove function definitions from the history list. Note that the function lingers in the internal history until the next command is entered before it vanishes, allowing you to briefly reuse or edit the
definition.
HIST_NO_STORE
Remove the history (fc l) command from the history list when invoked. Note that the command
lingers in the internal history until the next command is entered before it vanishes, allowing you to
briefly reuse or edit the line.
HIST_REDUCE_BLANKS
Remove superfluous blanks from each command line being added to the history list.
HIST_SAVE_NO_DUPS
When writing out the history file, older commands that duplicate newer ones are omitted.
HIST_VERIFY
Whenever the user enters a line with history expansion, dont execute the line directly; instead,
perform history expansion and reload the line into the editing buffer.
HUP <Z>
Send the HUP signal to running jobs when the shell exits.
IGNORE_BRACES (I) <S>
Do not perform brace expansion.
IGNORE_EOF (7)
Do not exit on endoffile. Require the use of exit or logout instead. However, ten consecutive
EOFs will cause the shell to exit anyway, to avoid the shell hanging if its tty goes away.
Also, if this option is set and the Zsh Line Editor is used, widgets implemented by shell functions
can be bound to EOF (normally ControlD) without printing the normal warning message. This
works only for normal widgets, not for completion widgets.
INC_APPEND_HISTORY
This options works like APPEND_HISTORY except that new history lines are added to the
$HISTFILE incrementally (as soon as they are entered), rather than waiting until the shell is
killed. The file is periodically trimmed to the number of lines specified by $SAVEHIST, but can
exceed this value between trimmings.
INTERACTIVE (i, ksh: i)
This is an interactive shell. This option is set upon initialisation if the standard input is a tty and
commands are being read from standard input. (See the discussion of SHIN_STDIN.) This
heuristic may be overridden by specifying a state for this option on the command line. The value
of this option cannot be changed anywhere other than the command line.
INTERACTIVE_COMMENTS (k) <K> <S>
Allow comments even in interactive shells.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHOPTIONS ( 1 )

KSH_ARRAYS <K> <S>


Emulate ksh array handling as closely as possible. If this option is set, array elements are numbered from zero, an array parameter without subscript refers to the first element instead of the
whole array, and braces are required to delimit a subscript (${path[2]} rather than just
$path[2]).
KSH_AUTOLOAD <K> <S>
Emulate ksh function autoloading. This means that when a function is autoloaded, the
corresponding file is merely executed, and must define the function itself. (By default, the function is defined to the contents of the file. However, the most common kshstyle case of the file
containing only a simple definition of the function is always handled in the kshcompatible
manner.)
KSH_GLOB <K>
In pattern matching, the interpretation of parentheses is affected by a preceding @, , +, ? or
!. See the section Filename Generation.
KSH_OPTION_PRINT <K>
Alters the way options settings are printed: instead of separate lists of set and unset options, all
options are shown, marked on if they are in the nondefault state, off otherwise.
KSH_TYPESET <K>
Alters the way arguments to the typeset family of commands, including declare, export, float,
integer, local and readonly, are processed. Without this option, zsh will perform normal word
splitting after command and parameter expansion in arguments of an assignment; with it, word
splitting does not take place in those cases.
LIST_AMBIGUOUS <D>
This option works when AUTO_LIST or BASH_AUTO_LIST is also set. If there is an unambiguous prefix to insert on the command line, that is done without a completion list being displayed;
in other words, autolisting behaviour only takes place when nothing would be inserted. In the
case of BASH_AUTO_LIST, this means that the list will be delayed to the third call of the function.
LIST_BEEP <D>
Beep on an ambiguous completion. More accurately, this forces the completion widgets to return
status 1 on an ambiguous completion, which causes the shell to beep if the option BEEP is also
set; this may be modified if completion is called from a userdefined widget.
LIST_PACKED
Try to make the completion list smaller (occupying less lines) by printing the matches in columns
with different widths.
LIST_ROWS_FIRST
Lay out the matches in completion lists sorted horizontally, that is, the second match is to the right
of the first one, not under it as usual.
LIST_TYPES (X) <D>
When listing files that are possible completions, show the type of each file with a trailing identifying mark.
LOCAL_OPTIONS <K>
If this option is set at the point of return from a shell function, all the options (including this one)
which were in force upon entry to the function are restored. Otherwise, only this option and the
XTRACE and PRINT_EXIT_VALUE options are restored. Hence if this is explicitly unset by a
shell function the other options in force at the point of return will remain so. A shell function can
also guarantee itself a known shell configuration with a formulation like emulate L zsh; the L
activates LOCAL_OPTIONS.
LOCAL_TRAPS <K>

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHOPTIONS ( 1 )

If this option is set when a signal trap is set inside a function, then the previous status of the trap
for that signal will be restored when the function exits. Note that this option must be set prior to
altering the trap behaviour in a function; unlike LOCAL_OPTIONS, the value on exit from the
function is irrelevant. However, it does not need to be set before any global trap for that to be
correctly restored by a function. For example,
unsetopt localtraps
trap INT
fn() { setopt localtraps; trap INT; sleep 3; }
will restore normally handling of SIGINT after the function exits.
LOGIN (l, ksh: l)
This is a login shell. If this option is not explicitly set, the shell is a login shell if the first character
of the argv[0] passed to the shell is a .
LONG_LIST_JOBS (R)
List jobs in the long format by default.
MAGIC_EQUAL_SUBST
All unquoted arguments of the form anything=expression appearing after the command name
have filename expansion (that is, where expression has a leading or =) performed on expression as if it were a parameter assignment. The argument is not otherwise treated specially; it is
passed to the command as a single argument, and not used as an actual parameter assignment. For
example, in echo foo=/bar:/rod, both occurrences of would be replaced. Note that this happens anyway with typeset and similar statements.
This option respects the setting of the KSH_TYPESET option. In other words, if both options
are in effect, arguments looking like assignments will not undergo wordsplitting.
MAIL_WARNING (U)
Print a warning message if a mail file has been accessed since the shell last checked.
MARK_DIRS (8, ksh: X)
Append a trailing / to all directory names resulting from filename generation (globbing).
MENU_COMPLETE (Y)
On an ambiguous completion, instead of listing possibilities or beeping, insert the first match
immediately. Then when completion is requested again, remove the first match and insert the
second match, etc. When there are no more matches, go back to the first one again.
reversemenucomplete may be used to loop through the list in the other direction. This option
overrides AUTO_MENU.
MONITOR (m, ksh: m)
Allow job control. Set by default in interactive shells.
MULTIOS <Z>
Perform implicit tees or cats when multiple redirections are attempted (see the section Redirection).
NOMATCH (+3) <C> <Z>
If a pattern for filename generation has no matches, print an error, instead of leaving it unchanged
in the argument list. This also applies to file expansion of an initial or =.
NOTIFY (5, ksh: b) <Z>
Report the status of background jobs immediately, rather than waiting until just before printing a
prompt.
NULL_GLOB (G)
If a pattern for filename generation has no matches, delete the pattern from the argument list
instead of reporting an error. Overrides NOMATCH.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHOPTIONS ( 1 )

NUMERIC_GLOB_SORT
If numeric filenames are matched by a filename generation pattern, sort the filenames numerically
rather than lexicographically.
OCTAL_ZEROES <S>
Interpret any integer constant beginning with a 0 as octal, per IEEE Std 1003.21992 (ISO
99452:1993). This is not enabled by default as it causes problems with parsing of, for example,
date and time strings with leading zeroes.
OVERSTRIKE
Start up the line editor in overstrike mode.
PATH_DIRS (Q)
Perform a path search even on command names with slashes in them. Thus if /usr/local/bin is in
the users path, and he or she types X11/xinit, the command /usr/local/bin/X11/xinit will be
executed (assuming it exists). Commands explicitly beginning with /, ./ or ../ are not subject
to the path search. This also applies to the . builtin.
Note that subdirectories of the current directory are always searched for executables specified in
this form. This takes place before any search indicated by this option, and regardless of whether
. or the current directory appear in the command search path.
POSIX_BUILTINS <K> <S>
When this option is set the command builtin can be used to execute shell builtin commands.
Parameter assignments specified before shell functions and special builtins are kept after the command completes unless the special builtin is prefixed with the command builtin. Special builtins
are ., :, break, continue, declare, eval, exit, export, integer, local, readonly, return, set, shift,
source, times, trap and unset.
PRINT_EIGHT_BIT
Print eight bit characters literally in completion lists, etc. This option is not necessary if your system correctly returns the printability of eight bit characters (see ctype(3)).
PRINT_EXIT_VALUE (1)
Print the exit value of programs with nonzero exit status.
PRIVILEGED (p, ksh: p)
Turn on privileged mode. This is enabled automatically on startup if the effective user (group) ID
is not equal to the real user (group) ID. Turning this option off causes the effective user and group
IDs to be set to the real user and group IDs. This option disables sourcing user startup files. If zsh
is invoked as sh or ksh with this option set, /etc/suid_profile is sourced (after /etc/profile on
interactive shells). Sourcing /.profile is disabled and the contents of the ENV variable is ignored.
This option cannot be changed using the m option of setopt and unsetopt, and changing it inside
a function always changes it globally regardless of the LOCAL_OPTIONS option.
PROMPT_BANG <K>
If set, ! is treated specially in prompt expansion. See the section Prompt Expansion.
PROMPT_CR (+V) <D>
Print a carriage return just before printing a prompt in the line editor. This is on by default as
multiline editing is only possible if the editor knows where the start of the line appears.
PROMPT_PERCENT <C> <Z>
If set, % is treated specially in prompt expansion. See the section Prompt Expansion.
PROMPT_SUBST <K>
If set, parameter expansion, command substitution and arithmetic expansion are performed in
prompts.
PUSHD_IGNORE_DUPS
Dont push multiple copies of the same directory onto the directory stack.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHOPTIONS ( 1 )

PUSHD_MINUS
Exchanges the meanings of + and when used with a number to specify a directory in the
stack.
PUSHD_SILENT (E)
Do not print the directory stack after pushd or popd.
PUSHD_TO_HOME (D)
Have pushd with no arguments act like pushd $HOME.
RC_EXPAND_PARAM (P)
Array expansions of the form foo${xx}bar, where the parameter xx is set to (a b c), are substituted with fooabar foobbar foocbar instead of the default fooa b cbar.
RC_QUOTES
Allow the character sequence to signify a single quote within singly quoted strings. Note this
does not apply in quoted strings using the format $..., where a backslashed single quote can be
used.
RCS (+f) <D>
After /etc/zshenv is sourced on startup, source the .zshenv, /etc/zprofile, .zprofile, /etc/zshrc,
.zshrc, /etc/zlogin, .zlogin, and .zlogout files, as described in the section Files. If this option is
unset, the /etc/zshenv file is still sourced, but any of the others will not be; it can be set at any time
to prevent the remaining startup files after the currently executing one from being sourced.
REC_EXACT (S)
In completion, recognize exact matches even if they are ambiguous.
RESTRICTED (r)
Enables restricted mode. This option cannot be changed using unsetopt, and setting it inside a
function always changes it globally regardless of the LOCAL_OPTIONS option. See the section
Restricted Shell.
RM_STAR_SILENT (H) <K> <S>
Do not query the user before executing rm or rm path/.
RM_STAR_WAIT
If querying the user before executing rm or rm path/, first wait ten seconds and ignore anything typed in that time. This avoids the problem of reflexively answering yes to the query when
one didnt really mean it. The wait and query can always be avoided by expanding the in ZLE
(with tab).
SHARE_HISTORY <K>
This option both imports new commands from the history file, and also causes your typed commands to be appended to the history file (the latter is like specifying INC_APPEND_HISTORY).
The history lines are also output with timestamps ala EXTENDED_HISTORY (which makes it
easier to find the spot where we left off reading the file after it gets rewritten).
By default, history movement commands visit the imported lines as well as the local lines, but you
can toggle this on and off with the setlocalhistory zle binding. It is also possible to create a zle
widget that will make some commands ignore imported commands, and some include them.
If you find that you want more control over when commands get imported, you may wish to turn
SHARE_HISTORY off, INC_APPEND_HISTORY on, and then manually import commands
whenever you need them using fc RI.
SH_FILE_EXPANSION <K> <S>
Perform filename expansion (e.g., expansion) before parameter expansion, command substitution, arithmetic expansion and brace expansion. If this option is unset, it is performed after brace
expansion, so things like $USERNAME and {pfalstad,rc} will work.

zsh 4.0.4

Last change: October 26, 2001

10

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHOPTIONS ( 1 )

SH_GLOB <K> <S>


Disables the special meaning of (, , ) and < for globbing the result of parameter and command substitutions, and in some other places where the shell accepts patterns. This option is set
by default if zsh is invoked as sh or ksh.
SHIN_STDIN (s, ksh: s)
Commands are being read from the standard input. Commands are read from standard input if no
command is specified with c and no file of commands is specified. If SHIN_STDIN is set explicitly on the command line, any argument that would otherwise have been taken as a file to run will
instead be treated as a normal positional parameter. Note that setting or unsetting this option on
the command line does not necessarily affect the state the option will have while the shell is running that is purely an indicator of whether on not commands are actually being read from standard input. The value of this option cannot be changed anywhere other than the command line.
SH_NULLCMD <K> <S>
Do not use the values of NULLCMD and READNULLCMD when doing redirections, use :
instead (see the section Redirection).
SH_OPTION_LETTERS <K> <S>
If this option is set the shell tries to interpret single letter options (which are used with set and
setopt) like ksh does. This also affects the value of the special parameter.
SHORT_LOOPS <C> <Z>
Allow the short forms of for, select, if, and function constructs.
SH_WORD_SPLIT (y) <K> <S>
Causes field splitting to be performed on unquoted parameter expansions. Note that this option
has nothing to do with word splitting. (See the section Parameter Expansion.)
SINGLE_COMMAND (t, ksh: t)
If the shell is reading from standard input, it exits after a single command has been executed. This
also makes the shell noninteractive, unless the INTERACTIVE option is explicitly set on the
command line. The value of this option cannot be changed anywhere other than the command
line.
SINGLE_LINE_ZLE (M) <K>
Use singleline command line editing instead of multiline.
SUN_KEYBOARD_HACK (L)
If a line ends with a backquote, and there are an odd number of backquotes on the line, ignore the
trailing backquote. This is useful on some keyboards where the return key is too small, and the
backquote key lies annoyingly close to it.
UNSET (+u, ksh: +u) <K> <S> <Z>
Treat unset parameters as if they were empty when substituting. Otherwise they are treated as an
error.
VERBOSE (v, ksh: v)
Print shell input lines as they are read.
XTRACE (x, ksh: x)
Print commands and their arguments as they are executed.
ZLE (Z)
Use the zsh line editor. Set by default in interactive shells connected to a terminal.
OPTION ALIASES

Some options have alternative names. These aliases are never used for output, but can be used just like normal option names when specifying options to the shell.

zsh 4.0.4

Last change: October 26, 2001

11

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHOPTIONS ( 1 )

BRACE_EXPAND
NO_IGNORE_BRACES (ksh and bash compatibility)
DOT_GLOB
GLOB_DOTS (bash compatibility)
HASH_ALL
HASH_CMDS (bash compatibility)
HIST_APPEND
APPEND_HISTORY (bash compatibility)
HIST_EXPAND
BANG_HIST (bash compatibility)
LOG

NO_HIST_NO_FUNCTIONS (ksh compatibility)

MAIL_WARN
MAIL_WARNING (bash compatibility)
ONE_CMD
SINGLE_COMMAND (bash compatibility)
PHYSICAL
CHASE_LINKS (ksh and bash compatibility)
PROMPT_VARS
PROMPT_SUBST (bash compatibility)
STDIN SHIN_STDIN (ksh compatibility)
TRACK_ALL
HASH_CMDS (ksh compatibility)
SINGLE LETTER OPTIONS
Default set

0
1
2
3
4
5
6
7
8
9
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P

zsh 4.0.4

CORRECT
PRINT_EXIT_VALUE
NO_BAD_PATTERN
NO_NOMATCH
GLOB_DOTS
NOTIFY
BG_NICE
IGNORE_EOF
MARK_DIRS
AUTO_LIST
NO_BEEP
NO_CLOBBER
PUSHD_TO_HOME
PUSHD_SILENT
NO_GLOB
NULL_GLOB
RM_STAR_SILENT
IGNORE_BRACES
AUTO_CD
NO_BANG_HIST
SUN_KEYBOARD_HACK
SINGLE_LINE_ZLE
AUTO_PUSHD
CORRECT_ALL
RC_EXPAND_PARAM

Last change: October 26, 2001

12

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

Q
R
S
T
U
V
W
X
Y
Z
a
e
f
g
h
i
k
l
m
n
p
r
s
t
u
v
w
x
y

ZSHOPTIONS ( 1 )

PATH_DIRS
LONG_LIST_JOBS
REC_EXACT
CDABLE_VARS
MAIL_WARNING
NO_PROMPT_CR
AUTO_RESUME
LIST_TYPES
MENU_COMPLETE
ZLE
ALL_EXPORT
ERR_EXIT
NO_RCS
HIST_IGNORE_SPACE
HIST_IGNORE_DUPS
INTERACTIVE
INTERACTIVE_COMMENTS
LOGIN
MONITOR
NO_EXEC
PRIVILEGED
RESTRICTED
SHIN_STDIN
SINGLE_COMMAND
NO_UNSET
VERBOSE
CHASE_LINKS
XTRACE
SH_WORD_SPLIT

sh/ksh emulation set

C
X
a
b
e
f
i
l
m
n
p
r
s
t
u
v
x

NO_CLOBBER
MARK_DIRS
ALL_EXPORT
NOTIFY
ERR_EXIT
NO_GLOB
INTERACTIVE
LOGIN
MONITOR
NO_EXEC
PRIVILEGED
RESTRICTED
SHIN_STDIN
SINGLE_COMMAND
NO_UNSET
VERBOSE
XTRACE

Also note

A
b
c
m
o

zsh 4.0.4

Used by set for setting arrays


Used on the command line to specify end of option processing
Used on the command line to specify a single command
Used by setopt for patternmatching option setting
Used in all places to allow use of long option names

Last change: October 26, 2001

13

User Commands

zsh 4.0.4

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHOPTIONS ( 1 )

Used by set to sort positional parameters

Last change: October 26, 2001

14

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

NAME

zshbuiltins zsh builtin commands


SHELL BUILTIN COMMANDS

simple command
See the section Precommand Modifiers.
. file [ arg ... ]
Read commands from file and execute them in the current shell environment.
If file does not contain a slash, or if PATH_DIRS is set, the shell looks in the components of
$path to find the directory containing file. Files in the current directory are not read unless .
appears somewhere in $path. If a file named file.zwc is found, is newer than file, and is the compiled form (created with the zcompile builtin) of file, then commands are read from that file
instead of file.
If any arguments arg are given, they become the positional parameters; the old positional parameters are restored when the file is done executing. The exit status is the exit status of the last command executed.
: [ arg ... ]
This command does nothing, although normal argument expansions is performed which may have
effects on shell parameters. A zero exit code is returned.
alias [ {+}gmrL ] [ name[=value] ... ]
For each name with a corresponding value, define an alias with that value. A trailing space in
value causes the next word to be checked for alias expansion. If the g flag is present, define a
global alias; global aliases are expanded even if they do not occur in command position.
For each name with no value, print the value of name, if any. With no arguments, print all
currently defined aliases. If the m flag is given the arguments are taken as patterns (they should
be quoted to preserve them from being interpreted as glob patterns), and the aliases matching these
patterns are printed. When printing aliases and the g or r flags are present, then restrict the
printing to global or regular aliases, respectively. Using + instead of , or ending the option list
with a single +, prevents the values of the aliases from being printed.
If the L flag is present, then print each alias in a manner suitable for putting in a startup script.
The exit status is nonzero if a name (with no value) is given for which no alias has been defined.
autoload [ {+}UXmt ] [ wkz ] [ name ... ]
Equivalent to functions u, with the exception of X/+X, w, k and z.
The flag X may be used only inside a shell function, and may not be followed by a name. It
causes the calling function to be marked for autoloading and then immediately loaded and executed, with the current array of positional parameters as arguments. This replaces the previous
definition of the function. If no function definition is found, an error is printed and the function
remains undefined and marked for autoloading.
The flag +X attempts to load each name as an autoloaded function, but does not execute it. The
exit status is zero (success) if the function was not previously defined and a definition for it was
found. This does not replace any existing definition of the function. The exit status is nonzero
(failure) if the function was already defined or when no definition was found. In the latter case the
function remains undefined and marked for autoloading.
The flag +X may be combined with either k or z to make the function be loaded using kshstyle
or zshstyle autoloading, respectively. If neither is given, the current setting of the
KSH_AUTOLOAD options determines how the function is loaded. With kshstyle autoloading,
the contents of the file will not be executed immediately. Instead, the function created will contain
the contents of the file plus a call to the function itself appended to it, thus given normal ksh autoloading behaviour on the first call to the function.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

With the w flag, the names are taken as names of files compiled with the zcompile builtin, and all
functions defined in them are marked for autoloading.
bg [ job ... ]
job ... &
Put each specified job in the background, or the current job if none is specified.
bindkey
See the section Zle Builtins in zshzle(1).
break [ n ]
Exit from an enclosing for, while, until, select or repeat loop. If n is specified, then break n levels instead of just one.
builtin name [ args ... ]
Executes the builtin name, with the given args.
bye

Same as exit.

cap

See the section The zsh/cap Module in zshmodules(1).

cd [ sLP ] [ arg ]
cd [ sLP ] old new
cd [ sLP ] {+}n
Change the current directory. In the first form, change the current directory to arg, or to the value
of $HOME if arg is not specified. If arg is , change to the value of $OLDPWD, the previous
directory. Otherwise, if a directory named arg is not found in the current directory and arg does
not begin with a slash, search each component of the shell parameter cdpath. If no directory is
found and the option CDABLE_VARS is set, and a parameter named arg exists whose value
begins with a slash, treat its value as the directory. In that case, the parameter is added to the
named directory hash table.
The second form of cd substitutes the string new for the string old in the name of the current directory, and tries to change to this new directory.
The third form of cd extracts an entry from the directory stack, and changes to that directory. An
argument of the form +n identifies a stack entry by counting from the left of the list shown by the
dirs command, starting with zero. An argument of the form n counts from the right. If the
PUSHD_MINUS option is set, the meanings of + and in this context are swapped.
If the s option is specified, cd refuses to change the current directory if the given pathname contains symlinks. If the P option is given or the CHASE_LINKS option is set, symbolic links are
resolved to their true values. If the L option is given symbolic links are followed regardless of
the state of the CHASE_LINKS option.
chdir

Same as cd.

clone

See the section The zsh/clone Module in zshmodules(1).

command simple command


See the section Precommand Modifiers.
comparguments
See the section The zsh/computil Module in zshmodules(1).
compcall
See the section The zsh/compctl Module in zshmodules(1).
compctl
See the section The zsh/compctl Module in zshmodules(1).
compdescribe
See the section The zsh/computil Module in zshmodules(1).

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

compfiles
See the section The zsh/computil Module in zshmodules(1).
compgroups
See the section The zsh/computil Module in zshmodules(1).
compquote
See the section The zsh/computil Module in zshmodules(1).
comptags
See the section The zsh/computil Module in zshmodules(1).
comptry
See the section The zsh/computil Module in zshmodules(1).
compvalues
See the section The zsh/computil Module in zshmodules(1).
continue [ n ]
Resume the next iteration of the enclosing for, while, until, select or repeat loop. If n is
specified, break out of n1 loops and resume at the nth enclosing loop.
declare Same as typeset.
dirs [ v ] [ arg ... ]
With no arguments, print the contents of the directory stack. If the v option is given, number the
directories in the stack when printing. Directories are added to this stack with the pushd command, and removed with the cd or popd commands. If arguments are specified, load them onto
the directory stack, replacing anything that was there, and push the current directory onto the
stack.
disable [ afmr ] name ...
Temporarily disable the named hash table elements. The default is to disable builtin commands.
This allows you to use an external command with the same name as a builtin command. The a
option causes disable to act on aliases. The f option causes disable to act on shell functions.
The r options causes disable to act on reserved words. Without arguments all disabled hash table
elements from the corresponding hash table are printed. With the m flag the arguments are taken
as patterns (which should be quoted to prevent them from undergoing filename expansion), and all
hash table elements from the corresponding hash table matching these patterns are disabled. Disabled objects can be enabled with the enable command.
disown [ job ... ]
job ... &
job ... &!
Remove the specified jobs from the job table; the shell will no longer report their status, and will
not complain if you try to exit an interactive shell with them running or stopped. If no job is
specified, disown the current job.
echo [ neE ] [ arg ... ]
Write each arg on the standard output, with a space separating each one. If the n flag is not
present, print a newline at the end. echo recognizes the following escape sequences:
\a
\b
\c
\e
\f
\n
\r
\t
\v

zsh 4.0.4

bell character
backspace
suppress final newline
escape
form feed
linefeed (newline)
carriage return
horizontal tab
vertical tab

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHBUILTINS ( 1 )

\\
backslash
\0NNN character code in octal
\xNN character code in hexadecimal
The E flag, or the BSD_ECHO option, can be used to disable these escape sequences. In the
latter case, e flag can be used to enable them.
echotc See the section The zsh/termcap Module in zshmodules(1).
echoti

See the section The zsh/terminfo Module in zshmodules(1).

emulate [ LR ] {zshshkshcsh}
Set up zsh options to emulate the specified shell as much as possible. csh will never be fully emulated. If the argument is not one of the shells listed above, zsh will be used as a default; more precisely, the tests performed on the argument are the same as those used to determine the emulation
at startup based on the shell name, see the section Compatibility in zshmisc(1) . If the R option
is given, all options are reset to their default value corresponding to the specified emulation mode,
except for certain options describing the interactive environment; otherwise, only those options
likely to cause portability problems in scripts and functions are altered. If the L option is given,
the options LOCAL_OPTIONS and LOCAL_TRAPS will be set as well, causing the effects of
the emulate command and any setopt and trap commands to be local to the immediately surrounding shell function, if any; normally these options are turned off in all emulation modes
except ksh.
enable [ afmr ] name ...
Enable the named hash table elements, presumably disabled earlier with disable. The default is to
enable builtin commands. The a option causes enable to act on aliases. The f option causes
enable to act on shell functions. The r option causes enable to act on reserved words. Without
arguments all enabled hash table elements from the corresponding hash table are printed. With the
m flag the arguments are taken as patterns (should be quoted) and all hash table elements from
the corresponding hash table matching these patterns are enabled. Enabled objects can be disabled
with the disable builtin command.
eval [ arg ... ]
Read the arguments as input to the shell and execute the resulting command in the current shell
process.
exec simple command
See the section Precommand Modifiers.
exit [ n ]
Exit the shell with the exit code specified by n; if none is specified, use the exit code from the last
command executed. An EOF condition will also cause the shell to exit, unless the
IGNORE_EOF option is set.
export [ name[=value] ... ]
The specified names are marked for automatic export to the environment of subsequently executed
commands. Equivalent to typeset gx. If a parameter specified does not already exist, it is created
in the global scope.
false [ arg ... ]
Do nothing and return an exit code of 1.
fc [ e ename ] [ nlrdDfEim ] [ old=new ... ] [ first [ last ] ]
fc ARWI [ filename ]
Select a range of commands from first to last from the history list. The arguments first and last
may be specified as a number or as a string. A negative number is used as an offset to the current
history event number. A string specifies the most recent event beginning with the given string.
All substitutions old=new, if any, are then performed on the commands.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHBUILTINS ( 1 )

If the l flag is given, the resulting commands are listed on standard output. If the m flag is also
given the first argument is taken as a pattern (should be quoted) and only the history events matching this pattern will be shown. Otherwise the editor program ename is invoked on a file containing
these history events. If ename is not given, the value of the parameter FCEDIT is used. If ename
is , no editor is invoked. When editing is complete, the edited command is executed.
If first is not specified, it will be set to 1 (the most recent event), or to 16 if the l flag is given.
If last is not specified, it will be set to first, or to 1 if the l flag is given.
The flag r reverses the order of the commands and the flag n suppresses command numbers
when listing. Also when listing, d prints timestamps for each command, and f prints full
timedate stamps. Adding the E flag causes the dates to be printed as dd.mm.yyyy, instead of
the default mm/dd/yyyy. Adding the i flag causes the dates to be printed in ISO8601
yyyymmdd format. With the D flag, fc prints elapsed times.
fc R reads the history from the given file, fc W writes the history out to the given file, and fc
A appends the history out to the given file. If no filename is specified, the $HISTFILE is
assumed. If the I option is added to R, only those events that are not already contained within
the internal history list are added. If the I option is added to A or W, only those events that are
new since last incremental append/write to the history file are appended/written. In any case, the
created file will have no more than $SAVEHIST entries.
fg [ job ... ]
job ... Bring each specified job in turn to the foreground. If no job is specified, resume the current job.
float [ {+}EFghlrtux ] [ name[=value] ... ]
Equivalent to typeset E, except that options irrelevant to floating point numbers are not permitted.
functions [ {+}UXmtu ] [ name ... ]
Equivalent to typeset f.
getcap See the section The zsh/cap Module in zshmodules(1).
getln [ AclneE ] name ...
Read the top value from the buffer stack and put it in the shell parameter name. Equivalent to
read zr.
getopts optstring name [ arg ... ]
Checks the args for legal options. If the args are omitted, use the positional parameters. A valid
option argument begins with a + or a . An argument not beginning with a + or a , or the
argument , ends the options. optstring contains the letters that getopts recognizes. If a letter
is followed by a :, that option is expected to have an argument. The options can be separated
from the argument by blanks.
Each time it is invoked, getopts places the option letter it finds in the shell parameter name,
prepended with a + when arg begins with a +. The index of the next arg is stored in OPTIND.
The option argument, if any, is stored in OPTARG.
The first option to be examined may be changed by explicitly assigning to OPTIND. OPTIND
has an initial value of 1, and is normally reset to 1 upon exit from a shell function. OPTARG is
not reset and retains its value from the most recent call to getopts. If either of OPTIND or
OPTARG is explicitly unset, it remains unset, and the index or option argument is not stored.
The option itself is still stored in name in this case.
A leading : in optstring causes getopts to store the letter of any invalid option in OPTARG, and
to set name to ? for an unknown option and to : when a required option is missing. Otherwise,
getopts sets name to ? and prints an error message when an option is invalid. The exit status is
nonzero when there are no more options.
hash [ Ldfmrv ] [ name[=value] ] ...

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

hash can be used to directly modify the contents of the command hash table, and the named directory hash table. Normally one would modify these tables by modifying ones PATH (for the command hash table) or by creating appropriate shell parameters (for the named directory hash table).
The choice of hash table to work on is determined by the d option; without the option the command hash table is used, and with the option the named directory hash table is used.
Given no arguments, and neither the r or f options, the selected hash table will be listed in full.
The r option causes the selected hash table to be emptied. It will be subsequently rebuilt in the
normal fashion. The f option causes the selected hash table to be fully rebuilt immediately. For
the command hash table this hashes all the absolute directories in the PATH, and for the named
directory hash table this adds all users home directories. These two options cannot be used with
any arguments.
The m option causes the arguments to be taken as patterns (which should be quoted) and the elements of the hash table matching those patterns are printed. This is the only way to display a limited selection of hash table elements.
For each name with a corresponding value, put name in the selected hash table, associating it
with the pathname value. In the command hash table, this means that whenever name is used
as a command argument, the shell will try to execute the file given by value. In the named directory hash table, this means that value may be referred to as name.
For each name with no corresponding value, attempt to add name to the hash table, checking what
the appropriate value is in the normal manner for that hash table. If an appropriate value cant be
found, then the hash table will be unchanged.
The v option causes hash table entries to be listed as they are added by explicit specification. If
has no effect if used with f.
If the L flag is present, then each hash table entry is printed in the form of a call to hash.
history Same as fc l.
integer [ {+}ghilrtux ] [ name[=value] ... ]
Equivalent to typeset i, except that options irrelevant to integers are not permitted.
jobs [ dlprs ] [ job ... ]
jobs Z string
Lists information about each given job, or all jobs if job is omitted. The l flag lists process IDs,
and the p flag lists process groups. If the r flag is specified only running jobs will be listed and
if the s flag is given only stopped jobs are shown. If the d flag is given, the directory from
which the job was started (which may not be the current directory of the job) will also be shown.
The Z option replaces the shells argument and environment space with the given string, truncated if necessary to fit. This will normally be visible in ps (ps(1)) listings. This feature is typically used by daemons, to indicate their state.
kill [ s signal_name ] job ...
kill [ sig ] job ...
kill l [ sig ... ]
Sends either SIGTERM or the specified signal to the given jobs or processes. Signals are given
by number or by names, without the SIG prefix. If the signal being sent is not KILL or
CONT, then the job will be sent a CONT signal if it is stopped. The argument job can be the
process ID of a job not in the job list. In the third form, kill l, if sig is not specified the signal
names are listed. Otherwise, for each sig that is a name, the corresponding signal number is listed.
For each sig that is a signal number or a number representing the exit status of a process which
was terminated or stopped by a signal the name of the signal is printed.
let arg ...
Evaluate each arg as an arithmetic expression. See the section Arithmetic Evaluation for a

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

description of arithmetic expressions. The exit status is 0 if the value of the last expression is
nonzero, and 1 otherwise.
limit [ hs ] [ resource [ limit ] ] ...
Set or display resource limits. Unless the s flag is given, the limit applies only the children of the
shell. If s is given without other arguments, the resource limits of the current shell is set to the
previously set resource limits of the children.
If limit is not specified, print the current limit placed on resource, otherwise set the limit to the
specified value. If the h flag is given, use hard limits instead of soft limits. If no resource is
given, print all limits.
resource can be one of:
addressspace
Maximum amount of address space used.
aiomemorylocked
Maximum amount of memory locked in RAM for AIO operations.
aiooperations
Maximum number of AIO operations.
cachedthreads
Maximum number of cached threads.
coredumpsize
Maximum size of a core dump.
cputime
Maximum CPU seconds per process.
datasize
Maximum data size (including stack) for each process.
descriptors
Maximum value for a file descriptor.
filesize Largest single file allowed.
maxproc
Maximum number of processes.
maxpthreads
Maximum number of threads per process.
memorylocked
Maximum amount of memory locked in RAM.
memoryuse
Maximum resident set size.
resident
Maximum resident set size.
sockbufsize
Maximum size of all socket buffers.
stacksize
Maximum stack size for each process.
vmemorysize
Maximum amount of virtual memory.
Which of these resource limits are available depends on the system. resource can be abbreviated
to any unambiguous prefix.
limit is a number, with an optional scaling factor, as follows:
nh
nk
nm
[mm:]ss

zsh 4.0.4

hours
kilobytes (default)
megabytes or minutes
minutes and seconds

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

local [ {+}AEFLRUZahilrtux [n]] [ name[=value] ] ...


Same as typeset, except that the options g, and f are not permitted. In this case the x option
does not force the use of g, i.e. exported variables will be local to functions.
log

List all users currently logged in who are affected by the current setting of the watch parameter.

logout [ n ]
Same as exit, except that it only works in a login shell.
noglob simple command
See the section Precommand Modifiers.
popd [ {+}n ]
Remove an entry from the directory stack, and perform a cd to the new top directory. With no
argument, the current top entry is removed. An argument of the form +n identifies a stack entry
by counting from the left of the list shown by the dirs command, starting with zero. An argument
of the form n counts from the right. If the PUSHD_MINUS option is set, the meanings of +
and in this context are swapped.
print [ bnrslzpNDPoOicm ] [ un ] [ R [ en ]] [ arg ... ]
With no flags or with flag , the arguments are printed on the standard output as described by
echo, with the following differences: the escape sequence \Mx metafies the character x (sets the
highest bit), \Cx produces a control character (\C@ and \C? give the characters NUL and
delete), and \E is a synonym for \e. Finally, if not in an escape sequence, \ escapes the following character and is not printed.
r

Ignore the escape conventions of echo.

Emulate the BSD echo command, which does not process escape sequences unless the e
flag is given. The n flag suppresses the trailing newline. Only the e and n flags are
recognized after R; all other arguments and options are printed.

Recognize all the escape sequences defined for the bindkey command, see zshzle(1).

Take the first argument as a pattern (should be quoted), and remove it from the argument
list together with subsequent arguments that do not match this pattern.

Place the results in the history list instead of on the standard output.

Do not add a newline to the output.

Print the arguments separated by newlines instead of spaces.

Print the arguments separated and terminated by nulls.

Print the arguments sorted in ascending order.

Print the arguments sorted in descending order.

If given together with o or O, sorting is performed caseindependently.

Print the arguments in columns.

un

Print the arguments to file descriptor n.

Print the arguments to the input of the coprocess.

Push the arguments onto the editing buffer stack, separated by spaces.

Treat the arguments as directory names, replacing prefixes with expressions, as


appropriate.

Perform prompt expansion (see zshmisc(1)).

pushd [ arg ]
pushd old new
pushd {+}n

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

Change the current directory, and push the old current directory onto the directory stack. In the
first form, change the current directory to arg. If arg is not specified, change to the second directory on the stack (that is, exchange the top two entries), or change to $HOME if the
PUSHD_TO_HOME option is set or if there is only one entry on the stack. Otherwise, arg is
interpreted as it would be by cd. The meaning of old and new in the second form is also the same
as for cd.
The third form of pushd changes directory by rotating the directory list. An argument of the form
+n identifies a stack entry by counting from the left of the list shown by the dirs command, starting with zero. An argument of the form n counts from the right. If the PUSHD_MINUS
option is set, the meanings of + and in this context are swapped.
If the option PUSHD_SILENT is not set, the directory stack will be printed after a pushd is performed.
pushln [ arg ... ]
Equivalent to print nz.
pwd [ rLP ]
Print the absolute pathname of the current working directory. If the r or the P flag is specified,
or the CHASE_LINKS option is set and the L flag is not given, the printed path will not contain
symbolic links.
r

Same as fc e .

read [ rzpqAclneEt ] [ k [ num ] ]


[ un ] [ name[?prompt] ] [ name ... ]
Read one line and break it into fields using the characters in $IFS as separators, except as noted
below. The first field is assigned to the first name, the second field to the second name, etc., with
leftover fields assigned to the last name. If name is omitted then REPLY is used for scalars and
reply for arrays.
r

Raw mode: a \ at the end of a line does not signify line continuation and backslashes in
the line dont quote the following character and are not removed.

Read only one character from the terminal and set name to y if this character was y or
Y and to n otherwise. With this flag set the return value is zero only if the character
was y or Y. Note that this always reads from the terminal, even if used with the p or
u or z flags or with redirected input. This option may also be used within zle widgets.

k [ num ]
Read only one (or num) characters. All are assigned to the first name, without word splitting. This flag is ignored when q is present. Input is read from the terminal unless one
of u or p is present. This option may also be used within zle widgets.
Note that num must be in the argument word that follows k, not in the same word. See
u.
z

e
E
A
c
l

zsh 4.0.4

Read one entry from the editor buffer stack and assign it to the first name, without word
splitting. Text is pushed onto the stack with print z or with pushline from the line
editor (see zshzle(1)). This flag is ignored when the k or q flags are present.
The input read is printed (echoed) to the standard output. If the e flag is used, no input
is assigned to the parameters.
The first name is taken as the name of an array and all words are assigned to it.
These flags are allowed only if called inside a function used for completion (specified
with the K flag to compctl). If the c flag is given, the words of the current command
are read. If the l flag is given, the whole line is assigned as a scalar. If both flags are

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

present, l is used and c is ignored.


n

Together with c, the number of the word the cursor is on is read. With l, the index of
the character the cursor is on is read. Note that the command name is word number 1, not
word 0, and that when the cursor is at the end of the line, its character index is the length
of the line plus one.

un

Input is read from file descriptor n, where n is a single digit and must not be separated
from u by any whitespace.

Input is read from the coprocess.

Test if input is available before attempting to read; if none is, return status 1 and do not
set any variables. This is not available when reading from the editor buffer with z, when
called from within completion with c or l, with q which clears the input queue before
reading, or within zle where other mechanisms should be used to test for input.
Note that read does not attempt to alter the input processing mode. The default mode is
canonical input, in which an entire line is read at a time, so usually read t will not read
anything until an entire line has been typed. However, when reading from the terminal
with k this is automatically handled; note that only availability of the first character is
tested, so that e.g. read t k 2 can still block on the second character. If the first argument contains a ?, the remainder of this word is used as a prompt on standard error
when the shell is interactive.

The value (exit status) of read is 1 when an endoffile is encountered, or when c or l is present
and the command is not called from a compctl function, or as described for q. Otherwise the
value is 0.
The behavior of some combinations of the k, p, q, u and z flags is undefined. Presently q
cancels all the others, p cancels u, k cancels z, and otherwise z cancels both p and u.
The c or l flags cancel any and all of kpquz.
readonly
Same as typeset r.
rehash Same as hash r.
return [ n ]
Causes a shell function or . script to return to the invoking script with the return status specified by
n. If n is omitted, the return status is that of the last command executed.
If return was executed from a trap in a TRAPNAL function, the effect is different for zero and
nonzero return status. With zero status (or after an implicit return at the end of the trap), the shell
will return to whatever it was previously processing; with a nonzero status, the shell will behave
as interrupted except that the return status of the trap is retained. Note that the numeric value of
the signal which caused the trap is passed as the first argument, so the statement return
$((128+$1)) will return the same status as if the signal had not been trapped.
sched

See the section The zsh/sched Module in zshmodules(1).

set [ {+}options {+}o option_name ] ... [ {+}A [ name ] ] [ arg ... ]


Set the options for the shell and/or set the positional parameters, or declare and set an array. If the
s option is given, it causes the specified arguments to be sorted before assigning them to the positional parameters (or to the array name if A is used). With +s sort arguments in descending
order. For the meaning of the other flags, see zshoptions(1). Flags may be specified by name
using the o option.
If the A flag is specified, name is set to an array containing the given args. if +A is used and
name is an array, the given arguments will replace the initial elements of that array; if no name is
specified, all arrays are printed. Otherwise the positional parameters are set. If no arguments are

zsh 4.0.4

Last change: October 26, 2001

10

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

given, then the names and values of all parameters are printed on the standard output. If the only
argument is +, the names of all parameters are printed.
setcap See the section The zsh/cap Module in zshmodules(1).
setopt [ {+}options {+}o option_name ] [ name ... ]
Set the options for the shell. All options specified either with flags or by name are set. If no arguments are supplied, the names of all options currently set are printed. If the m flag is given the
arguments are taken as patterns (which should be quoted to protect them from filename expansion), and all options with names matching these patterns are set.
shift [ n ] [ name ... ]
The positional parameters ${n+1} ... are renamed to $1 ..., where n is an arithmetic expression that
defaults to 1. If any names are given then the arrays with these names are shifted instead of the
positional parameters.
source file [ arg ... ]
Same as ., except that the current directory is always searched and is always searched first, before
directories in $path.
stat

See the section The zsh/stat Module in zshmodules(1).

suspend [ f ]
Suspend the execution of the shell (send it a SIGTSTP) until it receives a SIGCONT. Unless the
f option is given, this will refuse to suspend a login shell.
test [ arg ... ]
[ [ arg ... ] ]
Like the system version of test. Added for compatibility; use conditional expressions instead (see
the section Conditional Expressions).
times

Print the accumulated user and system times for the shell and for processes run from the shell.

trap [ arg [ sig ... ] ]


arg is a series of commands (usually quoted to protect it from immediate evaluation by the shell)
to be read and executed when the shell receives sig. Each sig can be given as a number or as the
name of a signal. If arg is , then all traps sig are reset to their default values. If arg is the
empty string, then this signal is ignored by the shell and by the commands it invokes.
If sig is ZERR then arg will be executed after each command with a nonzero exit status. If sig is
DEBUG then arg will be executed after each command. If sig is 0 or EXIT and the trap statement is executed inside the body of a function, then the command arg is executed after the function completes. If sig is 0 or EXIT and the trap statement is not executed inside the body of a
function, then the command arg is executed when the shell terminates.
The trap command with no arguments prints a list of commands associated with each signal.
Note that traps defined with the trap builtin are slightly different from those defined as TRAPNAL () { ... }, as the latter have their own function environment (line numbers, local variables,
etc.) while the former use the environment of the command in which they were called. For example,
trap print $LINENO DEBUG
will print the line number of a command executed after it has run, while
TRAPDEBUG() { print $LINENO; }
will always print the number zero.
true [ arg ... ]
Do nothing and return an exit code of 0.
ttyctl fu

zsh 4.0.4

Last change: October 26, 2001

11

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHBUILTINS ( 1 )

The f option freezes the tty, and u unfreezes it. When the tty is frozen, no changes made to the
tty settings by external programs will be honored by the shell, except for changes in the size of the
screen; the shell will simply reset the settings to their previous values as soon as each command
exits or is suspended. Thus, stty and similar programs have no effect when the tty is frozen.
Without options it reports whether the terminal is frozen or not.
type [ wfpams ] name ...
Equivalent to whence v.
typeset [ {+}AEFLRUZafghilrtuxm [n]] [ name[=value] ... ]
typeset T [ {+}LRUZrux ] SCALAR[=value] array
Set or display attributes and values for shell parameters.
A parameter is created for each name that does not already refer to one. When inside a function, a
new parameter is created for every name (even those that already exist), and is unset again when
the function completes. See Local Parameters in zshparam(1). The same rules apply to special
shell parameters, which retain their special attributes when made local.
For each name=value assignment, the parameter name is set to value. Note that arrays currently
cannot be assigned in typeset expressions, only scalars and integers.
For each remaining name that refers to a parameter that is set, the name and value of the parameter
are printed in the form of an assignment. Nothing is printed for newlycreated parameters, or
when any attribute flags listed below are given along with the name. Using + instead of minus to
introduce an attribute turns it off.
If the T option is given, exactly two (or zero) name arguments must be present. They represent a
scalar and an array (in that order) that will be tied together in the manner of $PATH and $path.
In other words, an array present in the latter variable appears as a scalar with the elements of the
array joined by colons in the former. Only the scalar may have an initial value. Both the scalar
and the array may otherwise be manipulated as normal. If one is unset, the other will automatically be unset too. There is no way of untying the variables without unsetting them, or converting
the type of one of them with another typeset command; +T does not work, assigning an array to
SCALAR is an error, and assigning a scalar to array sets it to be a singleelement array. Note that
both typeset xT ... and export T ... work, but only the scalar will be marked for export.
The g (global) flag is treated specially: it means that any resulting parameter will not be restricted
to local scope. Note that this does not necessarily mean that the parameter will be global, as the
flag will apply to any existing parameter (even if unset) from an enclosing function. This flag does
not affect the parameter after creation, hence it has no effect when listing existing parameters, nor
does the flag +g have any effect except in combination with m (see below).
If no name is present, the names and values of all parameters are printed. In this case the attribute
flags restrict the display to only those parameters that have the specified attributes, and using +
rather than to introduce the flag suppresses printing of the values of parameters when there is
no parameter name. Also, if the last option is the word +, then names are printed but values are
not.
If the m flag is given the name arguments are taken as patterns (which should be quoted). With
no attribute flags, all parameters (or functions with the f flag) with matching names are printed.
Note that m is ignored if no patterns are given. If the +g flag is combined with m, a new local
parameter is created for every matching parameter that is not already local. Otherwise m applies
all other flags or assignments to the existing parameters. Except when assignments are made with
name=value, using +m forces the matching parameters to be printed, even inside a function.
If no attribute flags are given and either no m flag is present or the +m form was used, each
parameter name printed is preceded by a list of the attributes of that parameter (array, association, exported, integer, readonly). If +m is used with attribute flags, and all those flags are introduced with +, the matching parameter names are printed but their values are not.

zsh 4.0.4

Last change: October 26, 2001

12

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

The following attribute flags may be specified:

zsh 4.0.4

The names refer to associative array parameters; see Array Parameters in zshparam(1).

Left justify and remove leading blanks from value. If n is nonzero, it defines the width of
the field; otherwise it is determined by the width of the value of the first assignment.
When the parameter is expanded, it is filled on the right with blanks or truncated if necessary to fit the field. Leading zeros are removed if the Z flag is also set.

Right justify and fill with leading blanks. If n is nonzero if defines the width of the field;
otherwise it is determined by the width of the value of the first assignment. When the
parameter is expanded, the field is left filled with blanks or truncated from the end.

For arrays (but not for associative arrays), keep only the first occurrence of each duplicated value. This may also be set for colonseparated special parameters like PATH or
FIGNORE, etc. This flag has a different meaning when used with f; see below.

Right justify and fill with leading zeros if the first nonblank character is a digit and the
L flag has not been set. If n is nonzero it defines the width of the field; otherwise it is
determined by the width of the value of the first assignment.

The names refer to array parameters. An array parameter may be created this way, but it
may not be assigned to in the typeset statement. When displaying, both normal and associative arrays are shown.

The names refer to functions rather than parameters. No assignments can be made, and
the only other valid flags are t, u and U. The flag t turns on execution tracing for
this function. The u and U flags cause the function to be marked for autoloading; U
also causes alias expansion to be suppressed when the function is loaded. The fpath
parameter will be searched to find the function definition when the function is first referenced; see the section Functions.

Hide: only useful for special parameters (those marked <S> in the table in
zshparams(1)), and for local parameters with the same name as a special parameter,
though harmless for others. A special parameter with this attribute will not retain its special effect when made local. Thus after typeset h PATH, a function containing
typeset PATH will create an ordinary local parameter without the usual behaviour of
PATH. Alternatively, the local parameter may itself be given this attribute; hence inside
a function typeset h PATH creates an ordinary local parameter and the special PATH
parameter is not altered in any way. It is also possible to create a local parameter using
typeset +h special, where the local copy of special will retain its special properties
regardless of having the h attribute. Global special parameters loaded from shell
modules (currently those in zsh/mapfile and zsh/parameter) are automatically given the
h attribute to avoid name clashes.

Hide value: specifies that typeset will not display the value of the parameter when listing
parameters; the display for such parameters is always as if the + flag had been given.
Use of the parameter is in other respects normal, and the option does not apply if the
parameter is specified by name, or by pattern with the m option. This is on by default
for the parameters in the zsh/parameter and zsh/mapfile modules. Note, however, that
unlike the h flag this is also useful for nonspecial parameters.

Use an internal integer representation. If n is nonzero it defines the output arithmetic


base, otherwise it is determined by the first assignment.

Use an internal doubleprecision floating point representation. On output the variable


will be converted to scientific notation. If n is nonzero it defines the number of
significant figures to display; the default is ten.

Use an internal doubleprecision floating point representation. On output the variable


will be converted to fixedpoint decimal notation. If n is nonzero it defines the number of

Last change: October 26, 2001

13

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

digits to display after the decimal point; the default is ten.


l

Convert the result to lower case whenever the parameter is expanded. The value is not
converted when assigned.

The given names are marked readonly.

Tags the named parameters. Tags have no special meaning to the shell. This flag has a
different meaning when used with f; see above.

Convert the result to upper case whenever the parameter is expanded. The value is not
converted when assigned. This flag has a different meaning when used with f; see
above.

Mark for automatic export to the environment of subsequently executed commands. If


the option GLOBAL_EXPORT is set, this implies the option g, unless +g is also explicitly given; in other words the parameter is not made local to the enclosing function. This
is for compatibility with previous versions of zsh.

ulimit [ SHacdflmnpstv [ limit ] ... ]


Set or display resource limits of the shell and the processes started by the shell. The value of limit
can be a number in the unit specified below or the value unlimited. If the H flag is given use
hard limits instead of soft limits. If the S flag is given together with the H flag set both hard and
soft limits. If no options are used, the file size limit (f) is assumed. If limit is omitted the current
value of the specified resources are printed. When more than one resource values are printed the
limit name and unit is printed before each value.
a
c
d
f
l
m
n
s
t
u
v

Lists all of the current resource limits.


512byte blocks on the size of core dumps.
Kbytes on the size of the data segment.
512byte blocks on the size of files written.
Kbytes on the size of lockedin memory.
Kbytes on the size of physical memory.
open file descriptors.
Kbytes on the size of the stack.
CPU seconds to be used.
processes available to the user.
Kbytes on the size of virtual memory.

umask [ S ] [ mask ]
The umask is set to mask. mask can be either an octal number or a symbolic value as described in
chmod(1). If mask is omitted, the current value is printed. The S option causes the mask to be
printed as a symbolic value. Otherwise, the mask is printed as an octal number. Note that in the
symbolic form the permissions you specify are those which are to be allowed (not denied) to the
users specified.
unalias Same as unhash a.
unfunction
Same as unhash f.
unhash [ adfm ] name ...
Remove the element named name from an internal hash table. The default is remove elements
from the command hash table. The a option causes unhash to remove aliases. The f option
causes unhash to remove shell functions. The d options causes unhash to remove named directories. If the m flag is given the arguments are taken as patterns (should be quoted) and all elements of the corresponding hash table with matching names will be removed.
unlimit [ hs ] resource ...
The resource limit for each resource is set to the hard limit. If the h flag is given and the shell
has appropriate privileges, the hard resource limit for each resource is removed. The resources of

zsh 4.0.4

Last change: October 26, 2001

14

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

the shell process are only changed if the s flag is given.


unset [ fm ] name ...
Each named parameter is unset. Local parameters remain local even if unset; they appear unset
within scope, but the previous value will still reappear when the scope ends.
Individual elements of associative array parameters may be unset by using subscript syntax on
name, which should be quoted (or the entire command prefixed with noglob) to protect the subscript from filename generation.
If the m flag is specified the arguments are taken as patterns (should be quoted) and all parameters with matching names are unset. Note that this cannot be used when unsetting associative
array elements, as the subscript will be treated as part of the pattern.
unset f is equivalent to unfunction.
unsetopt [ {+}options {+}o option_name ] [ name ... ]
Unset the options for the shell. All options specified either with flags or by name are unset. If no
arguments are supplied, the names of all options currently unset are printed. If the m flag is
given the arguments are taken as patterns (which should be quoted to preserve them from being
interpreted as glob patterns), and all options with names matching these patterns are unset.
vared

See the section Zle Builtins in zshzle(1).

wait [ job ... ]


Wait for the specified jobs or processes. If job is not given then all currently active child processes
are waited for. Each job can be either a job specification or the process ID of a job in the job table.
The exit status from this command is that of the job waited for.
whence [ vcwfpams ] name ...
For each name, indicate how it would be interpreted if used as a command name.
v

Produce a more verbose report.

Print the results in a cshlike format. This takes precedence over v.

For each name, print name: word where word is one of alias, builtin, command, function, hashed, reserved or none, according as name corresponds to an alias, a builtin
command, an external command, a shell function, a command defined with the hash builtin, a reserved word, or is not recognised. This takes precedence over v and c.

Causes the contents of a shell function to be displayed, which would otherwise not happen unless the c flag were used.

Do a path search for name even if it is an alias, reserved word, shell function or builtin.

Do a search for all occurrences of name throughout the command path. Normally only
the first occurrence is printed.

The arguments are taken as patterns (should be quoted), and the information is displayed
for each command matching one of these patterns.

If a pathname contains symlinks, print the symlinkfree pathname as well.

where [ wpms ] name ...


Equivalent to whence ca.
which [ wpams ] name ...
Equivalent to whence c.
zcompile [ U ] [ z k ] [ R M ] file [ name ... ]
zcompile ca [ m ] [ R M ] file [ name ... ]
zcompile t file [ name ... ]
This builtin command can be used to compile functions or scripts, storing the compiled form in a
file, and to examine files containing the compiled form. This allows faster autoloading of

zsh 4.0.4

Last change: October 26, 2001

15

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHBUILTINS ( 1 )

functions and execution of scripts by avoiding parsing of the text when the files are read.
The first form (without the c, a or t options) creates a compiled file. If only the file argument is
given, the output file has the name file.zwc and will be placed in the same directory as the file.
The shell will load the compiled file instead of the normal function file when the function is autoloaded; see the section Autoloading Functions in zshfunc(1) for a description of how autoloaded
functions are searched. The extension .zwc stands for zsh word code.
If there is at least one name argument, all the named files are compiled into the output file given as
the first argument. If file does not end in .zwc, this extension is automatically appended. Files
containing multiple compiled functions are called digest files, and are intended to be used as elements of the FPATH/fpath special array.
The second form, with the c or a options, writes the compiled definitions for all the named functions into file. For c, the names must be functions currently defined in the shell, not those marked
for autoloading. Undefined functions that are marked for autoloading may be written by using the
a option, in which case the fpath is searched and the contents of the definition files for those
functions, if found, are compiled into file. If both c and a are given, names of both defined functions and functions marked for autoloading may be given. In either case, the functions in files
written with the c or a option will be autoloaded as if the KSH_AUTOLOAD option were
unset.
The reason for handling loaded and notyetloaded functions with different options is that some
definition files for autoloading define multiple functions, including the function with the same
name as the file, and, at the end, call that function. In such cases the output of zcompile c does
not include the additional functions defined in the file, and any other initialization code in the file
is lost. Using zcompile a captures all this extra information.
If the m option is combined with c or a, the names are used as patterns and all functions whose
names match one of these patterns will be written. If no name is given, the definitions of all functions currently defined or marked as autoloaded will be written.
The third form, with the t option, examines an existing compiled file. Without further arguments,
the names of the original files compiled into it are listed. The first line of output shows the version
of the shell which compiled the file and how the file will be used (i.e. by reading it directly or by
mapping it into memory). With arguments, nothing is output and the return value is set to zero if
definitions for all names were found in the compiled file, and nonzero if the definition for at least
one name was not found.
Other options:
U

Aliases are not expanded when compiling the named files.

When the compiled file is read, its contents are copied into the shells memory, rather
than memorymapped (see M). This happens automatically on systems that do not support memory mapping.
When compiling scripts instead of autoloadable functions, it is often desirable to use this
option; otherwise the whole file, including the code to define functions which have
already been defined, will remain mapped, consequently wasting memory.

k
z

zsh 4.0.4

The compiled file is mapped into the shells memory when read. This is done in such a
way that multiple instances of the shell running on the same host will share this mapped
file. If neither R nor M is given, the zcompile builtin decides what to do based on the
size of the compiled file.
These options are used when the compiled file contains functions which are to be autoloaded. If z is given, the function will be autoloaded as if the KSH_AUTOLOAD
option is not set, even if it is set at the time the compiled file is read, while if the k is
given, the function will be loaded as if KSH_AUTOLOAD is set. If neither of these

Last change: October 26, 2001

16

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHBUILTINS ( 1 )

options is given, the function will be loaded as determined by the setting of the
KSH_AUTOLOAD option at the time the compiled file is read.
These options may also appear as many times as necessary between the listed names to
specify the loading style of all following functions, up to the next k or z.
The created file always contains two versions of the compiled format, one for bigendian
machines and one for smallendian machines. The upshot of this is that the compiled file
is machine independent and if it is read or mapped, only one half of the file is actually
used (and mapped).
zformat
See the section The zsh/zutil Module in zshmodules(1).
zftp

See the section The zsh/zftp Module in zshmodules(1).

zle

See the section Zle Builtins in zshzle(1).

zmodload [ dL ] [ ... ]
zmodload e [ A ] [ ... ]
zmodload [ a [ bcpf [ I ] ] ] [ iL ] ...
zmodload u [ abcdpf [ I ] ] [ iL ] ...
zmodload A [ L ] [ modalias[=module] ... ]
zmodload R modalias ...
Performs operations relating to zshs loadable modules. Loading of modules while the shell is
running (dynamical loading) is not available on all operating systems, or on all installations on a
particular operating system, although the zmodload command itself is always available and can be
used to manipulate modules built into versions of the shell executable without dynamical loading.
Without arguments the names of all currently loaded binary modules are printed. The L option
causes this list to be in the form of a series of zmodload commands. Forms with arguments are:
zmodload [ i ] name ...
zmodload u [ i ] name ...
In the simplest case, zmodload loads a binary module. The module must be in a file with
a name consisting of the specified name followed by a standard suffix, usually .so (.sl
on HPUX). If the module to be loaded is already loaded and the i option is given, the
duplicate module is ignored. Otherwise zmodload prints an error message.
The named module is searched for in the same way a command is, using $module_path
instead of $path. However, the path search is performed even when the module name
contains a /, which it usually does. There is no way to prevent the path search.
With u, zmodload unloads modules. The same name must be given that was given
when the module was loaded, but it is not necessary for the module to exist in the filesystem. The i option suppresses the error if the module is already unloaded (or was never
loaded).
Each module has a boot and a cleanup function. The module will not be loaded if its boot
function fails. Similarly a module can only be unloaded if its cleanup function runs successfully.
zmodload d [ L ] [ name ]
zmodload d name dep ...
zmodload ud name [ dep ... ]
The d option can be used to specify module dependencies. The modules named in the
second and subsequent arguments will be loaded before the module named in the first
argument.

zsh 4.0.4

Last change: October 26, 2001

17

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHBUILTINS ( 1 )

With d and one argument, all dependencies for that module are listed. With d and no
arguments, all module dependencies are listed. This listing is by default in a
Makefilelike format. The L option changes this format to a list of zmodload d commands.
If d and u are both used, dependencies are removed. If only one argument is given, all
dependencies for that module are removed.
zmodload ab [ L ]
zmodload ab [ i ] name [ builtin ... ]
zmodload ub [ i ] builtin ...
The ab option defines autoloaded builtins. It defines the specified builtins. When any
of those builtins is called, the module specified in the first argument is loaded. If only the
name is given, one builtin is defined, with the same name as the module. i suppresses
the error if the builtin is already defined or autoloaded, regardless of which module it
came from.
With ab and no arguments, all autoloaded builtins are listed, with the module name (if
different) shown in parentheses after the builtin name. The L option changes this format
to a list of zmodload a commands.
If b is used together with the u option, it removes builtins previously defined with ab.
This is only possible if the builtin is not yet loaded. i suppresses the error if the builtin
is already removed (or never existed).
zmodload ac [ IL ]
zmodload ac [ iI ] name [ cond ... ]
zmodload uc [ iI ] cond ...
The ac option is used to define autoloaded condition codes. The cond strings give the
names of the conditions defined by the module. The optional I option is used to define
infix condition names. Without this option prefix condition names are defined.
If given no condition names, all defined names are listed (as a series of zmodload commands if the L option is given).
The uc option removes definitions for autoloaded conditions.
zmodload ap [ L ]
zmodload ap [ i ] name [ parameter ... ]
zmodload up [ i ] parameter ...
The p option is like the b and c options, but makes zmodload work on autoloaded
parameters instead.
zmodload af [ L ]
zmodload af [ i ] name [ function ... ]
zmodload uf [ i ] function ...
The f option is like the b, p, and c options, but makes zmodload work on autoloaded
math functions instead.
zmodload a [ L ]
zmodload a [ i ] name [ builtin ... ]
zmodload ua [ i ] builtin ...
Equivalent to ab and ub.
zmodload e [ A ] [ string ... ]
The e option without arguments lists all loaded modules; if the A option is also given,
module aliases corresponding to loaded modules are also shown. With arguments only
the return status is set to zero if all strings given as arguments are names of loaded
modules and to one if at least on string is not the name of a loaded module. This can be
used to test for the availability of things implemented by modules. In this case, any

zsh 4.0.4

Last change: October 26, 2001

18

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHBUILTINS ( 1 )

aliases are automatically resolved and the A flag is not used.


zmodload A [ L ] [ modalias[=module] ... ]
For each argument, if both modalias and module are given, define modalias to be an alias
for the module module. If the module modalias is ever subsequently requested, either via
a call to zmodload or implicitly, the shell will attempt to load module instead. If module
is not given, show the definition of modalias. If no arguments are given, list all defined
module aliases. When listing, if the L flag was also given, list the definition as a
zmodload command to recreate the alias.
The existence of aliases for modules is completely independent of whether the name
resolved is actually loaded as a module: while the alias exists, loading and unloading the
module under any alias has exactly the same effect as using the resolved name, and does
not affect the connection between the alias and the resolved name which can be removed
either by zmodload R or by redefining the alias. Chains of aliases (i.e. where the first
resolved name is itself an alias) are valid so long as these are not circular. As the aliases
take the same format as module names, they may include path separators: in this case,
there is no requirement for any part of the path named to exist as the alias will be resolved
first. For example, any/old/alias is always a valid alias.
Dependencies added to aliased modules are actually added to the resolved module; these
remain if the alias is removed. It is valid to create an alias whose name is one of the standard shell modules and which resolves to a different module. However, if a module has
dependencies, it will not be possible to use the module name as an alias as the module
will already be marked as a loadable module in its own right.
Apart from the above, aliases can be used in the zmodload command anywhere module
names are required. However, aliases will not be shown in lists of loaded modules with a
bare zmodload.
zmodload R modalias ...
For each modalias argument that was previously defined as a module alias via zmodload
A, delete the alias. If any was not defined, an error is caused and the remainder of the
line is ignored.
Note that zsh makes no distinction between modules that were linked into the shell and modules
that are loaded dynamically. In both cases this builtin command has to be used to make available
the builtins and other things defined by modules (unless the module is autoloaded on these
definitions). This is true even for systems that dont support dynamic loading of modules.
zparseopts
See the section The zsh/zutil Module in zshmodules(1).
zprof

See the section The zsh/zprof Module in zshmodules(1).

zpty

See the section The zsh/zpty Module in zshmodules(1).

zregexparse
See the section The zsh/zutil Module in zshmodules(1).
zstyle

zsh 4.0.4

See the section The zsh/zutil Module in zshmodules(1).

Last change: October 26, 2001

19

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZLE ( 1 )

NAME

zshzle zsh command line editor


DESCRIPTION

If the ZLE option is set (which it is by default in interactive shells) and the shell input is attached to the terminal, the user is able to edit command lines.
There are two display modes. The first, multiline mode, is the default. It only works if the TERM parameter is set to a valid terminal type that can move the cursor up. The second, single line mode, is used if
TERM is invalid or incapable of moving the cursor up, or if the SINGLE_LINE_ZLE option is set. This
mode is similar to ksh, and uses no termcap sequences. If TERM is "emacs", the ZLE option will be unset
by default.
The parameters BAUD, COLUMNS, and LINES are also used by the line editor. See Parameters Used
By The Shell in zshparam(1).
KEYMAPS

A keymap in ZLE contains a set of bindings between key sequences and ZLE commands. The empty key
sequence cannot be bound.
There can be any number of keymaps at any time, and each keymap has one or more names. If all of a
keymaps names are deleted, it disappears. bindkey can be used to manipulate keymap names.
Initially, there are four keymaps:
emacs
viins
vicmd
.safe

EMACS emulation
vi emulation insert mode
vi emulation command mode
fallback keymap

The .safe keymap is special. It can never be altered, and the name can never be removed. However, it
can be linked to other names, which can be removed. In the future other special keymaps may be added;
users should avoid using names beginning with . for their own keymaps.
In addition to these four names, either emacs or viins is also linked to the name main. If one of the
VISUAL or EDITOR environment variables contain the string vi when the shell starts up then it will be
viins, otherwise it will be emacs. bindkeys e and v options provide a convenient way to override
this default choice.
When the editor starts up, it will select the main keymap. If that keymap doesnt exist, it will use .safe
instead.
In the .safe keymap, each single key is bound to selfinsert, except for J (line feed) and M (return)
which are bound to acceptline. This is deliberately not pleasant to use; if you are using it, it means you
deleted the main keymap, and you should put it back.
Reading Commands

When ZLE is reading a command from the terminal, it may read a sequence that is bound to some command and is also a prefix of a longer bound string. In this case ZLE will wait a certain time to see if more
characters are typed, and if not (or they dont match any longer string) it will execute the binding. This
timeout is defined by the KEYTIMEOUT parameter; its default is 0.4 sec. There is no timeout if the
prefix string is not itself bound to a command.
As well as ZLE commands, key sequences can be bound to other strings, by using bindkey s. When
such a sequence is read, the replacement string is pushed back as input, and the command reading process
starts again using these fake keystrokes. This input can itself invoke further replacement strings, but in
order to detect loops the process will be stopped if there are twenty such replacements without a real command being read.
ZLE BUILTINS

The ZLE module contains three related builtin commands. The bindkey command manipulates keymaps
and key bindings; the vared command invokes ZLE on the value of a shell parameter; and the zle

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZLE ( 1 )

command manipulates editing widgets and allows command line access to ZLE commands from within
shell functions.
bindkey [ options ] l
bindkey [ options ] d
bindkey [ options ] D keymap ...
bindkey [ options ] A oldkeymap newkeymap
bindkey [ options ] N newkeymap [ oldkeymap ]
bindkey [ options ] m
bindkey [ options ] r instring ...
bindkey [ options ] s instring outstring ...
bindkey [ options ] instring command ...
bindkey [ options ] [ instring ]
bindkeys options can be divided into three categories: keymap selection, operation selection, and
others. The keymap selection options are:
e

Selects keymap emacs, and also links it to main.

Selects keymap viins, and also links it to main.

Selects keymap vicmd.

The first nonoption argument is used as a keymap name, and does not otherwise count
as an argument.

If a keymap selection is required and none of the options above are used, the main keymap is
used. Some operations do not permit a keymap to be selected, namely:
l

List all existing keymap names. If the L option is also used, list in the form of bindkey
commands to create the keymaps.

Delete all existing keymaps and reset to the default state.

D keymap ...
Delete the named keymaps.
A oldkeymap newkeymap
Make the newkeymap name an alias for oldkeymap, so that both names refer to the
same keymap. The names have equal standing; if either is deleted, the other remains. If
there is already a keymap with the newkeymap name, it is deleted.
N newkeymap [ oldkeymap ]
Create a new keymap, named newkeymap. If a keymap already has that name, it is
deleted. If an oldkeymap name is given, the new keymap is initialized to be a duplicate
of it, otherwise the new keymap will be empty.
To use a newly created keymap, it should be linked to main. Hence the sequence of commands to
create and use a new keymap mymap initialized from the emacs keymap (which remains
unchanged) is:
bindkey N mymap emacs
bindkey A mymap main
Note that while bindkey A newmap main will work when newmap is emacs or viins, it will
not work for vicmd, as switching from vi insert to command mode becomes impossible.
The following operations act on the main keymap if no keymap selection option was given:
m

Add the builtin set of metakey bindings to the selected keymap. Only keys that are
unbound or bound to selfinsert are affected.

r instring ...
Unbind the specified instrings in the selected keymap. This is exactly equivalent to
binding the strings to undefinedkey.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHZLE ( 1 )

When R is also used, interpret the instrings as ranges.


When p is also used, the instrings specify prefixes. Any binding that has the given
instring as a prefix, not including the binding for the instring itself, if any, will be
removed. For example,
bindkey rpM viins [
will remove all bindings in the viinsert keymap beginning with an escape character
(probably cursor keys), but leave the binding for the escape character itself (probably
vicmdmode). This is incompatible with the option R.
s instring outstring ...
Bind each instring to each outstring. When instring is typed, outstring will be
pushed back and treated as input to the line editor. When R is also used, interpret the
instrings as ranges.
instring command ...
Bind each instring to each command. When R is used, interpret the instrings as
ranges.
[ instring ]
List key bindings. If an instring is specified, the binding of that string in the selected
keymap is displayed. Otherwise, all key bindings in the selected keymap are displayed.
(As a special case, if the e or v option is used alone, the keymap is not displayed the
implicit linking of keymaps is the only thing that happens.)
When the option p is used, the instring must be present. The listing shows all bindings
which have the given key sequence as a prefix, not including any bindings for the key
sequence itself.
When the L option is used, the list is in the form of bindkey commands to create the
key bindings.
When the R option is used as noted above, a valid range consists of two characters, with an optional
between them. All characters between the two specified, inclusive, are bound as specified.
For either instring or outstring, the following escape sequences are recognised:
\a
\b
\e, \E
\f
\n
\r
\t
\v
\NNN
\xNN
\M[]X
\C[]X
X

bell character
backspace
escape
form feed
linefeed (newline)
carriage return
horizontal tab
vertical tab
character code in octal
character code in hexadecimal
character with meta bit set
control character
control character

In all other cases, \ escapes the following character. Delete is written as ?. Note that \M? and \M?
are not the same, and that (unlike emacs), the bindings \MX and \eX are entirely distinct, although they
are initialized to the same bindings by bindkey m.
vared [ Aache ] [ p prompt ] [ r rprompt ] name
The value of the parameter name is loaded into the edit buffer, and the line editor is invoked. When the editor exits, name is set to the string value returned by the editor. When the c flag is given, the parameter is
created if it doesnt already exist. The a flag may be given with c to create an array parameter, or the A

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHZLE ( 1 )

flag to create an associative array. If the type of an existing parameter does not match the type to be
created, the parameter is unset and recreated.
If an array or array slice is being edited, separator characters as defined in $IFS will be shown quoted with
a backslash, as will backslashes themselves. Conversely, when the edited text is split into an array, a
backslash quotes an immediately following separator character or backslash; no other special handling of
backslashes, or any handling of quotes, is performed.
Individual elements of existing array or associative array parameters may be edited by using subscript syntax on name. New elements are created automatically, even without c.
If the p flag is given, the following string will be taken as the prompt to display at the left. If the r flag is
given, the following string gives the prompt to display at the right. If the h flag is specified, the history
can be accessed from ZLE. If the e flag is given, typing D (ControlD) on an empty line causes vared to
exit immediately with a nonzero return value.
zle l [ L a ] [ string ... ]
zle D widget ...
zle A oldwidget newwidget
zle N widget [ function ]
zle C widget completionwidget function
zle R [ c ] [ displaystring ] [ string ... ]
zle M string
zle U string
zle I
zle widget [ n num ] [ N ] args ...
zle
The zle builtin performs a number of different actions concerning ZLE. Which operation it performs
depends on its options:
l [ L a ]
List all existing userdefined widgets. If the L option is used, list in the form of zle commands to
create the widgets.
When combined with the a option, all widget names are listed, including the builtin ones. In this
case the L option is ignored.
If at least one string is given, nothing will be printed but the return status will be zero if all strings
are names of existing widgets (or of userdefined widgets if the a flag is not given) and nonzero
if at least one string is not a name of an defined widget.
D widget ...
Delete the named widgets.
A oldwidget newwidget
Make the newwidget name an alias for oldwidget, so that both names refer to the same widget.
The names have equal standing; if either is deleted, the other remains. If there is already a widget
with the newwidget name, it is deleted.
N widget [ function ]
Create a userdefined widget. If there is already a widget with the specified name, it is overwritten. When the new widget is invoked from within the editor, the specified shell function is called.
If no function name is specified, it defaults to the same name as the widget. For further information, see the section Widgets in zshzle(1).
C widget completionwidget function
Create a userdefined completion widget named widget. The completion widget will behave like
the builtin completionwidget whose name is given as completionwidget. To generate the completions, the shell function function will be called. For further information, see zshcompwid(1).
R [ c ] [ displaystring ] [ string ... ]

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHZLE ( 1 )

Redisplay the command line; this is to be called from within a userdefined widget to allow
changes to become visible. If a displaystring is given and not empty, this is shown in the status
line (immediately below the line being edited).
If the optional strings are given they are listed below the prompt in the same way as completion
lists are printed. If no strings are given but the c option is used such a list is cleared.
Note that this option is only useful for widgets that do not exit immediately after using it because
the strings displayed will be erased immediately after return from the widget.
This command can safely be called outside user defined widgets; if zle is active, the display will
be refreshed, while if zle is not active, the command has no effect. In this case there will usually
be no other arguments. The status is zero if zle was active, else one.
M string
As with the R option, the string will be displayed below the command line; unlike the R option,
the string will not be put into the status line but will instead be printed normally below the prompt.
This means that the string will still be displayed after the widget returns (until it is overwritten by
subsequent commands).
U string
This pushes the characters in the string onto the input stack of ZLE. After the widget currently
executed finishes ZLE will behave as if the characters in the string were typed by the user.
As ZLE uses a stack, if this option is used repeatedly the last string pushed onto the stack will be
processed first. However, the characters in each string will be processed in the order in which they
appear in the string.
I

Unusually, this option is only useful outside ordinary widget functions. It invalidates the current
zle display in preparation for output; usually this will be from a trap function. It has no effect if
zle is not active. When a trap exits, the shell checks to see if the display needs restoring, hence the
following will print output in such a way as not to disturb the line being edited:
TRAPUSR1() {
# Invalidate zle display
zle I
# Show output
print Hello
}
Note that there are better ways of manipulating the display from within zle widgets. In general,
the trap function may need to test whether zle is loaded before using this method; if it is not, there
is no point in loading it specially since the line editor will not be active.
The status is zero if zle was active, else one.

widget [ n num ] [ N ] args ...


Invoke the specified widget. This can only be done when ZLE is active; normally this will be
within a userdefined widget.
With the options n and N, the current numerical argument will be saved and then restored after
the call to widget; n num sets the numerical argument temporarily to num, while N sets it to
the default, i.e. as if there were none.
Any further arguments will be passed to the widget. If it is a shell function, these are passed down
as positional parameters; for builtin widgets it is up to the widget in question what it does with
them. Currently arguments are only handled by the incrementalsearch commands, the
historysearchforward and backward and the corresponding functions prefixed by vi, and by
universalargument. No error is flagged if the command does not use the arguments, or only
uses some of them.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZLE ( 1 )

The return status reflects the success or failure of the operation carried out by the widget, or if it is
a userdefined widget the return status of the shell function.
A nonzero return status causes the shell to beep when the widget exits, unless the BEEP options
was unset or the widget was called via the zle command. Thus if a user defined widget requires an
immediate beep, it should call the beep widget directly.
With no options and no arguments, only the return status will be set. It is zero if ZLE is currently active and
widgets could be invoked using this builtin command and nonzero if ZLE is not active.
WIDGETS

All actions in the editor are performed by widgets. A widgets job is simply to perform some small
action. The ZLE commands that key sequences in keymaps are bound to are in fact widgets. Widgets can
be userdefined or built in.
The standard widgets built in to ZLE are listed in Standard Widgets below. Other builtin widgets can be
defined by other modules (see zshmodules(1)). Each builtin widget has two names: its normal canonical
name, and the same name preceded by a .. The . name is special: it cant be rebound to a different
widget. This makes the widget available even when its usual name has been redefined.
Userdefined widgets are defined using zle N, and implemented as shell functions. When the widget is
executed, the corresponding shell function is executed, and can perform editing (or other) actions. It is
recommended that userdefined widgets should not have names starting with ..
USERDEFINED WIDGETS

Userdefined widgets, being implemented as shell functions, can execute any normal shell command. They
can also run other widgets (whether builtin or userdefined) using the zle builtin command. The standard
input of the function is closed to prevent external commands from unintentionally blocking ZLE by reading
from the terminal, but read k or read q can be used to read characters. Finally, they can examine and
edit the ZLE buffer being edited by reading and setting the special parameters described below.
These special parameters are always available in widget functions, but are not in any way special outside
ZLE. If they have some normal value outside ZLE, that value is temporarily inaccessible, but will return
when the widget function exits. These special parameters in fact have local scope, like parameters created
in a function using local.
Inside completion widgets and traps called while ZLE is active, these parameters are available readonly.
BUFFER (scalar)
The entire contents of the edit buffer. If it is written to, the cursor remains at the same offset,
unless that would put it outside the buffer.
BUFFERLINES
The number of screen lines needed for the edit buffer currently displayed on screen (i.e. without
any changes to the preceding parameters done after the last redisplay).
CURSOR (integer)
The offset of the cursor, within the edit buffer. This is in the range 0 to $#BUFFER, and is by
definition equal to $#LBUFFER. Attempts to move the cursor outside the buffer will result in the
cursor being moved to the appropriate end of the buffer.
HISTNO (integer)
The current history number.
KEYS (scalar)
The keys typed to invoke this widget, as a literal string.
LASTWIDGET (scalar)
The name of the last widget that was executed.
LBUFFER (scalar)
The part of the buffer that lies to the left of the cursor position. If it is assigned to, only that part of

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZLE ( 1 )

the buffer is replaced, and the cursor remains between the new $LBUFFER and the old
$RBUFFER.
MARK (integer)
Like CURSOR, but for the mark.
NUMERIC (integer)
The numeric argument. If no numeric argument was given, this parameter is unset. When this is
set inside a widget function, builtin widgets called with the zle builtin command will use the value
assigned. If it is unset inside a widget function, builtin widgets called behave as if no numeric
argument was given.
PENDING (integer)
The number of bytes pending for input, i.e. the number of bytes which have already been typed
and can immediately be read. On systems where the shell is not able to get this information, this
parameter will always have a value of zero.
PREBUFFER (scalar)
In a multiline input at the secondary prompt, this readonly parameter contains the contents of
the lines before the one the cursor is currently in.
RBUFFER (scalar)
The part of the buffer that lies to the right of the cursor position. If it is assigned to, only that part
of the buffer is replaced, and the cursor remains between the old $LBUFFER and the new
$RBUFFER.
WIDGET (scalar)
The name of the widget currently being executed.
STANDARD WIDGETS

The following is a list of all the standard widgets, and their default bindings in emacs mode, vi command
mode and vi insert mode (the emacs, vicmd and viins keymaps, respectively).
Note that cursor keys are bound to movement keys in all three keymaps; the shell assumes that the cursor
keys send the key sequences reported by the terminalhandling library (termcap or terminfo). The key
sequences shown in the list are those based on the VT100, common on many modern terminals, but in fact
these are not necessarily bound. In the case of the viins keymap, the initial escape character of the
sequences serves also to return to the vicmd keymap: whether this happens is determined by the KEYTIMEOUT parameter, see zshparam(1).
Movement

vibackwardblankword (unbound) (B) (unbound)


Move backward one word, where a word is defined as a series of nonblank characters.
backwardchar (B ESC[D) (unbound) (unbound)
Move backward one character.
vibackwardchar (unbound) (H h ?) (ESC[D)
Move backward one character, without changing lines.
backwardword (ESCB ESCb) (unbound) (unbound)
Move to the beginning of the previous word.
emacsbackwardword
Move to the beginning of the previous word.
vibackwardword (unbound) (b) (unbound)
Move to the beginning of the previous word, vistyle.
beginningofline (A) (unbound) (unbound)
Move to the beginning of the line. If already at the beginning of the line, move to the beginning of
the previous line, if any.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHZLE ( 1 )

vibeginningofline
Move to the beginning of the line, without changing lines.
endofline (E) (unbound) (unbound)
Move to the end of the line. If already at the end of the line, move to the end of the next line, if
any.
viendofline (unbound) ($) (unbound)
Move to the end of the line. If an argument is given to this command, the cursor will be moved to
the end of the line (argument 1) lines down.
viforwardblankword (unbound) (W) (unbound)
Move forward one word, where a word is defined as a series of nonblank characters.
viforwardblankwordend (unbound) (E) (unbound)
Move to the end of the current word, or, if at the end of the current word, to the end of the next
word, where a word is defined as a series of nonblank characters.
forwardchar (F ESC[C) (unbound) (unbound)
Move forward one character.
viforwardchar (unbound) (space l) (ESC[C)
Move forward one character.
vifindnextchar (XF) (f) (unbound)
Read a character from the keyboard, and move to the next occurrence of it in the line.
vifindnextcharskip (unbound) (t) (unbound)
Read a character from the keyboard, and move to the position just before the next occurrence of it
in the line.
vifindprevchar (unbound) (F) (unbound)
Read a character from the keyboard, and move to the previous occurrence of it in the line.
vifindprevcharskip (unbound) (T) (unbound)
Read a character from the keyboard, and move to the position just after the previous occurrence of
it in the line.
vifirstnonblank (unbound) () (unbound)
Move to the first nonblank character in the line.
viforwardword (unbound) (w) (unbound)
Move forward one word, vistyle.
forwardword (ESCF ESCf) (unbound) (unbound)
Move to the beginning of the next word. The editors idea of a word is specified with the WORDCHARS parameter.
emacsforwardword
Move to the end of the next word.
viforwardwordend (unbound) (e) (unbound)
Move to the end of the next word.
vigotocolumn (ESC) () (unbound)
Move to the column specified by the numeric argument.
vigotomark (unbound) () (unbound)
Move to the specified mark.
vigotomarkline (unbound) () (unbound)
Move to beginning of the line containing the specified mark.
virepeatfind (unbound) (;) (unbound)
Repeat the last vifind command.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZLE ( 1 )

virevrepeatfind (unbound) (,) (unbound)


Repeat the last vifind command in the opposite direction.
History Control

beginningofbufferorhistory (ESC<) (unbound) (unbound)


Move to the beginning of the buffer, or if already there, move to the first event in the history list.
beginningoflinehist
Move to the beginning of the line. If already at the beginning of the buffer, move to the previous
history line.
beginningofhistory
Move to the first event in the history list.
downlineorhistory (N ESC[B) (j) (ESC[B)
Move down a line in the buffer, or if already at the bottom line, move to the next event in the history list.
vidownlineorhistory (unbound) (+) (unbound)
Move down a line in the buffer, or if already at the bottom line, move to the next event in the history list. Then move to the first nonblank character on the line.
downlineorsearch
Move down a line in the buffer, or if already at the bottom line, search forward in the history for a
line beginning with the first word in the buffer.
If called from a function by the zle command with arguments, the first argument is taken as the
string for which to search, rather than the first word in the buffer.
downhistory (unbound) (N) (unbound)
Move to the next event in the history list.
historybeginningsearchbackward
Search backward in the history for a line beginning with the current line up to the cursor. This
leaves the cursor in its original position.
endofbufferorhistory (ESC>) (unbound) (unbound)
Move to the end of the buffer, or if already there, move to the last event in the history list.
endoflinehist
Move to the end of the line. If already at the end of the buffer, move to the next history line.
endofhistory
Move to the last event in the history list.
vifetchhistory (unbound) (G) (unbound)
Fetch the history line specified by the numeric argument. This defaults to the current history line
(i.e. the one that isnt history yet).
historyincrementalsearchbackward (R Xr) (unbound) (unbound)
Search backward incrementally for a specified string. The search is caseinsensitive if the search
string does not have uppercase letters and no numeric argument was given. The string may begin
with to anchor the search to the beginning of the line.
A restricted set of editing functions is available in the minibuffer. An interrupt signal, as defined
by the stty setting, will stop the search and go back to the original line. An undefined key will
have the same effect. The supported functions are:
backwarddeletechar,
vibackwarddeletechar, clearscreen, redisplay, quotedinsert, viquotedinsert,
acceptandhold,
acceptandinfernexthistory,
acceptline
and
acceptlineanddownhistory.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHZLE ( 1 )

magicspace just inserts a space. vicmdmode toggles between the main and vicmd keymaps;
the
main
keymap
(insert
mode)
will
be
selected
initially.
historyincrementalsearchbackward will get the next occurrence of the contents of the
minibuffer. historyincrementalsearchforward inverts the sense of the search.
virepeatsearch and virevrepeatsearch are similarly supported. The direction of the search
is indicated in the minibuffer.
Any multicharacter string that is not bound to one of the above functions will beep and interrupt
the search, leaving the last found line in the buffer. Any single character that is not bound to one of
the above functions, or selfinsert or selfinsertunmeta, will have the same effect but the function will be executed.
When called from a widget function by the zle command, the incremental search commands can
take a string argument. This will be treated as a string of keys, as for arguments to the bindkey
command, and used as initial input for the command. Any characters in the string which are
unused by the incremental search will be silently ignored. For example,
zle historyincrementalsearchbackward forceps
will search backwards for forceps, leaving the minibuffer containing the string forceps.
historyincrementalsearchforward (S Xs) (unbound) (unbound)
Search forward incrementally for a specified string. The search is caseinsensitive if the search
string does not have uppercase letters and no numeric argument was given. The string may begin
with to anchor the search to the beginning of the line. The functions available in the
minibuffer are the same as for historyincrementalsearchbackward.
historysearchbackward (ESCP ESCp) (unbound) (unbound)
Search backward in the history for a line beginning with the first word in the buffer.
If called from a function by the zle command with arguments, the first argument is taken as the
string for which to search, rather than the first word in the buffer.
vihistorysearchbackward (unbound) (/) (unbound)
Search backward in the history for a specified string. The string may begin with to anchor the
search to the beginning of the line.
A restricted set of editing functions is available in the minibuffer. An interrupt signal, as defined
by the stty setting, will stop the search. The functions available in the minibuffer are:
acceptline, backwarddeletechar, vibackwarddeletechar, backwardkillword,
vibackwardkillword, clearscreen, redisplay, quotedinsert and viquotedinsert.
vicmdmode is treated the same as acceptline, and magicspace is treated as a space. Any
other character that is not bound to selfinsert or selfinsertunmeta will beep and be ignored. If
the function is called from vi command mode, the bindings of the current insert mode will be used.
If called from a function by the zle command with arguments, the first argument is taken as the
string for which to search, rather than the first word in the buffer.
historysearchforward (ESCN ESCn) (unbound) (unbound)
Search forward in the history for a line beginning with the first word in the buffer.
If called from a function by the zle command with arguments, the first argument is taken as the
string for which to search, rather than the first word in the buffer.
vihistorysearchforward (unbound) (?) (unbound)
Search forward in the history for a specified string. The string may begin with to anchor the
search to the beginning of the line. The functions available in the minibuffer are the same as for
vihistorysearchbackward. Argument handling is also the same as for that command.
infernexthistory (XN) (unbound) (unbound)
Search in the history list for a line matching the current one and fetch the event following it.

zsh 4.0.4

Last change: October 26, 2001

10

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZLE ( 1 )

insertlastword (ESC_ ESC.) (unbound) (unbound)


Insert the last word from the previous history event at the cursor position. If a positive numeric
argument is given, insert that word from the end of the previous history event. If the argument is
zero or negative insert that word from the left (zero inserts the previous command word). Repeating this command replaces the word just inserted with the last word from the history event prior to
the one just used; numeric arguments can be used in the same way to pick a word from that event.
virepeatsearch (unbound) (n) (unbound)
Repeat the last vi history search.
virevrepeatsearch (unbound) (N) (unbound)
Repeat the last vi history search, but in reverse.
uplineorhistory (P ESC[A) (k) (ESC[A)
Move up a line in the buffer, or if already at the top line, move to the previous event in the history
list.
viuplineorhistory (unbound) () (unbound)
Move up a line in the buffer, or if already at the top line, move to the previous event in the history
list. Then move to the first nonblank character on the line.
uplineorsearch
Move up a line in the buffer, or if already at the top line, search backward in the history for a line
beginning with the first word in the buffer.
If called from a function by the zle command with arguments, the first argument is taken as the
string for which to search, rather than the first word in the buffer.
uphistory (unbound) (P) (unbound)
Move to the previous event in the history list.
historybeginningsearchforward
Search forward in the history for a line beginning with the current line up to the cursor. This
leaves the cursor in its original position.
Modifying Text

viaddeol (unbound) (A) (unbound)


Move to the end of the line and enter insert mode.
viaddnext (unbound) (a) (unbound)
Enter insert mode after the current cursor position, without changing lines.
backwarddeletechar (H ?) (unbound) (unbound)
Delete the character behind the cursor.
vibackwarddeletechar (unbound) (X) (H)
Delete the character behind the cursor, without changing lines. If in insert mode, this wont delete
past the point where insert mode was last entered.
backwarddeleteword
Delete the word behind the cursor.
backwardkillline
Kill from the beginning of the line to the cursor position.
backwardkillword (W ESCH ESC?) (unbound) (unbound)
Kill the word behind the cursor.
vibackwardkillword (unbound) (unbound) (W)
Kill the word behind the cursor, without going past the point where insert mode was last entered.
capitalizeword (ESCC ESCc) (unbound) (unbound)
Capitalize the current word and move past it.

zsh 4.0.4

Last change: October 26, 2001

11

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHZLE ( 1 )

vichange (unbound) (c) (unbound)


Read a movement command from the keyboard, and kill from the cursor position to the endpoint
of the movement. Then enter insert mode. If the command is vichange, change the current line.
vichangeeol (unbound) (C) (unbound)
Kill to the end of the line and enter insert mode.
vichangewholeline (unbound) (S) (unbound)
Kill the current line and enter insert mode.
copyregionaskill (ESCW ESCw) (unbound) (unbound)
Copy the area from the cursor to the mark to the kill buffer.
copyprevword (ESC_) (unbound) (unbound)
Duplicate the word to the left of the cursor.
copyprevshellword (ESC_) (unbound) (unbound)
Like copyprevword, but the word is found by using shell parsing, whereas copyprevword
looks for blanks. This makes a difference when the word is quoted and contains spaces.
videlete (unbound) (d) (unbound)
Read a movement command from the keyboard, and kill from the cursor position to the endpoint
of the movement. If the command is videlete, kill the current line.
deletechar
Delete the character under the cursor.
videletechar (unbound) (x) (unbound)
Delete the character under the cursor, without going past the end of the line.
deleteword
Delete the current word.
downcaseword (ESCL ESCl) (unbound) (unbound)
Convert the current word to all lowercase and move past it.
killword (ESCD ESCd) (unbound) (unbound)
Kill the current word.
gosmacstransposechars
Exchange the two characters behind the cursor.
viindent (unbound) (>) (unbound)
Indent a number of lines.
viinsert (unbound) (i) (unbound)
Enter insert mode.
viinsertbol (unbound) (I) (unbound)
Move to the first nonblank character on the line and enter insert mode.
vijoin (XJ) (J) (unbound)
Join the current line with the next one.
killline (K) (unbound) (unbound)
Kill from the cursor to the end of the line. If already on the end of the line, kill the newline character.
vikillline (unbound) (unbound) (U)
Kill from the cursor back to wherever insert mode was last entered.
vikilleol (unbound) (D) (unbound)
Kill from the cursor to the end of the line.
killregion

zsh 4.0.4

Last change: October 26, 2001

12

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHZLE ( 1 )

Kill from the cursor to the mark.


killbuffer (XK) (unbound) (unbound)
Kill the entire buffer.
killwholeline (U) (unbound) (unbound)
Kill the current line.
vimatchbracket (XB) (%) (unbound)
Move to the bracket character (one of {}, () or []) that matches the one under the cursor. If the cursor is not on a bracket character, move forward without going past the end of the line to find one,
and then go to the matching bracket.
viopenlineabove (unbound) (O) (unbound)
Open a line above the cursor and enter insert mode.
viopenlinebelow (unbound) (o) (unbound)
Open a line below the cursor and enter insert mode.
vioperswapcase
Read a movement command from the keyboard, and swap the case of all characters from the cursor position to the endpoint of the movement. If the movement command is vioperswapcase,
swap the case of all characters on the current line.
overwritemode (XO) (unbound) (unbound)
Toggle between overwrite mode and insert mode.
viputbefore (unbound) (P) (unbound)
Insert the contents of the kill buffer before the cursor. If the kill buffer contains a sequence of lines
(as opposed to characters), paste it above the current line.
viputafter (unbound) (p) (unbound)
Insert the contents of the kill buffer after the cursor. If the kill buffer contains a sequence of lines
(as opposed to characters), paste it below the current line.
quotedinsert (V) (unbound) (unbound)
Insert the next character typed into the buffer literally. An interrupt character will not be inserted.
viquotedinsert (unbound) (unbound) (Q V)
Display a at the cursor position, and insert the next character typed into the buffer literally. An
interrupt character will not be inserted.
quoteline (ESC) (unbound) (unbound)
Quote the current line; that is, put a character at the beginning and the end, and convert all
characters to \.
quoteregion (ESC") (unbound) (unbound)
Quote the region from the cursor to the mark.
vireplace (unbound) (R) (unbound)
Enter overwrite mode.
virepeatchange (unbound) (.) (unbound)
Repeat the last vi mode text modification. If a count was used with the modification, it is remembered. If a count is given to this command, it overrides the remembered count, and is remembered
for future uses of this command. The cut buffer specification is similarly remembered.
vireplacechars (unbound) (r) (unbound)
Replace the character under the cursor with a character read from the keyboard.
selfinsert (printable characters) (unbound) (printable characters and some control characters)
Insert a character into the buffer at the cursor position.
selfinsertunmeta (ESCI ESCJ ESCM) (unbound) (unbound)

zsh 4.0.4

Last change: October 26, 2001

13

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHZLE ( 1 )

Insert a character into the buffer after stripping the meta bit and converting M to J.
visubstitute (unbound) (s) (unbound)
Substitute the next character(s).
viswapcase (unbound) () (unbound)
Swap the case of the character under the cursor and move past it.
transposechars (T) (unbound) (unbound)
Exchange the two characters to the left of the cursor if at end of line, else exchange the character
under the cursor with the character to the left.
transposewords (ESCT ESCt) (unbound) (unbound)
Exchange the current word with the one before it.
viunindent (unbound) (<) (unbound)
Unindent a number of lines.
upcaseword (ESCU ESCu) (unbound) (unbound)
Convert the current word to all caps and move past it.
yank (Y) (unbound) (unbound)
Insert the contents of the kill buffer at the cursor position.
yankpop (ESCy) (unbound) (unbound)
Remove the text just yanked, rotate the killring, and yank the new top. Only works following
yank or yankpop.
viyank (unbound) (y) (unbound)
Read a movement command from the keyboard, and copy the region from the cursor position to
the endpoint of the movement into the kill buffer. If the command is viyank, copy the current
line.
viyankwholeline (unbound) (Y) (unbound)
Copy the current line into the kill buffer.
viyankeol
Copy the region from the cursor position to the end of the line into the kill buffer. Arguably, this
is what Y should do in vi, but it isnt what it actually does.
Arguments

digitargument (ESC0..ESC9) (19) (unbound)


Start a new numeric argument, or add to the current one.
See also
vidigitorbeginningofline. This only works if bound to a key sequence ending in a decimal
digit.
Inside a widget function, a call to this function treats the last key of the key sequence which called
the widget as the digit.
negargument (ESC ) (unbound) (unbound)
Changes the sign of the following argument.
universalargument
Multiply the argument of the next command by 4. Alternatively, if this command is followed by
an integer (positive or negative), use that as the argument for the next command. Thus digits cannot be repeated using this command. For example, if this command occurs twice, followed
immediately by forwardchar, move forward sixteen spaces; if instead it is followed by 2, then
forwardchar, move backward two spaces.
Inside a widget function, if passed an argument, i.e. zle universalargument num, the numerical
argument will be set to num; this is equivalent to NUMERIC=num.

zsh 4.0.4

Last change: October 26, 2001

14

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHZLE ( 1 )

Completion

acceptandmenucomplete
In a menu completion, insert the current completion into the buffer, and advance to the next possible completion.
completeword
Attempt completion on the current word.
deletecharorlist (D) (unbound) (unbound)
Delete the character under the cursor. If the cursor is at the end of the line, list possible completions for the current word.
expandcmdpath
Expand the current command to its full pathname.
expandorcomplete (TAB) (unbound) (TAB)
Attempt shell expansion on the current word. If that fails, attempt completion.
expandorcompleteprefix
Attempt shell expansion on the current word up to cursor.
expandhistory (ESCspace ESC!) (unbound) (unbound)
Perform history expansion on the edit buffer.
expandword (X) (unbound) (unbound)
Attempt shell expansion on the current word.
listchoices (ESCD) (D =) (D)
List possible completions for the current word.
listexpand (Xg XG) (G) (G)
List the expansion of the current word.
magicspace
Perform history expansion and insert a space into the buffer. This is intended to be bound to
space.
menucomplete
Like completeword, except that menu completion is used. See the MENU_COMPLETE
option.
menuexpandorcomplete
Like expandorcomplete, except that menu completion is used.
reversemenucomplete
Perform menu completion, like menucomplete, except that if a menu completion is already in
progress, move to the previous completion rather than the next.
endoflist
When a previous completion displayed a list below the prompt, this widget can be used to move
the prompt below the list.
Miscellaneous

acceptandhold (ESCA ESCa) (unbound) (unbound)


Push the contents of the buffer on the buffer stack and execute it.
acceptandinfernexthistory
Execute the contents of the buffer. Then search the history list for a line matching the current one
and push the event following onto the buffer stack.
acceptline (J M) (J M) (J M)
Finish editing the buffer. Normally this causes the buffer to be executed as a shell command.
acceptlineanddownhistory (O) (unbound) (unbound)

zsh 4.0.4

Last change: October 26, 2001

15

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHZLE ( 1 )

Execute the current line, and push the next history event on the the buffer stack.
beep

Beep, unless the BEEP option is unset.

vicmdmode (XV) (unbound) ([)


Enter command mode; that is, select the vicmd keymap. Yes, this is bound by default in emacs
mode.
vicapslockpanic
Hang until any lowercase key is pressed. This is for vi users without the mental capacity to keep
track of their caps lock key (like the author).
clearscreen (L ESCL) (L) (L)
Clear the screen and redraw the prompt.
describekeybriefly
Reads a key sequence, then prints the function bound to that sequence.
exchangepointandmark (XX) (unbound) (unbound)
Exchange the cursor position with the position of the mark.
executenamedcmd (ESCx) (unbound) (unbound)
Read the name of an editor command and execute it. A restricted set of editing functions is available in the minibuffer. An interrupt signal, as defined by the stty setting, will abort the function.
The allowed functions are: backwarddeletechar, vibackwarddeletechar, clearscreen,
redisplay, quotedinsert, viquotedinsert, backwardkillword, vibackwardkillword,
killwholeline, vikillline, backwardkillline, listchoices, deletecharorlist,
completeword, acceptline, expandorcomplete and expandorcompleteprefix.
killregion kills the last word, and vicmdmode is treated the same as acceptline. The space
and tab characters, if not bound to one of these functions, will complete the name and then list the
possibilities if the AUTO_LIST option is set. Any other character that is not bound to selfinsert
or selfinsertunmeta will beep and be ignored. The bindings of the current insert mode will be
used.
executelastnamedcmd (ESCz) (unbound) (unbound)
Redo the last function executed with executenamedcmd.
getline (ESCG ESCg) (unbound) (unbound)
Pop the top line off the buffer stack and insert it at the cursor position.
poundinsert (unbound) (#) (unbound)
If there is no # character at the beginning of the buffer, add one to the beginning of each line. If
there is one, remove a # from each line that has one. In either case, accept the current line. The
INTERACTIVE_COMMENTS option must be set for this to have any usefulness.
vipoundinsert
If there is no # character at the beginning of the current line, add one. If there is one, remove it.
The INTERACTIVE_COMMENTS option must be set for this to have any usefulness.
pushinput
Push the entire current multiline construct onto the buffer stack and return to the toplevel (PS1)
prompt. If the current parser construct is only a single line, this is exactly like pushline. Next
time the editor starts up or is popped with getline, the construct will be popped off the top of the
buffer stack and loaded into the editing buffer.
pushline (Q ESCQ ESCq) (unbound) (unbound)
Push the current buffer onto the buffer stack and clear the buffer. Next time the editor starts up,
the buffer will be popped off the top of the buffer stack and loaded into the editing buffer.
pushlineoredit
At the toplevel (PS1) prompt, equivalent to pushline. At a secondary (PS2) prompt, move the

zsh 4.0.4

Last change: October 26, 2001

16

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHZLE ( 1 )

entire current multiline construct into the editor buffer. The latter is equivalent to pushinput followed by getline.
redisplay (unbound) (R) (R)
Redisplays the edit buffer.
sendbreak (G ESCG) (unbound) (unbound)
Abort the current editor function, e.g. executenamedcommand, or the editor itself, e.g. if you
are in vared. Otherwise abort the parsing of the current line.
runhelp (ESCH ESCh) (unbound) (unbound)
Push the buffer onto the buffer stack, and execute the command runhelp cmd, where cmd is the
current command. runhelp is normally aliased to man.
visetbuffer (unbound) (") (unbound)
Specify a buffer to be used in the following command. There are 35 buffers that can be specified:
the 26 named buffers " a to " z and the nine queued buffers " 1 to " 9. The named buffers can
also be specified as " A to " Z.
When a buffer is specified for a cut command, the text being cut replaces the previous contents of
the specified buffer. If a named buffer is specified using a capital, the newly cut text is appended
to the buffer instead of overwriting it.
If no buffer is specified for a cut command, " 1 is used, and the contents of " 1 to " 8 are each
shifted along one buffer; the contents of " 9 is lost.
visetmark (unbound) (m) (unbound)
Set the specified mark at the cursor position.
setmarkcommand (@) (unbound) (unbound)
Set the mark at the cursor position.
spellword (ESC$ ESCS ESCs) (unbound) (unbound)
Attempt spelling correction on the current word.
undefinedkey
This command is executed when a key sequence that is not bound to any command is typed. By
default it beeps.
undo (_ Xu XU) (unbound) (unbound)
Incrementally undo the last text modification.
redo

Incrementally redo undone text modifications.

viundochange (unbound) (u) (unbound)


Undo the last text modification. If repeated, redo the modification.
whatcursorposition (X=) (unbound) (unbound)
Print the character under the cursor, its code as an octal, decimal and hexadecimal number, the
current cursor position within the buffer and the column of the cursor in the current line.
whereis
Read the name of an editor command and and print the listing of key sequences that invoke the
specified command.
whichcommand (ESC?) (unbound) (unbound)
Push the buffer onto the buffer stack, and execute the command whichcommand cmd. where
cmd is the current command. whichcommand is normally aliased to whence.
vidigitorbeginningofline (unbound) (0) (unbound)
If the last command executed was a digit as part of an argument, continue the argument. Otherwise, execute vibeginningofline.

zsh 4.0.4

Last change: October 26, 2001

17

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPWID ( 1 )

NAME

zshcompwid zsh completion widgets


DESCRIPTION

The shells programmable completion mechanism can be manipulated in two ways; here the lowlevel
features supporting the newer, functionbased mechanism are defined. A complete set of shell functions
based on these features is described in zshcompsys(1), and users with no interest in adding to that system
(or, potentially, writing their own see dictionary entry for hubris) should skip this section. The older
system based on the compctl builtin command is described in zshcompctl(1).
Completion widgets are defined by the C option to the zle builtin command provided by the zsh/zle
module (see zshzle(1)). For example,
zle C complete expandorcomplete completer
defines a widget named complete. The second argument is the name of any of the builtin widgets that
handle
completions:
completeword,
expandorcomplete,
expandorcompleteprefix,
menucomplete,
menuexpandorcomplete,
reversemenucomplete,
listchoices,
or
deletecharorlist. Note that this will still work even if the widget in question has been rebound.
When this newly defined widget is bound to a key using the bindkey builtin command defined in the
zsh/zle module (see zshzle(1)), typing that key will call the shell function completer. This function is
responsible for generating the possible matches using the builtins described below. As with other ZLE
widgets, the function is called with its standard input closed.
Once the function returns, the completion code takes over control again and treats the matches in the same
manner as the specified builtin widget, in this case expandorcomplete.
SPECIAL PARAMETERS

Inside completion widgets, and any functions called from them, some parameters have special meaning;
outside these functions they are not special to the shell in any way. These parameters are used to pass
information between the completion code and the completion widget. Some of the builtin commands and
the condition codes use or change the current values of these parameters. Any existing values will be hidden during execution of completion widgets; except for compstate, the parameters are reset on each function exit (including nested function calls from within the completion widget) to the values they had when
the function was entered.
CURRENT
This is the number of the current word, i.e. the word the cursor is currently on in the words array.
Note that this value is only correct if the ksharrays option is not set.
IPREFIX
Initially this will be set to the empty string. This parameter functions like PREFIX; it contains a
string which precedes the one in PREFIX and is not considered part of the list of matches. Typically, a string is transferred from the beginning of PREFIX to the end of IPREFIX, for example:
IPREFIX=${PREFIX%%\=}=
PREFIX=${PREFIX#=}
causes the part of the prefix up to and including the first equal sign not to be treated as part of a
matched string. This can be done automatically by the compset builtin, see below.
ISUFFIX
As IPREFIX, but for a suffix that should not be considered part of the matches; note that the
ISUFFIX string follows the SUFFIX string.
PREFIX
Initially this will be set to the part of the current word from the beginning of the word up to the
position of the cursor; it may be altered to give a common prefix for all matches.
QIPREFIX
This parameter is readonly and contains the quoted string up to the word being completed. E.g.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPWID ( 1 )

when completing " foo, this parameter contains the double quote. If the q option of compset is
used (see below), and the original string was " foo bar with the cursor on the bar, this parameter contains " foo .
QISUFFIX
Like QIPREFIX, but containing the suffix.
SUFFIX
Initially this will be set to the part of the current word from the cursor position to the end; it may
be altered to give a common suffix for all matches. It is most useful when the option
COMPLETE_IN_WORD is set, as otherwise the whole word on the command line is treated as a
prefix.
compstate
This is an associative array with various keys and values that the completion code uses to
exchange information with the completion widget. The keys are:
all_quotes
The q option of the compset builtin command (see below) allows a quoted string to be
broken into separate words; if the cursor is on one of those words, that word will be completed, possibly invoking compset q recursively. With this key it is possible to test
the types of quoted strings which are currently broken into parts in this fashion. Its value
contains one character for each quoting level. The characters are a single quote or a double quote for strings quoted with these characters and a backslash for strings not starting
with a quote character. The first character in the value always corresponds to the innermost quoting level.
context This will be set by the completion code to the overall context in which completion is
attempted. Possible values are:
array_value
when completing inside the value of an array parameter assignment; in this case
the words array contains the words inside the parentheses.
brace_parameter
when completing the name of a parameter in a parameter expansion beginning
with ${.
command
when completing for a normal command (either in command position or for an
argument of the command).
condition
when completing inside a [[...]] conditional expression; in this case the words
array contains only the words inside the conditional expression.
math

when completing in a mathematical environment such as a ((...)) construct.

parameter
when completing the name of a parameter in a parameter expansion beginning
with $ but not ${.
redirect
when completing after a redirection operator.
subscript
when completing inside a parameter subscript.
value
exact

zsh 4.0.4

when completing the value of a parameter assignment.

Controls the behaviour when the REC_EXACT option is set. It will be set to accept if
an exact match would be accepted, and will be unset otherwise.

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPWID ( 1 )

If it was set when at least one match equal to the string on the line was generated, the
match is accepted.
exact_string
The string of an exact match if one was found, otherwise unset.
ignored The number of words that were ignored because they matched one of the patterns given
with the F option to the compadd builtin command.
insert

This controls the manner in which a match is inserted into the command line. On entry to
the widget function, if it is unset the command line is not to be changed; if set to unambiguous, any prefix common to all matches is to be inserted; if set to
automenuunambiguous, the common prefix is to be inserted and the next invocation of
the completion code may start menu completion (due to the AUTO_MENU option being
set); if set to menu or automenu menu completion will be started for the matches
currently generated (in the latter case this will happen because the AUTO_MENU is set).
The value may also contain the string tab when the completion code would normally
not really do completion, but only insert the TAB character.
On exit it may be set to any of the values above (where setting it to the empty string is the
same as unsetting it), or to a number, in which case the match whose number is given will
be inserted into the command line. Negative numbers count backward from the last
match (with 1 selecting the last match) and outofrange values are wrapped around,
so that a value of zero selects the last match and a value one more than the maximum
selects the first. Unless the value of this key ends in a space, the match is inserted as in a
menu completion, i.e. without automatically appending a space.
Both menu and automenu may also specify the the number of the match to insert, given
after a colon. For example, menu:2 says to start menu completion, beginning with the
second match.
Note that a value containing the substring tab makes the matches generated be ignored
and only the TAB be inserted.
Finally, it may also be set to all, which makes all matches generated be inserted into the
line.

insert_positions
When the completion system inserts an unambiguous string into the line, there may be
multiple places where characters are missing or where the character inserted differs from
at least one match. The value of this key contains a colon separated list of all these positions, as indexes into the command line.
last_prompt
If this is set to a nonempty string for every match added, the completion code will move
the cursor back to the previous prompt after the list of completions has been displayed.
Initially this is set or unset according to the ALWAYS_LAST_PROMPT option.
list

This controls whether or how the list of matches will be displayed. If it is unset or empty
they will never be listed; if its value begins with list, they will always be listed; if it
begins with autolist or ambiguous, they will be listed when the AUTO_LIST or
LIST_AMBIGUOUS options respectively would normally cause them to be.
If the substring force appears in the value, this makes the list be shown even if there is
only one match. Normally, the list would be shown only if there are at least two matches.
The value contains the substring packed if the LIST_PACKED option is set. If this substring is given for all matches added to a group, this group will show the
LIST_PACKED behavior. The same is done for the LIST_ROWS_FIRST option with
the substring rows.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPWID ( 1 )

Finally, if the value contains the string explanations, only the explanation strings, if any,
will be listed and if it contains messages, only the messages (added with the x option of
compadd) will be listed. If it contains both explanations and messages both kinds of
explanation strings will be listed. It will be set appropriately on entry to a completion
widget and may be changed there.
list_lines
This gives the number of lines that are needed to display the full list of completions.
Note that to calculate the total number of lines to display you need to add the number of
lines needed for the command line to this value, this is available as the value of the
BUFFERLINES special parameter.
list_max
Initially this is set to the value of the LISTMAX parameter. It may be set to any other
value; when the widget exits this value will be used in the same way as the value of
LISTMAX.
nmatches
The number of matches generated and accepted by the completion code so far.
old_insert
On entry to the widget this will be set to the number of the match of an old list of completions that is currently inserted into the command line. If no match has been inserted, this
is unset.
As with old_list, the value of this key will only be used if it is the string keep. If it was
set to this value by the widget and there was an old match inserted into the command line,
this match will be kept and if the value of the insert key specifies that another match
should be inserted, this will be inserted after the old one.
old_list This is set to yes if there is still a valid list of completions from a previous completion at
the time the widget is invoked. This will usually be the case if and only if the previous
editing operation was a completion widget or one of the builtin completion functions. If
there is a valid list and it is also currently shown on the screen, the value of this key is
shown.
After the widget has exited the value of this key is only used if it was set to keep. In this
case the completion code will continue to use this old list. If the widget generated new
matches, they will not be used.
parameter
The name of the parameter when completing in a subscript or in the value of a parameter
assignment.
pattern_insert
Normally this is set to menu, which specifies that menu completion will be used whenever a set of matches was generated using pattern matching. If it is set to any other
nonempty string by the user and menu completion is not selected by other option settings, the code will instead insert any common prefix for the generated matches as with
normal completion.
pattern_match
Locally controls the behaviour given by the GLOB_COMPLETE option. Initially it is
set to if and only if the option is set. The completion widget may set it to this value,
to an empty string (which has the same effect as unsetting it), or to any other nonempty
string. If it is nonempty, unquoted metacharacters on the command line will be treated
as patterns; if it is , then additionally a wildcard is assumed at the cursor position;
if it is empty or unset, metacharacters will be treated literally.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPWID ( 1 )

Note that the matcher specifications given to the compadd builtin command are not used
if this is set to a nonempty string.
quote

When completing inside quotes, this contains the quotation character (i.e. either a single
quote, a double quote, or a backtick). Otherwise it is unset.

quoting When completing inside single quotes, this is set to the string single; inside double
quotes, the string double; inside backticks, the string backtick. Otherwise it is unset.
redirect

The redirection operator when completing in a redirection position, i.e. one of <, >, etc.

restore This is set to auto before a function is entered, which forces the special parameters mentioned above (words, CURRENT, PREFIX, IPREFIX, SUFFIX, and ISUFFIX) to be
restored to their previous values when the function exits. If a function unsets it or sets it
to any other string, they will not be restored.
to_end Specifies the occasions on which the cursor is moved to the end of a string when a match
is inserted. On entry to a widget function, it may be single if this will happen when a single unambiguous match was inserted or match if it will happen any time a match is
inserted (for example, by menu completion; this is likely to be the effect of the
ALWAYS_TO_END option).
On exit, it may be set to single as above. It may also be set to always, or to the empty
string or unset; in those cases the cursor will be moved to the end of the string always or
never respectively. Any other string is treated as match.
unambiguous
This key is readonly and will always be set to the common (unambiguous) prefix the
completion code has generated for all matches added so far.
unambiguous_cursor
This gives the position the cursor would be placed at if the common prefix in the unambiguous key were inserted, relative to the value of that key. The cursor would be placed
before the character whose index is given by this key.
unambiguous_positions
This contains all positions where characters in the unambiguous string are missing or
where the character inserted differs from at least one of the matches. The positions are
given as indexes into the string given by the value of the unambiguous key.
vared

If completion is called while editing a line using the vared builtin, the value of this key is
set to the name of the parameter given as an argument to vared. This key is only set
while a vared command is active.

words This array contains the words present on the command line currently being edited.
BUILTIN COMMANDS

compadd [ akqQfenUl12C ] [ F array ]


[ P prefix ] [ S suffix ]
[ p hiddenprefix ] [ s hiddensuffix ]
[ i ignoredprefix ] [ I ignoredsuffix ]
[ W fileprefix ] [ d array ]
[ J name ] [ V name ] [ X explanation ] [ x message ]
[ r removechars ] [ R removefunc ]
[ D array ] [ O array ] [ A array ]
[ M matchspec ] [ ] [ words ... ]
This builtin command can be used to add matches directly and control all the information the completion code stores with each possible match. The return value is zero if at least one match was
added and nonzero if no matches were added.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPWID ( 1 )

The completion code breaks the string to complete into seven fields in the order:
< ipre> < apre> < hpre> < word> < hsuf> < asuf> < isuf>
The first field is an ignored prefix taken from the command line, the contents of the IPREFIX
parameter plus the string given with the i option. With the U option, only the string from the i
option is used. The field < apre> is an optional prefix string given with the P option. The
< hpre> field is a string that is considered part of the match but that should not be shown when
listing completions, given with the p option; for example, functions that do filename generation
might specify a common path prefix this way. < word> is the part of the match that should appear
in the list of completions, i.e. one of the words given at the end of the compadd command line.
The suffixes < hsuf> , < asuf> and < isuf> correspond to the prefixes < hpre> , < apre> and < ipre>
and are given by the options s, S and I, respectively.
The supported flags are:
P prefix
This gives a string to be inserted before the given words. The string given is not considered as part of the match and any shell metacharacters in it will not be quoted when the
string is inserted.
S suffix
Like P, but gives a string to be inserted after the match.
p hiddenprefix
This gives a string that should be inserted into the command line before the match but
that should not appear in the list of matches. Unless the U option is given, this string
must be matched as part of the string on the command line.
s hiddensuffix
Like p, but gives a string to insert after the match.
i ignoredprefix
This gives a string to insert into the command line just before any string given with the
P option. Without P the string is inserted before the string given with p or
directly before the match.
I ignoredsuffix
Like i, but gives an ignored suffix.
a

With this flag the words are taken as names of arrays and the possible matches are their
values. If only some elements of the arrays are needed, the words may also contain subscripts, as in foo[2,1].

With this flag the words are taken as names of associative arrays and the possible matches
are their keys. As for a, the words may also contain subscripts, as in foo[(R)bar].

d array
This adds permatch display strings. The array should contain one element per word
given. The completion code will then display the first element instead of the first word,
and so on. The array may be given as the name of an array parameter or directly as a
spaceseparated list of words in parentheses.
If there are fewer display strings than words, the leftover words will be displayed
unchanged and if there are more display strings than words, the leftover display strings
will be silently ignored.
l

This option only has an effect if used together with the d option. If it is given, the
display strings are listed one per line, not arrayed in columns.

J name
Gives the name of the group of matches the words should be stored in.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPWID ( 1 )

V name
Like J but naming a unsorted group. These are in a different name space than groups
created with the J flag.
1

If given together with the V option, makes only consecutive duplicates in the group be
removed. If combined with the J option, this has no visible effect. Note that groups with
and without this flag are in different name spaces.

If given together with the J or V option, makes all duplicates be kept. Again, groups
with and without this flag are in different name spaces.

X explanation
The explanation string will be printed with the list of matches, above the group currently
selected.
x message
Like X, but the message will be printed even if there are no matches in the group.
q

The suffix given with S will be automatically removed if the next character typed is a
blank or does not insert anything, or if the suffix consists of only one character and the
next character typed is the same character.

r removechars
This is a more versatile form of the q option. The suffix given with S or the slash
automatically added after completing directories will be automatically removed if the
next character typed inserts one of the characters given in the removechars. This string
is parsed as a characters class and understands the backslash sequences used by the print
command. For example, r " az\t" removes the suffix if the next character typed
inserts a lowercase character or a TAB, and r " 09" removes the suffix if the next
character typed inserts anything but a digit. One extra backslash sequence is understood
in this string: \ stands for all characters that insert nothing. Thus S " =" q is the
same as S " =" r " = \t\n\" .
R removefunc
This is another form of the r option. When a suffix has been inserted and the completion
accepted, the function removefunc will be called after the next character typed. It is
passed the length of the suffix as an argument and can use the special parameters available in ordinary (noncompletion) zle widgets (see zshzle(1)) to analyse and modify the
command line.
f

If this flag is given, all of the matches built from words are marked as being the names of
files. They are not required to be actual filenames, but if they are, and the option
LIST_TYPES is set, the characters describing the types of the files in the completion
lists will be shown. This also forces a slash to be added when the name of a directory is
completed.

This flag can be used to tell the completion code that the matches added are parameter
names for a parameter expansion. This will make the AUTO_PARAM_SLASH and
AUTO_PARAM_KEYS options be used for the matches.

W fileprefix
This string is a pathname that will be prepended to each of the matches formed by the
given words together with any prefix specified by the p option to form a complete
filename for testing. Hence it is only useful if combined with the f flag, as the tests will
not otherwise be performed.
F array
Specifies an array containing patterns. Words matching one of these patterns are ignored,
i.e. not considered to be possible matches.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPWID ( 1 )

The array may be the name of an array parameter or a list of literal patterns enclosed in
parentheses and quoted, as in F " (?.o ?.h)" . If the name of an array is given, the
elements of the array are taken as the patterns.
Q

This flag instructs the completion code not to quote any metacharacters in the words
when inserting them into the command line.

M matchspec
This gives local match specifications as described below in the section Matching Control. This option may be given more than once. In this case all matchspecs given are
concatenated with spaces between them to form the specification string to use. Note that
they will only be used if the U option is not given.
n

Specifies that the words added are to be used as possible matches, but are not to appear in
the completion listing.

If this flag is given, all words given will be accepted and no matching will be done by the
completion code. Normally this is used in functions that do the matching themselves.

O array
If this option is given, the words are not added to the set of possible completions.
Instead, matching is done as usual and all of the words given as arguments that match the
string on the command line will be stored in the array parameter whose name is given as
array.
A array
As the O option, except that instead of those of the words which match being stored in
array, the strings generated internally by the completion code are stored. For example,
with a matching specification of M " L:no=" , the string nof on the command line
and the string foo as one of the words, this option stores the string nofoo in the array,
whereas the O option stores the foo originally given.
D array
As with O, the words are not added to the set of possible completions. Instead, the completion code tests whether each word in turn matches what is on the line. If the nth word
does not match, the nth element of the array is removed. Elements for which the
corresponding word is matched are retained.
C

This option adds a special match which expands to all other matches when inserted into
the line, even those that are added after this option is used. Together with the d option it
is possible to specify a string that should be displayed in the list for this special match. If
no string is given, it will be shown as a string containing the strings that would be
inserted for the other matches, truncated to the width of the screen.
This flag ends the list of flags and options. All arguments after it will be taken as the
words to use as matches even if they begin with hyphens.

Except for the M flag, if any of these flags is given more than once, the first one (and its argument) will be used.
compset p number
compset P [ number ] pattern
compset s number
compset S [ number ] pattern
compset n begin [ end ]
compset N begpat [ endpat ]
compset q
This command simplifies modification of the special parameters, while its return value allows tests
on them to be carried out.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPWID ( 1 )

The options are:


p number
If the contents of the PREFIX parameter is longer than number characters, the first
number characters are removed from it and appended to the contents of the IPREFIX
parameter.
P [ number ] pattern
If the value of the PREFIX parameter begins with anything that matches the pattern, the
matched portion is removed from PREFIX and appended to IPREFIX.
Without the optional number, the longest match is taken, but if number is given, anything
up to the numberth match is moved. If the number is negative, the numberth longest
match is moved. For example, if PREFIX contains the string a=b=c, then compset P
\= will move the string a=b= into the IPREFIX parameter, but compset P 1 \=
will move only the string a=.
s number
As p, but transfer the last number characters from the value of SUFFIX to the front of
the value of ISUFFIX.
S [ number ] pattern
As P, but match the last portion of SUFFIX and transfer the matched portion to the
front of the value of ISUFFIX.
n begin [ end ]
If the current word position as specified by the parameter CURRENT is greater than or
equal to begin, anything up to the beginth word is removed from the words array and the
value of the parameter CURRENT is decremented by begin.
If the optional end is given, the modification is done only if the current word position is
also less than or equal to end. In this case, the words from position end onwards are also
removed from the words array.
Both begin and end may be negative to count backwards from the last element of the
words array.
N begpat [ endpat ]
If one of the elements of the words array before the one at the index given by the value of
the parameter CURRENT matches the pattern begpat, all elements up to and including
the matching one are removed from the words array and the value of CURRENT is
changed to point to the same word in the changed array.
If the optional pattern endpat is also given, and there is an element in the words array
matching this pattern, the parameters are modified only if the index of this word is higher
than the one given by the CURRENT parameter (so that the matching word has to be
after the cursor). In this case, the words starting with the one matching endpat are also
removed from the words array. If words contains no word matching endpat, the testing
and modification is performed as if it were not given.
q

The word currently being completed is split on spaces into separate words, respecting the
usual shell quoting conventions. The resulting words are stored in the words array, and
CURRENT, PREFIX, SUFFIX, QIPREFIX, and QISUFFIX are modified to reflect
the word part that is completed.

In all the above cases the return value is zero if the test succeeded and the parameters were
modified and nonzero otherwise. This allows one to use this builtin in tests such as:
if compset P \=; then ...

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPWID ( 1 )

This forces anything up to and including the last equal sign to be ignored by the completion code.
compcall [ TD ]
This allows the use of completions defined with the compctl builtin from within completion widgets. The list of matches will be generated as if one of the nonwidget completion function
(completeword, etc.) had been called, except that only compctls given for specific commands
are used. To force the code to try completions defined with the T option of compctl and/or the
default completion (whether defined by compctl D or the builtin default) in the appropriate
places, the T and/or D flags can be passed to compcall.
The return value can be used to test if a matching compctl definition was found. It is nonzero if a
compctl was found and zero otherwise.
Note that this builtin is defined by the zsh/compctl module.
CONDITION CODES

The following additional condition codes for use within the [[ ... ]] construct are available in completion
widgets. These work on the special parameters. All of these tests can also be performed by the compset
builtin, but in the case of the condition codes the contents of the special parameters are not modified.
prefix [ number ] pattern
true if the test for the P option of compset would succeed.
suffix [ number ] pattern
true if the test for the S option of compset would succeed.
after begpat
true if the test of the N option with only the begpat given would succeed.
between begpat endpat
true if the test for the N option with both patterns would succeed.
MATCHING CONTROL

It is possible by use of the M option of the compadd builtin command to specify how the characters in the
string to be completed (referred to here as the command line) map onto the characters in the list of matches
produced by the completion code (referred to here as the trial completions). Note that this is not used if the
command line contains a glob pattern and the GLOB_COMPLETE option is set or the pattern_match of
the compstate special association is set to a nonempty string.
The matchspec given as the argument to the M option (see Builtin Commands above) consists of one or
more matching descriptions separated by whitespace. Each description consists of a letter followed by a
colon and then the patterns describing which character sequences on the line match which character
sequences in the trial completion. Any sequence of characters not handled in this fashion must match
exactly, as usual.
The forms of matchspec understood are as follows. In each case, the form with an uppercase initial character retains the string already typed on the command line as the final result of completion, while with a
lowercase initial character the string on the command line is changed into the corresponding part of the trial
completion.
m:lpat=tpat
M:lpat=tpat
Here, lpat is a pattern that matches on the command line, corresponding to tpat which matches in
the trial completion.
l:lanchorlpat=tpat
L:lanchorlpat=tpat
l:lanchorranchor=tpat
L:lanchorranchor=tpat
b:lpat=tpat
B:lpat=tpat

zsh 4.0.4

Last change: October 26, 2001

10

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPWID ( 1 )

These letters are for patterns that are anchored by another pattern on the left side. Matching for
lpat and tpat is as for m and M, but the pattern lpat matched on the command line must be preceded by the pattern lanchor. The lanchor can be blank to anchor the match to the start of the
command line string; otherwise the anchor can occur anywhere, but must match in both the command line and trial completion strings.
If no lpat is given but a ranchor is, this matches the gap between substrings matched by lanchor
and ranchor. Unlike lanchor, the ranchor only needs to match the trial completion string.
The b and B forms are similar to l and L with an empty anchor, but need to match only the beginning of the trial completion or the word on the command line, respectively.
r:lpatranchor=tpat
R:lpatranchor=tpat
r:lanchorranchor=tpat
R:lanchorranchor=tpat
e:lpat=tpat
E:lpat=tpat
As l, L, b and B, with the difference that the command line and trial completion patterns are
anchored on the right side. Here an empty ranchor and the e and E forms force the match to the
end of the trial completion or command line string.
Each lpat, tpat or anchor is either an empty string or consists of a sequence of literal characters (which may
be quoted with a backslash), question marks, character classes, and correspondence classes; ordinary shell
patterns are not used. Literal characters match only themselves, question marks match any character, and
character classes are formed as for globbing and match any character in the given set.
Correspondence classes are defined like character classes, but with two differences: they are delimited by a
pair of braces, and negated classes are not allowed, so the characters ! and have no special meaning
directly after the opening brace. They indicate that a range of characters on the line match a range of characters in the trial completion, but (unlike ordinary character classes) paired according to the corresponding
position in the sequence. For example, to make any lowercase letter on the line match the corresponding
uppercase letter in the trial completion, you can use m:{az}={AZ}. More than one pair of classes can
occur, in which case the first class before the = corresponds to the first after it, and so on. If one side has
more such classes than the other side, the superfluous classes behave like normal character classes. In
anchor patterns correspondence classes also behave like normal character classes.
The pattern tpat may also be one or two stars, or . This means that the pattern on the command line
can match any number of characters in the trial completion. In this case the pattern must be anchored (on
either side); in the case of a single star, the anchor then determines how much of the trial completion is to
be included only the characters up to the next appearance of the anchor will be matched. With two
stars, substrings matched by the anchor can be matched, too.
Examples:
The keys of the options association defined by the parameter module are the option names in
alllowercase form, without underscores, and without the optional no at the beginning even though the
builtins setopt and unsetopt understand option names with uppercase letters, underscores, and the optional
no. The following alters the matching rules so that the prefix no and any underscore are ignored when trying to match the trial completions generated and uppercase letters on the line match the corresponding
lowercase letters in the words:
compadd M L:[nN][oO]= M:_= M:{AZ}={az} \
${(k)options}
The first part says that the pattern [nN][oO] at the beginning (the empty anchor before the pipe symbol) of
the string on the line matches the empty string in the list of words generated by completion, so it will be
ignored if present. The second part does the same for an underscore anywhere in the command line string,
and the third part uses correspondence classes so that any uppercase letter on the line matches the

zsh 4.0.4

Last change: October 26, 2001

11

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPWID ( 1 )

corresponding lowercase letter in the word. The use of the uppercase forms of the specification characters
(L and M) guarantees that what has already been typed on the command line (in particular the prefix no)
will not be deleted.
Note that the use of L in the first part means that it matches only when at the beginning of both the command line string and the trial completion. I.e., the string _NO_f would not be completed to _NO_foo,
nor would NONO_f be completed to NONO_foo because of the leading underscore or the second NO
on the line which makes the pattern fail even though they are otherwise ignored. To fix this, one would use
B:[nN][oO]= instead of the first part. As described above, this matches at the beginning of the trial completion, independent of other characters or substrings at the beginning of the command line word which are
ignored by the same or other matchspecs.
The second example makes completion case insensitive. This is just the same as in the option example,
except here we wish to retain the characters in the list of completions:
compadd M m:{az}={AZ} ...
This makes lowercase letters match their uppercase counterparts. To make uppercase letters match the
lowercase forms as well:
compadd M m:{azAZ}={AZaz} ...
A nice example for the use of patterns is partial word completion. Sometimes you would like to make
strings like c.s.u complete to strings like comp.source.unix, i.e. the word on the command line consists
of multiple parts, separated by a dot in this example, where each part should be completed separately
note, however, that the case where each part of the word, i.e. comp, source and unix in this example,
is to be completed from separate sets of matches is a different problem to be solved by the implementation
of the completion widget. The example can be handled by:
compadd M r:.= r:= \
comp.sources.unix comp.sources.misc ...
The first specification says that lpat is the empty string, while anchor is a dot; tpat is , so this can match
anything except for the . from the anchor in the trial completion word. So in c.s.u, the matcher sees c,
followed by the empty string, followed by the anchor ., and likewise for the second dot, and replaces the
empty strings before the anchors, giving c[omp].s[ources].u[nix], where the last part of the completion is
just as normal.
With the pattern shown above, the string c.u could not be completed to comp.sources.unix because the
single star means that no dot (matched by the anchor) can be skipped. By using two stars as in r:.=,
however, c.u could be completed to comp.sources.unix. This also shows that in some cases, especially
if the anchor is a real pattern, like a character class, the form with two stars may result in more matches
than one would like.
The second specification is needed to make this work when the cursor is in the middle of the string on the
command line and the option COMPLETE_IN_WORD is set. In this case the completion code would
normally try to match trial completions that end with the string as typed so far, i.e. it will only insert new
characters at the cursor position rather then at the end. However in our example we would like the code to
recognise matches which contain extra characters after the string on the line (the nix in the example).
Hence we say that the empty string at the end of the string on the line matches any characters at the end of
the trial completion.
More generally, the specification
compadd M r:[.,_]= r:= ...
allows one to complete words with abbreviations before any of the characters in the square brackets. For
example, to complete veryverylongfile.c rather than veryverylongheader.h with the above in effect, you
can just type very.c before attempting completion.

zsh 4.0.4

Last change: October 26, 2001

12

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPWID ( 1 )

The specifications with both a left and a right anchor are useful to complete partial words whose parts are
not separated by some special character. For example, in some places strings have to be completed that are
formed LikeThis (i.e. the separate parts are determined by a leading uppercase letter) or maybe one has to
complete strings with trailing numbers. Here one could use the simple form with only one anchor as in:
compadd M r:[AZ09]= r:= LikeTHIS FooHoo 5foo123 5bar234
But with this, the string H would neither complete to FooHoo nor to LikeTHIS because in each case
there is an uppercase letter before the H and that is matched by the anchor. Likewise, a 2 would not be
completed. In both cases this could be changed by using r:[AZ09]=, but then H completes to both
LikeTHIS and FooHoo and a 2 matches the other strings because characters can be inserted before
every uppercase letter and digit. To avoid this one would use:
compadd M r:[AZ09][AZ09]= r:= \
LikeTHIS FooHoo foo123 bar234
By using these two anchors, a H matches only uppercase Hs that are immediately preceded by something matching the left anchor [AZ09]. The effect is, of course, that H matches only the string
FooHoo, a 2 matches only bar234 and so on.
When using the completion system (see zshcompsys(1)), users can define match specifications that are to be
used for specific contexts by using the matcher and matcherlist styles. The values for the latter will be
used everywhere.
COMPLETION WIDGET EXAMPLE

The first step is to define the widget:


zle C complete completeword completefiles
Then the widget can be bound to a key using the bindkey builtin command:
bindkey X\t complete
After that the shell function completefiles will be invoked after typing controlX and TAB. The function
should then generate the matches, e.g.:
completefiles () { compadd }
This function will complete files in the current directory matching the current word.

zsh 4.0.4

Last change: October 26, 2001

13

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

NAME

zshcompsys zsh completion system


DESCRIPTION

This describes the shell code for the new completion system. It consists of various shell functions; those
beginning comp are to be called directly by the user, while those beginning _ are called by the completion code. The shell functions of the second set which implement completion behaviour and which may be
bound to keystrokes, are referred to as widgets.
INITIALIZATION

If the system was installed completely, it should be enough to call the shell function compinit from your
initialization file; see the next section. However, the function compinstall can be run by a user to configure
various aspects of the completion system.
Usually, compinstall will insert code into .zshrc, although if that is not writable it will save it in another
file and tell you that files location. Note that it is up to you to make sure that the lines added to .zshrc are
actually run; you may, for example, need to move them to an earlier place in the file if .zshrc usually
returns early. So long as you keep them all together (including the comment lines at the start and finish),
you can rerun compinstall and it will correctly locate and modify these lines. Note, however, that any code
you add to this section by hand is likely to be lost if you rerun compinstall, although lines using the command zstyle should be gracefully handled.
The new code will take effect next time you start the shell, or run .zshrc by hand; there is also an option to
make them take effect immediately. However, if compinstall has removed definitions, you will need to
restart the shell to see the changes.
To run compinstall you will need to make sure it is in a directory mentioned in your fpath parameter,
which should already be the case if zsh was properly configured as long as your startup files do not remove
the appropriate directories from fpath. Then it must be autoloaded (autoload U compinstall is recommended). You can abort the installation any time you are being prompted for information, and your .zshrc
will not be altered at all; changes only take place right at the end, where you are specifically asked for
confirmation.
Use of compinit

This section describes the use of compinit to initialize completion for the current session when run directly
by the user; if you have run compinstall it will be called automatically from your .zshrc.
To initialize the system, the function compinit should be in a directory mentioned in the fpath parameter,
and should be autoloaded (autoload U compinit is recommended), and then run simply as compinit.
This will define a few utility functions, arrange for all the necessary shell functions to be autoloaded, and
will then redefine all widgets that do completion to use the new system. If you use the menuselect
widget, which is part of the zsh/complist module, you should make sure that that module is loaded before
the call to compinit so that that widget is also redefined. If completion styles (see below) are set up to
perform expansion as well as completion by default, and the TAB key is bound to expandorcomplete,
compinit will rebind it to completeword; this is necessary to use the correct form of expansion.
Should you need to use the original completion commands, you can still bind keys to the old widgets by
putting a . in front of the widget name, e.g. .expandorcomplete.
To speed up the running of compinit, it can be made to produce a dumped configuration which will be read
in on future invocations; this is the default, although it can be turned off by calling compinit with the
option D. The dumped file is .zcompdump in the same directory as the startup files (i.e. $ZDOTDIR or
$HOME); alternatively, an explicit file name can be given by compinit d dumpfile. On the next call to
compinit, it will read the dumped file instead of performing a full initialization.
If the number of completion files changes, compinit will recognise this and produce a new dump file.
However, if the name of a function or the arguments in the first line of a #compdef function (as described
below) change, it is easiest to delete the dump file by hand so that compinit will recreate it the next time it
is run. The check performed to see if there are new functions can be omitted by giving the option C. In

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

this case the dump file will only be created if there isnt one already.
The dumping is actually done by another function, compdump, but you will only need to run this yourself
if you change the configuration (e.g. using compdef) and then want to dump the new one. The name of the
old dumped file will be remembered for this purpose.
If the parameter _compdir is set, compinit uses it as a directory where completion functions can be found;
this is only necessary if they are not already in the function search path.
For security reasons compinit also checks if the completion system would use files not owned by root or by
the current user, or files in directories that are world or groupwritable or that are not owned by root or by
the current user. If such files or directories are found, compinit will ask if the completion system should
really be used. To avoid these tests and make all files found be used without asking, use the option u, and
to make compinit silently ignore all insecure files and directories use the option i. This security check is
skipped entirely when the C option is given.
The security check can be retried at any time by running the function compaudit. This is the same check
used by compinit, but when it is executed directly any changes to fpath are made local to the function so
they do not persist. The directories to be checked may be passed as arguments; if none are given, compaudit uses fpath and _compdir to find completion system directories, adding missing ones to fpath as necessary. To force a check of exactly the directories currently named in fpath, set _compdir to an empty string
before calling compaudit or compinit.
Autoloaded files

The convention for autoloaded functions used in completion is that they start with an underscore; as already
mentioned, the fpath/FPATH parameter must contain the directory in which they are stored. If zsh was
properly installed on your system, then fpath/FPATH automatically contains the required directories for
the standard functions.
For incomplete installations, if compinit does not find enough files beginning with an underscore (fewer
than twenty) in the search path, it will try to find more by adding the directory _compdir to the search path.
If that directory has a subdirectory named Base, all subdirectories will be added to the path. Furthermore,
if the subdirectory Base has a subdirectory named Core, compinit will add all subdirectories of the subdirectories is to the path: this allows the functions to be in the same format as in the zsh source distribution.
When compinit is run, it searches all such files accessible via fpath/FPATH and reads the first line of each
of them. This line should contain one of the tags described below. Files whose first line does not start with
one of these tags are not considered to be part of the completion system and will not be treated specially.
The tags are:
#compdef names...
The file will be made autoloadable and the function defined in it will be called when completing
names, each of which is either the name of a command whose arguments are to be completed or
one of a number of special contexts in the form context described below for the _complete function.
Each name may also be of the form cmd=service. This is used by functions that offer multiple
services, i.e. different completion behaviour for multiple commands. Such a string makes the
completion system call the function when completing arguments for the command cmd, setting
the parameter $service to the string service. The function can then use that parameter to decide
what to complete.
#compdef p pattern
The file will be made autoloadable and the function defined in it will be called when completing
for a command whose name matches the given pattern (a standard globbing pattern). Note that
only one pattern may be given.
#compdef P pattern
Like the previous one, but the function will be called only if no completion function for the command on the line could be found.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

#compdef k style keysequences...


This can be used to bind special completion functions to the keysequences specified. It creates a
widget behaving like the builtin widget style, which must be one of those that perform completion,
namely
completeword,
deletecharorlist,
expandorcomplete,
expandorcompleteprefix, listchoices, menucomplete, menuexpandorcomplete, or
reversemenucomplete. If the zsh/complist module is loaded (see zshmodules(1)), the same
happens to the menuselect widget.
The widget is then bound to all the keysequences given, if any: when one of the keysequences is
typed, the function in the file will be invoked to generate the matches. Note that a key will not be
rebound if if it already was (that is, was bound to something other than undefinedkey). The
widget created has the same name as the file and can be bound to any other keys using bindkey as
usual.
#compdef K widgetname style keysequences ...
This is similar to k, with the same style and keysequences arguments, preceded by a string giving the name of a widget. In this case only one keysequences argument may be given, but the
entire set of three arguments may be repeated with a different set of arguments. In particular, the
widgetname must be distinct in each set. It should begin with _, else one will be added, and
should not clash with the name of any existing widget: names based on the name of the function
are most useful. For example,
#compdef K _foo_complete completeword " XC" \
_foo_list listchoices " XD"
(all on one line) defines a widget _foo_complete for completion, bound to XC, and a widget
_foo_list for listing, bound to XD.
#autoload [ options ]
This is used for files defining utility functions that are not to be called directly as completion functions but should be loaded automatically when invoked. Typically they are to be called from
within one of the completion functions.
The options will be given to the autoload builtin command when making the function autoloaded.
Most often, this will be +X to force the function to be loaded immediately. Note that the U flag
is always implicitly added.
The # is part of the tag name and no white space is allowed after it. The #compdef tags use the compdef
function described below; the main difference is that the name of the function is supplied implicitly.
Note also that the functions for the completion system assume that the KSH_AUTOLOAD option is not
set and cannot be loaded when it is set. To avoid having to unset KSH_AUTOLOAD, you can instead use
one or more zwc file(s) which have been created with the command zcompile z to load the functions for
the completion system; see zshbuiltins(1). This forces the functions to be autoloaded the way zsh normally
loads functions.
Functions

The compinit file defines the following function, which may also be called directly by the user.
compdef [ an ] function names...
compdef d names...
compdef p [ a ] function pattern
compdef P [ a ] function pattern
compdef k [ an ] function style keysequences...
compdef K [ an ] function name style keysequences ...
The first form tells the completion system to call the given function when completing for the contexts or commands whose names are given: this is like the #compdef tag unless the first word
contains an equal sign. In this case all words have to be of the form cmd=service where service
is the name of a command or of a service defined by an autoloaded function with the #compdef

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

tag and an argument of the form cmd=service. This kind of use makes the arguments of the cmds
be completed as those for the services.
If the n option is given, any existing completion behaviour for particular contexts or commands
will not be altered. These definitions can be deleted by giving the d option as in the second form.
The form with p is similar to the first, but function will be called for all commands whose name
matches the pattern; this is like the #compdef p function tag.
The form with P is like the third, but the function will be called only if no function for the command itself was found or if one was found and it set the _compskip parameter to a value not containing the substring patterns.
The form with k defines a widget with the same name as the function which will be called for
each of the keysequences; this is like the #compdef k tag. The function should generate the
completions needed and will otherwise behave like the builtin widget whose name is given as the
style argument. The widgets usable for this are: completeword, deletecharorlist,
expandorcomplete,
expandorcompleteprefix,
listchoices,
menucomplete,
menuexpandorcomplete, and reversemenucomplete, as well as menuselect if the
zsh/complist module is loaded. The option n prevents the key being bound if it is already to
bound to something other than undefinedkey.
The form with K is similar and defines multiple widgets based on the same function, each of
which requires the set of three arguments name, style and keysequences, where the latter two are
as for k and the first must be a unique widget name beginning with an underscore.
In each of the forms supporting it the a option makes the function autoloadable (exactly
equivalent to autoload U function).
The compdef function is the place to turn to when one wants to define what the completion system should
complete for a certain command. The function named can of course be one of the functions supplied or one
written by the user. For example, if one has a command foo that gets process identifiers as arguments, one
could do:
compdef _pids foo
using the _pids function from the distribution to generate the process identifiers. Not also the
_gnu_generic function described below, which can be used to complete options for commands that understand the help option.
COMPLETION SYSTEM CONFIGURATION

This section gives a short overview of how the completion system works, and then more detail on how
users can configure how and when matches are generated.
Overview

When completion is attempted somewhere on a command line the completion system first tries to find out
the context where completion was tried. The context depends on such things as the name of the command
when completing an argument, and possibly also the name of an option when completing an argument to
that option.
The context of a completion is a string consisting of multiple fields. This is used to look up styles that can
be used to configure the completion system. Since it is not possible to build the whole context string in
advance, completion functions may modify some of the fields and hence the context used for lookup may
vary during the same call to the completion system.
The context string always consists of the following fields, separated by colons and with a leading colon
before the first:

zsh 4.0.4

The literal string completion, saying that this style is used by the completion system.

The function; in many cases this field will be blank, but when the completion system is called from

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

other functions, like predicton or one of the functions in the Command directory of the distribution, this field contains the name of that function, often in an abbreviated form.

The completer currently active, which is the name of the function without the leading underscore.
A completer is in overall control of how completion is to be performed; complete is the basic
one for ordinary completion, but completers may perform various related tasks such as correction,
or modify the behaviour of a later completer (see the section Control Functions below for more
information).

The context or command. This is either one of the special context names such as condition as
explained for the _complete completer below, or the name of the command we are completing
arguments for. Completion functions for commands that have subcommands usually modify this
field to contain the name of the command followed by a minus sign and the subcommand (e.g.
the completion function for the cvs command sets this field to strings such as cvsadd when completing for the add subcommand).

The argument, describing which argument we are completing. Normally this is either a string of
the form argumentn, where n is the number of the argument or it is a string of the form
optionoptn when completing the nth argument of the option opt.

The tag. Tags are used to discriminate between the types of matches a completion function can
generate in a certain context.

As an example, the context name


:completion::complete:dvips:optiono1:files
says that normal completion was attempted on an argument of the dvips command (more precisely: completion was attempted on the first argument after the o option) and the completion function will generate
filenames for this context.
In many of the possible contexts the completion system can generate matches, often multiple types of
matches. These types are represented as simple names called tags. The completion system will decide
internally what sort of tags are allowed; a list of the standard possibilities is given below. To determine in
which order the tags are to be used by the completion function, the tagorder style for the appropriate
context may be set, as described in the list of standard styles below. Only those types of matches whose
tags were selected by this style will be produced, and in the order given, although the default is to try all
relevant tags in an order determined by the particular completion in use.
The _complete_help bindable command described in the section Bindable Commands below can be
invoked to find out the context and tag names and styles used at a particular point in completion. It shows
the list of contexts and tags that would be used in if completion were tried at the current cursor position.
Hence one can easily find out all the information needed to change the behaviour of the tagorder style for
a particular context.
Completion behaviour can be modified by various other styles defined with the zstyle builtin command (see
zshmodules(1)). When looking up styles the completion system uses full context names, including the tag.
Styles determine such things as how the matches are generated; some of them correspond to shell options
(for example, the use of menu completion), but styles provide more specific control. They can have any
number of strings as their value. Looking up the value of a style therefore consists of two things: the context, which may be matched as a pattern, and the name of the style itself, which must be given exactly.
For example, many completion functions can generate matches in a simple and a verbose form and use the
verbose style to decide which form should be used. To make all such functions use the verbose form, put

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

zstyle :completion: verbose yes


in one of the startup files like .zshrc; this sort of style can also be configured with the compinstall function.
This definition simply means that the verbose style has yes as its value in every context inside the completion system. If the context pattern were , the verbose style would have this value anywhere the style
mechanism is used, not just in completion.
As a more specific example, the completion function for the kill builtin command uses the verbose style to
decide if jobs and processes are listed only as job numbers and process identifiers or if they are listed with
the full job texts and the command lines of the processes (the latter is achieved by calling the ps command).
To make this builtin list the matches only as numbers one could call:
zstyle :completion:::kill: verbose no
Furthermore, if one wanted to see the command lines for processes but not the job texts one could use the
fact that the context name contains the tag name when styles are looked up. As the function for the kill
builtin command uses the tags jobs and processes, we can use:
zstyle :completion:::kill::jobs verbose no
To have more control over when certain values for styles are used one can use the special parameters available in completion widgets (see see zshcompwid(1))) and the e option to zstyle that makes the value be
evaluated when looked up. For example, to make the completer style have a different value when completing for the cvs command, one could use the words special array:
zstyle e :completion: completer
if [[ $words[1] = cvs ]]; then
reply=(_complete)
else
reply=(_complete _approximate)
fi
One should be careful not to use too complicated code with this option, at least for the styles that are looked
up quite often. These are basically those that define some global completion behaviour but allow that to be
different for all matches or groups of matches (such as the menu and listrowsfirst styles). Alternatively
one can always use a less general pattern for the context than in the example above and use a second call to
zstyle with a generic pattern and without using the e option to define the default behaviour.
Note that the order in which styles are defined does not matter; the style mechanism uses the most specific
possible match for a particular style to determine the set of values. More precisely, strings are preferred
over
patterns
(for
example,
:completion::complete:foo
is
more
specific
than
:completion::complete:), and longer patterns are preferred over shorter patterns.
As with tags, completion functions can use any style they choose, so there cant be a complete list. However, the following two sections list those tags and styles that are used in many places of the completion
system.
Standard Tags

Here are the tags currently used by the completion system. Some of them are only used when looking up
styles and do not refer to a particular type of match.
accounts
used to look up the usershosts style
allexpansions
used by the _expand completer when adding the single string containing all possible expansions
allfiles for the names of all files (as distinct from a particular subset, see the globbedfiles tag).
arguments
when an argument of a command may be completed
arrays for names of array parameters

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

associationkeys
for keys of associative arrays; used when completing inside a subscript of a parameter of this type
bookmarks
when completing bookmarks (e.g. for URLs and the zftp function suite)
builtins for names of builtin commands
characters
used for commands like stty when completing characters; also used when completing character
classes after a opening bracket
colormapids
for X colormap ids
colors

for color names

commands
for names of external commands and names of subcommands (used by some commands like cvs)
contexts
for contexts used by the zstyle builtin command
corrections
used by the _approximate and _correct completers for the possible corrections
cursors for cursor names used by X programs
default used to look up default values for various styles that may also be set for tags that are used when
generating matches; note that this tag is used when only the function field of the context name is
set up
descriptions
used when looking up the value of the format style for descriptions
devices for names of device special files
directories
for names of directories
directorystack
for entries in the directory stack
displays
for X display names
domains
for network domains
expansions
used by the _expand completer for individual possibilities resulting from expansion of a word
extensions
for X server extensions
filedescriptors
for the numbers of open file descriptors
files

the generic filematching tag used by completion functions that can complete the names of some
kind of file

fonts

used for X font names

functions
names of functions, normally shell functions although certain commands may understand other
kinds of function

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

globbedfiles
for names of files matching the glob pattern used by completion functions that expect a certain
type of file
groups used when completing names of user groups
historywords
for words from the history
hosts

for hostnames

indexes used for array indexes


jobs

used for jobs

keymaps
for names of zsh keymaps
keysyms
for names of X keysyms
libraries
for names of system libraries
limits

for system limits

localdirectories
for names of directories which are subdirectories of the current working directory when completing for the cd and related builtin commands
manuals
for names of manual pages
maps

for map names (e.g. NIS maps)

messages
used to look up the format style for messages
modifiers
for names of X modifiers
modules
for modules (e.g. zsh modules)
myaccounts
used to look up the usershosts style
nameddirectories
for named directories (you wouldnt have guessed that, would you?)
names for all kinds of names
nicknames
for nicknames of NIS maps
options for command options
original

used by the _approximate, _correct and _expand completers when adding the original string

otheraccounts
used to look up the usershosts style
packages
for packages (e.g. rpm or installed Debian packages)
parameters
for names of parameters

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

pathdirectories
for names of directories found by searching the cdpath array when completing for the cd and
related builtin commands
paths

used to look up the values of the expand, ambiguous and specialdirs styles

pods

for perl pods (documentation files)

ports

for communication ports

prefixes
for prefixes (like those of a URL)
printers
for printer names
processes
for process identifiers
processesnames
used to look up the command style when generating the names of processes for killall
sequences
for sequences (e.g. mh sequences)
sessions
for sessions in the zftp function suite
signals for signal names
strings for strings (e.g. the replacement strings for the cd builtin command)
styles

for styles used by the zstyle builtin command

tags

for tags (e.g. rpm tags)

targets for makefile targets


types

for types of whatever (e.g. address types for the xhost command)

urls

used to look up the urls and local styles when completing URLs

users

for usernames

values when completing a value out of a set of values (or a list of such values)
version used by _call_program to look up the command to run to determine the installed version of various other commands (such as diff and make).
warnings
used to look up the format style for warnings
widgets for zsh widget names
windows
for IDs of X windows
zshoptions
for shell options
Standard Styles

Here are the names of the styles used by the completion system. Note that the values of several of these
styles represent boolean values; here, any of the strings true, on, yes, and 1 can be used for the truth
value true and the strings false, off, no, and 0 are interpreted as false. The behavior for any other
value is undefined unless the description for the particular style mentions other possible values; in particular, the default value may be either on or off if the style is not set.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

Some of these styles are tested for every tag used to add possible matches and for the default tag (most notably menu, listcolors and the styles controlling the completion listing like listpacked and lastprompt).
When tested for the default tag, only the function field of the context will be set up, so the default value
will normally be set like:
zstyle :completion::default menu ...
acceptexact
This is tested for the default tag and the tags used when generating matches. If it is set to true for
at least one match which is the same as the string on the line, this match will immediately be
accepted.
When completing pathnames (where it is looked up for the paths tag), this style also accepts any
number of patterns as the value. If this is used, pathnames matching one of these patterns will be
accepted immediately even if the command line contains some more partially typed pathname
components and these match no file under the directory accepted.
Note that this is also used by the _expand completer to decide if words beginning with a tilde or
parameter expansion should be expanded. This means that if, for example, there are parameters foo
and foobar, the string $foo will only be expanded if acceptexact is set to true.
addspace
This style is used by the _expand completer. If it is true (the default), a space will be inserted
after all words resulting from the expansion (except for directory names which get a slash). The
value may also be the string file to make the completer add a space only to names of existing
files. Finally, the true values and file may be combined with subst to keep the completer
from adding a space when the resulting words were generated by expanding a substitution of the
form $(...) or ${...}.
It is also used by the _prefix completer as a simple boolean value to decide if a space should be
inserted before the suffix.
ambiguous
This applies when completing nonfinal components of filename paths. If it is set, the cursor is
left after the first ambiguous component, even if menu completion is in use. It is tested with the
paths tag.
assignlist
When completing after an equals sign, the completion system normally completes only one
filename. In some cases, particularly for certain parameters such as PATH, a list of filenames
separated by colons is required. This style can be set to a list of patterns matching the names of
such parameters.
The default is to complete lists when the word on the line already contains a colon.
autodescription
If set, this styles value will be used as the description for options which are not described by the
completion functions, but that have exactly one argument. The sequence %d in the value will be
replaced by the description for this argument. Depending on personal preferences, it may be useful to set this style to something like specify: %d. Note that this may not work for some commands.
avoidcompleter
This is used by the _all_matches completer to decide if the string consisting of all matches should
be added to the list currently being generated. Its value is a list of names of completers. If any of
these is the name of the completer that generated the matches in this completion, the string will not
be added.
The default value for this style is _expand _old_list _correct _approximate, i.e. it contains the
completers for which a string with all matches will almost never be wanted.

zsh 4.0.4

Last change: October 26, 2001

10

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

cachepath
This style defines the path where any cache files containing dumped completion data are stored.
Defaults to $ZDOTDIR/.zcompcache, or $HOME/.zcompcache if $ZDOTDIR is not
defined. The completion layer will not be used unless the usecache style is set.
callcommand
Currently this is only used by the function completing make targets. If it is set to true and the
installed version of the make command allows it, make is called in a way to generate all possible
targets. The default value of this style is false because calling make can potentially take a very
long time and in some cases may even cause actions from the makefile be executed despite the
options given to make.
command
In many places, completion functions need to call external commands to generate the list of completions. This style can be used to override the command which is called in some such cases. The
elements of the value are joined with spaces to form a command line to execute. The value can
also start with a hyphen, in which case the usual command will be added to the end; this is most
useful for putting builtin or command in front to make sure the appropriate version of a command is called, for example to avoid calling a shell function with the same name as an external
command.
As an example, the function generating process IDs as matches uses this style with the processes
tag to generate the IDs to complete and the list of processes to display (if the verbose style is
true). The list produced by the command should look like the output of the ps command. The
first line is not displayed, but is searched for the string PID (or pid) to find the position of the
process IDs in the following lines. If the line does not contain PID, the first numbers in each of
the other lines are taken as the process IDs to complete.
Note that the completion function generally has to call the command every time it is called.
Because of that care should be taken to specify only commands that take a short time to run (and
that will eventually stop at all).
commands
This is used by the function completing subcommands for the system initialisation scripts (residing in /etc/init.d or somewhere not too far away from that). Its values give the default commands
to complete for those commands for which the completion function isnt able to find them out
automatically. The default for this style are the two strings start and stop.
complete
This is used by the _expand_alias function when invoked as a bindable command. If it set to
true and the word on the command line is not the name of an alias, matching alias names will be
completed.
completer
The strings given as the value of this style provide the names of the completer functions to use.
The available completer functions are described in the section Control Functions below.
Each string may be the name of a completer function or a string of the form function:name. In
the first case the completer field of the context will contain the name of the completer without the
leading underscore and with all other underscores replaced by hyphens. In the second case the
function is the name of the completer to call, but the context will contain the name in the completer field of the context. If the name starts with a hyphen, the string for the context will be build
from the name of the completer function as in the first case with the name appended to it. For
example:
zstyle :completion: completer _complete _complete:foo
Here, completion will call the _complete completer twice, once using complete and once using
completefoo in the completer field of the context. Normally, using the same completer more

zsh 4.0.4

Last change: October 26, 2001

11

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

than once makes only sense when used with the functions:name form, because otherwise the
context name will be the same in all calls to the completer; possible exceptions to this rule are the
_ignored and _prefix completers.
The default value for this style is _complete _ignored, i.e. normally only completion will be done,
first using the ignoredpatterns style and the $fignore array and then without ignoring matches.
condition
This style is used by the _list completer function to decide if insertion of matches should be
delayed unconditionally. The default is true.
disabled

If this is set to true, the _expand_alias completer and bindable command will try to expand disabled aliases, too. The default is false.

disablestat
This is used with an empty tag by the function completing for the cvs command to decide if the
zsh/stat module should be used to generate names of modified files in the appropriate places (this
is its only use). If set, completion will use the ls command.
domains
If set, gives the names of network domains that should be completed. If this is not set by the user
domain names will be taken from the file /etc/resolv.conf.
expand This style is used when completing strings consisting of multiple parts, such as path names. If one
of its values is the string prefix, the partially typed word from the line will be expanded as far as
possible even if trailing parts cannot be completed. If one of its values is the string suffix,
matching names for components after the first ambiguous one will also be added. This means that
the resulting string is the longest unambiguous string possible, but if menu completion is started
on the list of matches generated this way, this will also cycle through the names of the files in
pathname components after the first ambiguous one.
fakefiles
This style is used when completing files and looked up without a tag. Its values are of the form
dir:names.... This will add the names (strings separated by spaces) as possible matches when
completing in the directory dir, even if no such files really exist.
This can be useful on systems that support special filesystems whose toplevel pathnames can not
be listed or generated with glob patterns. It can also be used for directories for which one does not
have read permission.
fakeparameters
This is used by the completion function generating parameter names as matches. Its values are
names of parameters which might not yet be set, but which should be completed nonetheless.
Each name may also be followed by a colon and a string specifying the type of the parameter (like
scalar, array or integer). If such a type is given, the name will only be completed if parameters of that type are requested in the particular context. Names for which no type is specified will
always be completed.
filepatterns
In most places where filenames are completed, the function _files is used which can be configured
with this style. If the style is unset, _files offers, one after another, up to three tags:
globbedfiles, directories and allfiles, depending on the types of files expected by the caller
of _files.
If the filepatterns style is set, the default tags are not used. Instead, the value of the style says
which tags and which patterns are to be offered. The strings in the value contain specifications of
the form pattern:tag; each string may contain any number of such specifications. The pattern
gives a glob pattern that is to be used to generate filenames. If it contains the sequence %p, that
is replaced by the pattern(s) given by the calling function. Colons in the pattern must be preceded

zsh 4.0.4

Last change: October 26, 2001

12

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

by a backslash to make them distinguishable from the colon before the tag. If more than one pattern is needed, the patterns can be given inside braces, separated by commas. The tags of all
strings in the value will be offered by _files (again, one after another) and used when looking up
other styles. For strings containing more than one specification, the filenames for all specifications
will be generated at the same try. If no :tag is given the files tag will be used. The tag may
also be followed by an optional second colon and a description. If that is given, this description
will be used for the %d in the value of the format style (if that is set) instead of the default
description supplied by the completion function. If the description given here contains itself a
%d, that is replaced with the description supplied by the completion function.
For example, to make the rm command first complete only names of object files and the names of
all files if no object file matches the string on the line, one would do:
zstyle :completion:::rm: filepatterns \
.o:objectfiles %p:allfiles
Another interesting example is to change the default behaviour that makes completion first offer
files matching the patterns given by the calling function, then directories and then all files. Many
people prefer to get both the files matching the given patterns and the directories in the first try and
all files at the second try. To achieve this, one could do:
zstyle :completion: filepatterns \
%p:globbedfiles (/):directories :allfiles
This works even for contexts in which all files would be completed, because _files will not try a
pattern more than once and it stops when the pattern was tried.
Note also that during the execution of completion functions, the EXTENDED_GLOB option is in
effect, so the characters #, and have special meanings in the patterns.
filesort
The completion function that generates filenames as possible matches uses this style without a tag
to determine in which order the names should be listed and completed when using menu completion. The value may be one of size to sort them by the size of the file, links to sort them by the
number of links to the file, modification (or time or date) to sort them by the last
modification time, access to sort them by the last access time, or inode (or change) to sort
them by the last inode change time. If the style is set to any other value, or is unset, files will be
sorted alphabetically by name. If the value contains the string reverse, sorting is done in
decreasing order.
forcelist
This forces a list of completions to be shown at any point where listing is done, even in cases
where the list would usually be suppressed. For example, normally the list is only shown if there
are at least two different matches. By setting this style to always, the list will always be shown,
even if there is only a single match which is immediately accepted. The style may also be set to a
number. In this case the list will be shown if there are at least that many matches, even if they
would all insert the same string.
This style is tested for the default tag and all tags used when generating matches. This allows one
to turn unconditional listing on for certain types of matches.
format If this is set for the descriptions tag, its value is used as a string to display above matches in completion lists. The sequence %d in this string will be replaced with a short description of what
these matches are. This string may also contain the sequences to specify output attributes, such as
%B, %S and %{...%}.
For the same purpose, this style is also tested with the tags used when matches are generated
before it is tested for the descriptions tag. This provides the possibility of defining different format strings for different types of matches.

zsh 4.0.4

Last change: October 26, 2001

13

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

Note also that some completer functions define additional %sequences. These are described for
the completer functions that make use of them.
For the messages tag, this style defines a string used by some completion functions to display
messages. Here, the %d is replaced with a message given by the completion function.
Finally, when set with the warnings tag, the format string is printed when no matches could be
generated at all. In this case the %d is replaced with the descriptions for the matches that were
expected separated by spaces and the sequence %D is replaced with those descriptions separated
by newlines.
The % for the sequences that are replaced by strings provided by the completion functions like
the %d may be followed by field width specifications as described for the zformat builtin command from the zsh/zutil module, see zshmodules(1).
glob

This is used by the _expand completer. If it is set to true (the default), globbing will be
attempted on the words resulting from substitution (see the substitute style) or the original string
from the line.

global If this is set to true (the default), the _expand_alias completer and bindable command will try to
expand global aliases.
groupname
The completion system can put different types of matches in different groups which are then
displayed separately in the list of possible completions. This style can be used to give the names
for these groups for particular tags. For example, in command position the completion system
generates names of builtin and external commands, names of aliases, shell functions and parameters and reserved words as possible completions. To have the external commands and shell functions listed separately, one can set:
zstyle :completion:::command::commands groupname commands
zstyle :completion:::command::functions groupname functions
This also means that if the same name is used for different types of matches, then those matches
will be displayed together in the same group.
If the name given is the empty string, then the name of the tag for the matches will be used as the
name of the group. So, to have all different types of matches displayed separately, one can just set:
zstyle :completion: groupname
All matches for which no group name is defined will be put in a group named default.
grouporder
This style is to be used together with the groupname style. Once different types of matches are
put into different groups, this style can be used to define in which order these groups should appear
when listing (compare tagorder, which determines which completions appear at all). The strings
in the value are taken as group names and the named groups will be shown in the order in which
their names appear in the value. All groups whose names are not given in the value of this style
will appear in the order defined by the function generating the matches.
For example, to have names of builtin commands, shell functions and external commands appear
in this order when completing in command position one would set:
zstyle :completion:::command: grouporder \
builtins functions commands
groups A style holding the names of the groups that should be completed. If this is not set by the user, the
group names from the YP database or the file /etc/group will be used.
hidden If this is set to one of the true values, the matches for the tags for which this is set will not appear
in the list; only the description for the matches as set with the format style will be shown. If this
is set to all, not even the description will be displayed.

zsh 4.0.4

Last change: October 26, 2001

14

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

Note that the matches will still be completed; they are just not shown in the list. To avoid having
matches considered as possible completions at all, the tagorder style can be modified as
described below.
hosts

A style holding the names of hosts that should be completed. If this is not set by the user the hostnames in /etc/hosts will be used.

hostsports
This style is used by commands that need or accept hostnames and ports. The strings in the value
should be of the form host:port. These hostnames and ports are completed depending on the
information already on the line, so that if, for example, the hostname is already typed, only those
ports specified for that host will be completed. Multiple ports for the same host may appear.
ignoreline
This style is tested for the tags used when generating matches. If it is set to true, then none of the
words that are already on the line will be considered possible completions. If it is set to current,
the word the cursor is on will not be considered a possible completion. The same happens if the
value is currentshown, but only if the list of completions is currently shown on the screen.
Finally, if it is set to other all words except the current one will not be considered to be a possible completion.
The values current and currentshown are a bit like the opposite of acceptexact. They mean
that only strings with missing characters will be completed.
Note that you almost certainly dont want to set this to true or other for a general context such
as :completion:. This is because it would disallow completion of, for example, options multiple times even if the command in question accepts the option more than once.
ignoreparents
The style is tested by the function completing pathnames without a tag to determine whether to
ignore the names of directories already mentioned in the current word, or the name of the current
working directory. The value must include one or both of the following strings:
parent The name of any directory whose path is already contained in the word on the line is
ignored. For example, when completing after foo/../, the directory foo will not be considered a valid completion.
pwd

The name of the current working directory will not be completed, so that, for example,
completion after ../ will not use the name of the current directory.

In addition, the value may include one or both of:


..

Ignore the specified directories only when the word on the line contains the substring ../.

directory
Ignore only when names of directories are completed, not when completing names of
files.
Note that names of directories ignored because of one of the tests will be ignored in the same way
as the matches ignored because of the ignoredpatterns style. I.e., by using the _ignored completer it is possible to complete these directories nonetheless.
ignoredpatterns
This style can be used to specify a list of patterns which are tested against against the trial completions in a given context; any matching completions will be removed from the list of possibilities.
The _ignored completer can appear in the list of completers to produce a list which includes these
matches once more. This is a more configurable version of the shell parameter $fignore.
Note that during the execution of completion functions, the EXTENDED_GLOB option is in
effect, so the characters #, and have special meanings in the patterns.
insertids

zsh 4.0.4

Last change: October 26, 2001

15

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

When completing process IDs, for example as arguments to the kill and wait builtins, completion
allows the user to type the name of a command, which will be converted to the appropriate process
ID. A problem arises when the process name typed is not unique. By default (or if this style is set
explicitly to menu) the name will be converted immediately to a set of possible IDs, and menu
completion will be started to cycle through them. If the value of the style is single, however, the
shell will wait until the user has typed enough to make the command unique before converting the
name to an ID; the user must type any additional characters required. If the value is any other
string, menu completion will be started when the string typed by the user is longer than the common prefix of the corresponding IDs.
inserttab
If this has one of the true values, the completion system will insert a TAB character (assuming it
was used to start completion) instead of performing completion when there is no nonblank character to the left of the cursor. If set to false, completion will be done even there.
The value may also contain the substrings pending or pending=val to make the character
typed to start completion be inserted instead of completion being tried when there is input pending
which has not yet been processed by the shell. If a val is given, completion will not be done if
there are at least that many characters of unprocessed input. This is often useful to have set when
pasting characters into a terminal. Note however, that it relies on the $PENDING special parameter from the zsh/zle module being set properly which is not guaranteed on all platforms.
The default value of this style is true unless when completing inside the vared builtin command,
where it defaults to false.
insertunambiguous
This is used by the _match and _approximate completer functions, where the possible completions may not have a common prefix so that menu completion is often the most useful may of
choosing completions. If the style is set to true, the completer will start menu completion only if
no unambiguous string could be generated that is at least as long as the original string typed by the
user. Note that the _approximate completer uses it after setting the completer field in the context
name to one of correctnum or approximatenum, where num is the number of errors that were
accepted.
When used for the _match completer, the style may also be set to the string pattern. This
makes the pattern on the line be left unchanged if it didnt match unambiguously.
keepprefix
This style is used by the _expand completer. If it is true, the completer will try to keep a prefix
containing a tilde or parameter expansion. I.e., the string /f would be expanded to /foo
instead of /home/user/foo. If the style is set to changed (the default), the prefix will only be
left unchanged if there were other changes between the expanded words and the original word
from the command line. Any other value makes the prefix be expanded unconditionally.
Note that with one of the true values, the _expand completer returns if there is only one expansion and that is, after restoring the original prefix, the same as the original word. This means that
other completers will be called immediately after _expand.
lastprompt
This is used to determine if the completion code should try to put the cursor back onto the previous command line after showing a completion listing (as for the ALWAYS_LAST_PROMPT
option). As with several other styles, it is tested for the default tag as well as all the possible tags
when generating matches. The cursor will be moved back to the previous line if this style is true
for all types of matches added. Note also that this is independent of the numeric argument, unlike
the ALWAYS_LAST_PROMPT option.
list

zsh 4.0.4

This style is used by the _history_complete_word bindable command. If it is set to true it has
no effect, but if it is set to false the matches will not be listed, overriding the setting of the
options that control listing behaviour, especially AUTO_LIST. Use the context prefix

Last change: October 26, 2001

16

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

:completion:historywords.
listcolors
If the zsh/complist module is used, this style can be used to set color specifications as with the
ZLS_COLORS and ZLS_COLOURS parameters, which will not be honored under this completion system (see the section The zsh/complist Module in zshmodules(1)).
If this style is set for the default tag, the strings in the value are taken as specifications that are to
be used everywhere. If it is set for other tags, the specifications are used only for matches of the
type described by the tag. For this to work best, the groupname style must be set to an empty
string. If the groupname tag specifies other names for the groups the matches in these groups
can be colored by using these names together with the (group)... syntax described for the
ZLS_COLORS and ZLS_COLOURS parameters and adding the specifications to the value for
this style with the default tag (although in most cases it should work by setting this style for the
appropriate tags).
It is possible to use the same specifications set up for the GNU version of the ls command:
zstyle :completion::default listcolors ${(s.:.)LS_COLORS}
The default colors are the same as for the GNU ls command and can be obtained by setting the
style to an empty string (i.e. ).
listpacked
Like the listcolors style, this is tested with the default tag and all tags used when generating
matches. If it is set to true for a tag, the matches added for it will be listed as if the
LIST_PACKED option were set. If it is set to false, they are listed normally.
listprompt
If this style is set for the default tag, completion lists that dont fit on the screen can be scrolled
(see the description of the zsh/complist module in zshmodules(1)). The value, if not the empty
string, will be displayed after every screenful and the shell will prompt for a key press; if the style
is set to the empty string, a default prompt will be used. The value may contain the escape
sequences %l or %L, which will be replaced by the number of the last line displayed and the
total number of lines; %m or %M, which will be replaced by the number of the last match
shown and the total number of matches; and %p and %P, which will be replaced by Top
when at the beginning of the list, Bottom when at the end and the position shown in percent of
the total length otherwise. In each of these cases the form with the uppercase letter is replaced by
a string of fixed width, padded to the right with spaces. As in other prompt strings, the escape
sequences %S, %s, %B, %b, %U, %u, and %{...%} for entering and leaving the
display modes standout, bold and underline are also available.
listrowsfirst
This style is tested in the same way as the listpacked style and determines if matches are to be
listed in a rowsfirst fashion, as for the LIST_ROWS_FIRST option.
listsuffixes
This style is used by the function used to complete filenames. If completion is attempted on a
string containing multiple partially typed pathname components and this style is set to true, all
components starting with the first one for which more than one match could be generated will be
shown.
local

zsh 4.0.4

This style is used by completion functions which generate URLs as possible matches to add suitable matches when a URL points to a local web server, that is, one whose files are available
directly on the local file system. Its value should consist of three strings: a hostname, the path to
the default web pages for the server and the directory name used by a user placing web pages
within their home area. For example, completion after http://toast/yousir/ will attempt to
match the name toast against the first argument to the style, and if successful will look in the
directory under yousir given by the third argument to the style for possible completions.

Last change: October 26, 2001

17

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

matchoriginal
This is used by the _match completer. If it is set to only, _match will try to generate matches
without inserting a at the cursor position. If set to any other nonempty value, it will first try
to generate matches without inserting the and if that yields no matches, it will try again with
the inserted. If it is unset or set to the empty string, matching will only be done with the
inserted.
matcher
This style is tested for tags used when generating matches. Its value is used as an match
specification additional to any given by the matcherlist style which should be in the form
described in the section Matching Control in zshcompwid(1).
matcherlist
This style is used by the main completion function to retrieve match specifications that are to be
used everywhere. Its value should be a list of such specifications. The completion system will try
them one after another for each completer selected. For example, to first try simple completion
and, if that generates no matches, caseinsensitive completion one would do:
zstyle :completion: matcherlist m:{azAZ}={AZaz}
By default every specification replaces previous ones. If specification is prefixed with +, it is added
to the existing list. This allows testing more general patterns without repeating the whole list every
time, as in:
zstyle :completion: matcherlist +m{aZ}={AZ} +m{AZ}={az}
The style allows even finer control by specifying a particular completer, without the leading underscore, in the third field of the completion context. For example, if one uses the completers _complete and _prefix but wants to try caseinsensitive completion only when using the _complete
completer, one would do:
zstyle :completion: completer _complete _prefix
zstyle :completion::complete: matcherlist \
m:{azAZ}={AZaz}
Note that the completer style allows userdefined names to be used in the context instead of the
name of the completer. This is useful if, for example, one wants to try normal completion without
a match specification and with caseinsensitive matching first, correction if that doesnt generate
any matches and partialword completion if that doesnt yield any matches either. In this case one
can give the _complete completer more than once in the completer style and define different
match specifications for each occurrence, as in:
zstyle :completion: completer _complete _correct _complete:foo
zstyle :completion::complete: matcherlist \
m:{azAZ}={AZaz}
zstyle :completion::foo: matcherlist \
m:{azAZ}={AZaz} r:[_./]= r:=
If the style is unset in any context no match specification is applied; further, some completers such
as _correct and _approximate do not use the match specifications at all. However, it is always
safe to use the simple form for this style (as in the first example above), since any completers
which do not use match specifications will only ever be called once, rather than once per
specification.
Since the specificationstrings in this style have to be tried one after another, it is a good idea to
keep their number low. In most cases one to three strings (each of which may, without to large a
performance hit, consist of more than one single match specification) will give acceptable performance.
maxerrors
This is used by the _approximate and _correct completer functions to determine the maximum

zsh 4.0.4

Last change: October 26, 2001

18

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

number of errors to allow. The completer will try to generate completions by first allowing one
error, then two errors, and so on, until either a match or matches were found or the maximum
number of errors given by this style has been reached.
If the value for this style contains the string numeric, the completer function will take any
numeric argument as the maximum number of errors allowed. For example, with
zstyle :completion::approximate::: maxerrors 2 numeric
two errors are allowed if no numeric argument is given, but with a numeric argument of six (as in
ESC6 TAB), up to six errors are accepted. Hence with a value of 0 numeric, no correcting
completion will be attempted unless a numeric argument is given.
If the value contains the string notnumeric, the completer will not try to generate corrected
completions when given a numeric argument, so in this case the number given should be greater
than zero. For example, 2 notnumeric specifies that correcting completion with two errors will
usually be performed, but if a numeric argument is given, correcting completion will not be performed.
The default value for this style is 2 numeric.
menu

If this is set to true in a given context, using any of the tags defined for a given completion, menu
completion will be used. The tag default can be used to set the default value, but a specific tag
will take precedence. If none of the values found in this way is true but at least one is set to auto
the behaviour will be as for the AUTO_MENU option. Finally, if one of the values is explicitly
set to false, menu completion will be turned off even if it would otherwise be active (for example,
with the MENU_COMPLETE option).
Using the form yes=num, where yes may be any of the true values (yes, true, on and 1)
turns on menu completion if there at least num matches. Using this for one of the false values (as
in no=10) makes menu completion not be used if there are num or more matches. Of course, this
is only useful when menu completion is normally used, e.g. by setting the MENU_COMPLETE
option. The true values may also be used in the form yes=long to turn on menu completion if
the list does not fit onto the screen. This will start menu completion only if normal completion
was attempted, not when only the list of possible completions was requested. To start menu completion even then, the value yes=longlist can be used.
In addition to (or instead of) the above possibilities, the value may contain the string select,
optionally followed by an equals sign and a number. In this case menu selection (as defined by the
zsh/complist module) will be started. Without the optional number, it will be started unconditionally and with a number it will be started only if at least that many matches are generated; if the
values for more than one tag provide a number, the smallest number is taken. Menu selection can
be turned off explicitly by defining a value containing the string noselect.
It is also possible to start menu selection only if the list of matches does not fit on the screen by
using the value select=long. This will only start menu selection if the widget invoked does completion, not simply listing as done by deletecharorlist; to start menu selection even here, use
the value select=longlist.
To turn on menu completion or menu selection when a certain number of matches is generated or
the list of matches does not fit onto the screen, both of yes= and select= can be given twice,
once with a number and once with long or longlist.

numbers
This is used with the jobs tag. If it is true, the shell will complete the job numbers instead of the
shortest unambiguous strings of the jobs command lines. If the value is a number, job numbers
will only be used if that many words from the job descriptions are required to resolve ambiguities.
For example, if the value is 1, strings will only be used if all jobs differ in the first word on their
command lines.
oldlist This is used by the _oldlist completer. If it is set to always, then standard widgets which

zsh 4.0.4

Last change: October 26, 2001

19

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

perform listing will retain the current list of matches, however they were generated; this can be
turned off explicitly with the value never, giving the behaviour without the _oldlist completer.
If the style is unset, or any other value, then the existing list of completions is displayed if it is not
already; otherwise, the standard completion list is generated; this is the default behaviour of
_oldlist. However, if there is an old list and this style contains the name of the completer function
that generated the list, then the old list will be used even if it was generated by a widget which
does not do listing.
For example, suppose you type Xc to use the _correct_word widget, which generates a list of
corrections for the word under the cursor. Usually, typing D would generate a standard list of
completions for the word on the command line, and show that. With _oldlist, it will instead show
the list of corrections already generated.
As another example consider the _match completer: with the insertunambiguous style set to
true it inserts only a common prefix string, if there is any. However, this may remove parts of
the original pattern, so that further completion could produce more matches than on the first
attempt. By using the _oldlist completer and setting this style to _match, the list of matches generated on the first attempt will be used again.
oldmatches
This is used by the _all_matches completer to decide if an old list of matches should be used if
one exists. It may be set to one of the true values or to the string only to use such a list. If it is
set to only, _all_matches will only use an old list and wont have any effect on the list of
matches currently being generated.
oldmenu
This is used by the _oldlist completer. It controls how menu completion behaves when a completion has already been inserted and the user types a standard completion key type such as TAB.
The default behaviour of _oldlist is that menu completion always continues with the existing list
of completions. If this style is set to false, however, a new completion is started if the old list
was generated by a different completion command; this is the behaviour without the _oldlist completer.
For example, suppose you type Xc to generate a list of corrections, and menu completion is
started in one of the usual ways. Usually, or with this style set to false, typing TAB at this point
would start trying to complete the line as it now appears. With _oldlist, it instead continues to
cycle through the list of corrections.
original

This is used by the _approximate and _correct completers to decide if the original string should
be added as one possible completion. Normally, this is done only if there are at least two possible
corrections, but if this style is set to true, it is always added. Note that these completers use this
style after setting the completer field in the context name to correctnum or approximatenum,
where num is the number of errors that were accepted.

packageset
This style is used when completing arguments of the Debian dpkg program. It contains an override for the default package set for a given context. For example,
zstyle :completion::complete:dpkg:option status1: \
packageset avail
causes available packages, rather than only installed packages, to be completed for dpkg
status.

zsh 4.0.4

path

The function that completes color names uses this style with the colors tag. The value should be
the pathname of a file containing color names in the format of an X11 rgb.txt file. If the style is
not set but this file is found in one of various standard locations it will be used as the default.

ports

A style holding the service names of ports to complete. If this is not set by the user, the service

Last change: October 26, 2001

20

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

names from /etc/services will be used.


prefixhidden
This is used when matches with a common prefix are added (e.g. option names). If it is true, this
prefix will not be shown in the list of matches.
The default value for this style is false.
prefixneeded
This, too, is used for matches with a common prefix. If it is set to true this common prefix has to
be typed by the user to generate the matches. E.g. for options this means that the , +, or
has to be on the line to make option names be completed at all.
The default style for this style is true.
preserveprefix
This style is used when completing path names. Its value should be a pattern matching an initial
prefix of the word to complete that should be left unchanged under all circumstances. For example, on some Unices an initial // (double slash) has a special meaning and hence should be kept.
For that one could set this style to the string //. As another example, setting this style to ?:/
under Cygwin would allow completion after a:/... and the like.
range

This is used by the _history completer and the _history_complete_word bindable command to
decide which words should be completed. It may be set to a number, N, to say that only the last N
words from the history should be completed. The value may also be of the form max:slice. This
means that first the last slice words will be completed. If that yields no matches, the slice words
before those will be tried and so on, until either at least one match is generated or max words have
been tried. The default is to complete all words from the history at once.

regular This style is used by the _expand_alias completer and bindable command. If set to true (the
default), regular aliases will be expanded but only in command position. If it is set to false, regular aliases will never be expanded and if it is set to the string always, regular aliases will be
expanded even if not in command position.
removealldups
The _history_complete_word bindable command and the _history completer use this to decide if
all duplicate matches should be removed, rather than just consecutive duplicates.
selectprompt
If this is set for the default tag, its value will be displayed during menu selection (see the menu
style above) when the completion list does not fit on the screen as a whole. The same escapes as
for the listprompt style are understood, but give the number of the match or line the mark is on.
A default prompt is used when the value is the empty string.
selectscroll
This style is tested for the default tag and determines how a completion list is scrolled during a
menu selection (see the menu style above) when the completion list does not fit on the screen as a
whole. Its value should be 0 (zero) to scroll by halfscreenfuls, a positive integer to scroll by
that many lines and a negative number to scroll by the number of lines of the screen minus that
number (or plus the number, since it is negative). The default is to scroll by single lines.
singleignored
This is used by the _ignored completer. It specifies what should be done if it can generate only
one match, which is often a special case. If its value is show, the single match will be displayed
but not inserted. If the value is menu, then the single match and the original string are both
added as matches and menu completion is started so that one can easily select either of them.
sort

zsh 4.0.4

If set to true, completion functions that generate words from the history as possible matches sort
these words alphabetically instead of keeping them in the order in which they appear in the history
(from youngest to oldest).

Last change: October 26, 2001

21

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

This is also used by the _expand completer. Here, if it is set to true, the expansions generated
will always be sorted. If it is set to menu, then the expansions are only sorted when they are
offered as single strings (not in the string containing all possible expansions).
specialdirs
Normally, the completion code will not produce the directory names . and .. as possible completions. If this style is set to true, it will add both . and .. as possible completions; if it is set
to .., only .. will be added.
squeezeslashes
If set to true, sequences of slashes (as in foo//bar) will be treated as if they were only one slash
when completing pathnames. This is the usual behaviour of UNIX paths. However, by default the
file completion function behaves as if there were a between the slashes.
stop

If set to true, the _history_complete_word bindable command will stop once when reaching the
beginning or end of the history. Invoking _history_complete_word will then wrap around to the
opposite end of the history. If this style is set to false (the default), _history_complete_word
will loop immediately as in a menu completion.

substglobsonly
This is used by the _expand completer. If it is set to true, the expansion will only be used if it
resulted from globbing; hence, if expansions resulted from the use of the substitute style
described below, but these were not further changed by globbing, the expansions will be rejected.
The default for this style is false.
substitute
This boolean style controls whether the _expand completer will first try to expand all substitutions
in the string (such as $(...) and ${...}).
The default is true.
suffix

This is used by the _expand completer if the word starts with a tilde or contains a parameter
expansion. If it is set to true, the word will only be expanded if it doesnt have a suffix, i.e. if it is
something like foo or $foo, but not if it is foo/ or $foo/bar, unless that suffix itself contains characters eligible for expansion. The default for this style is true.

tagorder
This provides a mechanism for sorting how the tags available in a particular context will be used.
The values for the style are sets of spaceseparated lists of tags. The tags in each value will be
tried at the same time; if no match is found, the next value is used. (See the filepatterns style for
an exception to this behavior.)
For example:
zstyle :completion::complete:command: tagorder \
commands functions
specifies that completion in command position should offer only completions for external commands and shell functions immediately.
In addition to tag names, each string in the value may take one of the following forms:

If any string in the value consists of only a hyphen, then only the tags specified by the
other strings in the value are generated. Normally all tags not explicitly selected are tried
last if the specified tags fail to generate any matches. This means that a value consisting
only of a single hyphen turns off completion.

! tags... A string starting with an exclamation mark specifies names of tags that are not to be used.
The effect is the same as if all other possible tags for the context had been listed.
tag:label ...
In strings not starting with an exclamation mark, it is also possible to specify tag labels

zsh 4.0.4

Last change: October 26, 2001

22

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

instead of only tags, where tag is one of the tags offered by the completion function for
the current context and label is a name. For this, the completion function will generate
matches in the same way as for the tag but it will use the label in place of the tag in the
context names used to look up styles. If the label starts with a hyphen, the tag is
prepended to the label to form the name used for lookup. This can be used to make the
completion system try a certain tag more than once, supplying different style settings for
each attempt, see below for an example.
The label may optionally be followed by a second colon and a description. This description will then be used for the %d in the value of the format style instead of the default
description supplied by the completion function. Spaces in the description have to be
quoted by preceding them with a backslash and a %d appearing in the description is
replaced with the description given by the completion function.
In each of the cases above, the tag may also be a pattern or more than one pattern inside braces and
separated by commas. In this case all of the offered tags matching the pattern(s) will be used except for
those that are given explicitly in the same string. There are probably two main uses of this. One is the case
where one wants to try one of the tags more than once, setting other styles differently for each try, but still
wants to use all the other tags without having to repeat them all. For example, to make completion of function names in command position ignore all the completion functions starting with an underscore the first
time completion is tried, one could do:
zstyle :completion:::command: tagorder \
functions:noncomp functions
zstyle :completion::functionsnoncomp ignoredpatterns _
Here, the completion system will first try all tags offered, but will use the tag label functionsnoncomp
when looking up styles for the function names completed. For this, the ignoredpatterns style is set to
exclude functions starting with an underscore from the set of possible matches. If none of the generated
matches match the string on the line, the completion system will use the second value of the tagorder
style and complete functions names again, but this time using the name functions to look up styles, so that
the ignoredpatterns style is not used and all function names are considered.
Of course, this can also be used to split the matches for one tag into different groups. For example:
zstyle :completion: tagorder \
options:long:long\ options
options:short:short\ options
options:singleletter:single\ letter\ options
zstyle :completion::optionslong ignoredpatterns [+]([])
zstyle :completion::optionsshort ignoredpatterns [+]?
zstyle :completion::optionssingleletter ignoredpatterns ???
With the groupnames style set, this makes options beginning with , options beginning with a single
or + but containing multiple characters, and singleletter options be displayed in separate groups with
different descriptions.
The second interesting use of patterns is the case where one wants to try multiple match specifications one
after another. The matcherlist style offers something similar, but it is tested very early in the completion
system and hence cant be set for single commands nor for more specific contexts. Here is how to try normal completion without any match specification and, if that generates no matches, try again with
caseinsensitive matching, restricting the effect to arguments of the command foo:
zstyle :completion:::foo: tagorder :case
zstyle :completion:case matcher m:{az}={AZ}
First, all the tags offered when completing after foo are tried using the normal tag name. If that generates
no matches, the second value of tagorder is used, which tries all tags again except that this time each has
case appended to its name for lookup of styles. Hence this time the value for the matcher style from the

zsh 4.0.4

Last change: October 26, 2001

23

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

second call to zstyle in the example is used to make completion caseinsensitive.


Using the e option of the zstyle builtin command, it is possible to specify conditions saying when certain
tags are to be used. For example:
zstyle e :command: tagorder
if [[ n $PREFIX ]]; then
reply=( )
else
reply=( )
fi
Makes completion in command position happen only if the string on the line is not empty. This is tested
using the PREFIX parameter which is special in completion widgets; see zshcompwid for a description of
these special parameters. Setting reply to an empty array ensures that only the default behaviour of trying
all tags at once is used and setting it to an array containing only a hyphen disables that default behaviour
thus keeping all tags from being tried.
If no style has been defined for a context, the strings ()argument ()option values and
options plus all tags offered by the completion function will be used to provide a sensible default
behavior that causes arguments (whether normal command arguments or arguments of options) to be completed before option names for most commands.
urls
This is used together with the the urls tag by completion functions that generate URLs as possible matches.
If the value consists of more than one string or if the only string does not name a file or directory, the
strings are used as the URLs to complete.
If the value contains only one string and that is the name of a normal file, the URLs are taken from that file
(where the URLs may be separated by white space or newlines).
Finally, if the only string in the value names a directory, that should contain subdirectories named after the
retrieval methods which occur as the first part of a URL, i.e. http, ftp, bookmark, and so on. These
subdirectories should contain files and other subdirectories whose pathnames are possible completions
after the initial http://, ftp://, etc. See the description in the file _urls in the User subdirectory of the
completion system for more information.
usecache
If this is set, the completion caching layer is activated for any completions which use it (via the
_store_cache, _retrieve_cache, and _cache_invalid functions). The directory containing the cache files
can be changed with the cachepath style.
usecompctl
If this style is set to a string not equal to false, 0, no, and off, the completion system may use any completion specifications defined with the compctl builtin command. If the style is unset, this is done only if the
zsh/compctl module is loaded. The string may also contain the substring first to make the definition for
compctl T be used, and the substring default to make the one for compctl D be used.
Note that this is only intended to smooth the transition from compctl to the new completion system and
may disappear in the future.
Note also that the definitions from compctl will only be used if there is no specific completion function for
the command in question. For example, while completing arguments to the command foo, if this was handled by a command function _foo, compctl would never be tried, while if it was handled by _default,
compctl would be tried.
users
This may be set to a list of names that should be completed whenever a username is needed. If it is not set
or the string on the line doesnt match any of the strings in this list, all usernames will be completed.
usershosts

zsh 4.0.4

Last change: October 26, 2001

24

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

The values of this style should be of the form user@host or user:host. It is used for commands that need
pairs of user and hostnames. For such commands, only the pairs from this style are used and if, for example, the username is already typed, then only the hostnames for which there is a pair with that username is
defined.
If set for the myaccounts tag, this is used for commands such as rlogin and ssh; in this case the style
should contain the names of the users own accounts on remote hosts. If set for the otheraccounts tag, it
is used for commands such as talk and finger and should contain other peoples accounts. Finally, it may
also be used by some commands with the accounts tag.
usershostsports
Like usershosts but used for commands like telnet and containing strings of the form user@host:port.
verbose
This is used in several contexts to decide if only a simple or a verbose list of matches should be generated.
For example some commands show descriptions for option names if this style is true.
The default value for this style is true.
word
This is used by the _list completer, which prevents the insertion of completions until a second completion
attempt when the line has not changed. The normal way of finding out if the line has changed is to compare
its entire contents between the two occasions. If this style is true, the comparison is instead performed only
on the current word. Hence if completion is performed on another word with the same contents, completion will not be delayed.
CONTROL FUNCTIONS

The initialization script compinit redefines all the widgets which perform completion to call the supplied
widget function _main_complete. This function acts as a wrapper calling the socalled completer functions that generate matches. If _main_complete is called with arguments, these are taken as the names of
completer functions to be called in the order given. If no arguments are given, the set of functions to try is
taken from the completer style. For example, to use normal completion and correction if that doesnt generate any matches:
zstyle :completion: completer _complete _correct
after calling compinit. The default value for this style is _complete _ignored, i.e. normally only ordinary
completion is tried, first with the effect of the ignoredpatterns style and then without it. The
_main_complete function uses the return value of the completer functions to decide if other completers
should be called. If the return value is zero, no other completers are tried and the _main_complete function returns.
If the first argument to _main_complete is a single hyphen, the arguments will not be taken as names of
completers. Instead, the second argument gives a name to use in the completer field of the context and the
other arguments give a command name and arguments to call to generate the matches.
The following completer functions are contained in the distribution (users may write their own):
_all_matches
This completer can be used to add a string consisting of all other matches. To ensure, that this
string is always added, this completer has to be used as the first completer in the list. The
avoidcompleter style is used to decide if the string should be added. This will only be done if
the matches were generated by a completer not named by one of the values of the style.
This function also uses the style oldmatches. If it is set to true or to the string only and there
is a list of matches from a previous completion, those matches will be inserted in the command
line. If it is set to the the string only, it will only insert an old list and wont add the string for all
matches of the list currently being generated.

zsh 4.0.4

Last change: October 26, 2001

25

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

With the oldmatches style set, this completer should probably not be called unconditionally.
Instead one could use the e option of the zstyle builtin command to add a condition to the completer or to the oldmatches style. Alternatively, one could use the _generic function to bind
_all_matches to a separate key binding, for example:
zle C allmatches completeword _generic
bindkey Xa allmatches
zstyle :completion:allmatches: oldmatches only
zstyle :completion:allmatches: completer _all_matches
_approximate
This completer function uses the _complete completer to generate a list of strings for the context
the cursor is currently in, allowing you to specify a maximum number of errors: see the description of approximate matching in zshexpn(1) for how errors are counted. The resulting list of
corrected and completed strings is then presented to the user. The intended use of this completer
function is to try after the normal _complete completer by setting:
zstyle :completion: completer _complete _approximate
This will give correcting completion if and only if normal completion yields no possible completions. When corrected completions are found, the completer will normally start menu completion
allowing you to cycle through these strings.
This completer uses the tags corrections and original when generating the possible corrections
and the original string. The format style for the former may contain the additional sequences
%e and %o which will be replaced by the number of errors accepted to generate the corrections and the original string, respectively.
As with all completers, _approximate uses its name without the underscore in the completer field
of the context name. Once it has started trying to generate matches, it will append a minus sign
and the number of errors accepted to its name. _approximate will first look for completions with
one error, then two, and on so up to the limit on the number of errors set by the maxerrors style.
Hence on the first try the completer field of the context contains approximate1, on the second
try approximate2, and so on.
When _approximate is called from another function, the number of errors to accept may be given
with the a option. Its argument should be the same as the value of the maxerrors style, all in
one string.
Note that this completer (and the _correct completer mentioned below) can be quite expensive to
call, especially when a large number of errors are allowed. One way to avoid this is to set up the
completer style using the e option to zstyle so that some completers are only used when completion is attempted a second time on the same string, e.g.:
zstyle :completion: completer
if [[ $_last_try != " $HISTNO$BUFFER$CURSOR" ]]; then
_last_try=" $HISTNO$BUFFER$CURSOR"
reply=(_complete _match _prefix)
else
reply=(_ignored _correct _approximate)
fi
This uses the HISTNO parameter and the BUFFER and CURSOR special parameters that are
available inside zle and completion widgets to find out if the command line hasnt changed since
the last time completion was tried. Only then are the _ignored, _correct and _approximate completers called.
_complete
This completer generates all possible completions in a contextsensitive manner, i.e. using the settings defined with the compdef function explained above and the current settings of all special

zsh 4.0.4

Last change: October 26, 2001

26

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

parameters. This gives the normal completion behaviour.


To complete arguments of commands, _complete uses the utility function _normal, which is in
turn responsible for finding the particular function; it is described below. Various contexts of the
form context, as mentioned above for the #compdef tag, are handled specially. These are:
arrayvalue
for completion on the right hand side of an arrayassignment (foo=(...)).
braceparameter
for completing the name of a parameter expansion within braces (${...}).
command
for completing in a command position.
condition
for completion inside conditions ([[...]]).
default
for generating completions when no special completion function is used.
equal
for completion of words beginning with an equals sign
first for adding completions before any other completion functions are tried; if this function
sets the _compskip parameter to all, no other completion functions will be called, if it is
set to a string containing the substring patterns, no pattern completion functions will be
called, and if it is set to a string containing default the function for the default context will not be called, but functions defined for commands will.
math for completion inside mathematical contexts, such as ((...)).
parameter
for completing the name of a parameter expansion ($...).
redirect
for completion after a redirection operator.
subscript
for completion inside subscripts.
tilde for completion after a tilde () character, but before a slash.
value for completion on the right hand side of an assignment.
Default implementations are supplied for each of these contexts, in most cases named after the
context itself (e.g. completion for the tilde context is done by the function named _tilde).
Before trying to find a function for a specific context, _complete checks if the parameter compcontext is set. If it is set to an array, the elements are taken to be the possible matches which will
be completed using the tag values and the description value. If it is set to an associative array,
the keys are used as the possible completions and the values (if nonempty) are used as descriptions for the matches. If compcontext is set to a string containing colons, it should be of the
form tag:descr:action. In this case the tag and descr give the tag and description to use and the
action says what should be completed in one of the forms described for the _arguments utility
function below.
Finally, if compcontext is set to a string without colons, the value is taken as the name of the
context to use and the function defined for that context will be called. For this purpose, there is a
special context named commandline that completes whole command lines (commands and
their arguments) and is not used by the completion system itself, but has a function handling completion for it.
_correct

zsh 4.0.4

Last change: October 26, 2001

27

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

Generate corrections, but not completions, for the current word; this is similar to _approximate
but will not allow any number of extra characters at the cursor as that completer does, hence this is
similar to spellchecking. It calls _approximate but uses a different completer field in the context
name.
For example, with:
zstyle :completion::::: completer _complete _correct _approximate
zstyle :completion::correct::: maxerrors 2 notnumeric
zstyle :completion::approximate::: maxerrors 3 numeric
correction will accept up to two errors. If a numeric argument is given, correction will not be performed, but correcting completion will be, and will accept as many errors as given by the numeric
argument. Without a numeric argument, first correction and then correcting completion will be
tried, with the first one accepting two errors and the second one accepting three errors.
When _correct is called as a function, the number of errors to accept may be given following the
a option. The argument should be the same as the value of the accept style, all in one string.
This completer function is intended to be used without the _approximate completer or, as in the
example, just before it. Using it after the _approximate completer is useless since _approximate
will at least generate the corrected strings generated by the _correct completer and probably
more.
_expand
This completer function does not really do completion, but instead checks if the word on the command line is eligible for expansion and, if it is, gives detailed control over how this expansion is
done. When using this, one should not use the expandorcomplete widget, but instead use
completeword, as expandorcomplete will expand the string on the line before the completion
widget is called. Also, this completer should be called before the _complete completer function.
The tags used when generating expansions are allexpansions for the string containing all possible expansions, expansions when adding the possible expansions as single matches and original
when adding the original string from the line. In which order these strings are generated and
which of these strings are generated at all can be controlled by using the grouporder style and by
modifying the tagorder style, as usual.
The format string for allexpansions and for expansions may contain the sequence %o which
will be replaced by the original string from the line.
Which kind of expansion is tried is controlled by the substitute, glob and substglobsonly
styles.
When _expand is called as a function, the different modes may be selected with options. The s
to substitute, g to glob and o to substglobsonly.
_expand_alias
If the word the cursor is on is an alias, it is expanded and no other completers are called. The
types of aliases which are to be expanded can be controlled with the regular, global and disabled
styles.
This function is also a bindable command, see the section Bindable Commands below.
_history
Complete words from the shells command history. This completer uses the removealldups,
and sort styles also used by the _history_complete_word bindable command, see the section
Bindable Commands below and the section Completion System Configuration above.
_ignored
The ignoredpatterns style can be set to a list of patterns which are compared against possible
completions; matching ones are removed. With this completer those matches can be reinstated, as
if no ignoredpatterns style were set. The completer actually generates its own list of matches;

zsh 4.0.4

Last change: October 26, 2001

28

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

which completers are used for this is determined in the same way as for the _prefix completer.
The singleignored style is used if only one match could be generated. It can be set to show to
prevent that match from being displayed or inserted into the line, or it can be set to menu, in
which case the single match and the original string from the line will be offered in a menu completion.
_list

This completer allows one to delay the insertion of matches until completion is attempted a second
time without the word on the line being changed. On the first attempt, only the list of matches will
be shown. It is affected by the styles condition and word, see the section Completion System
Configuration above.

_match This completer is intended to be used after the _complete completer. It allows one to give patterns
on the command line and to complete all strings matching these patterns from the set of possible
completions for the context the cursor is in, without having to set the GLOB_COMPLETE
option.
Normally this will be done by taking the pattern from the line, inserting a at the cursor position
and comparing the resulting pattern with the possible completions generated. However, if the
matchoriginal style has a value of only, no will be inserted. If matchoriginal has any other
nonempty string as its value, this completer will first try to generate matches without, then with a
inserted at the cursor position.
The generated matches will be offered in a menu completion unless the insertunambiguous style
is set to true. In this case menu completion will only be started if no unambiguous string could
be generated that is at least as long as the original string. The style may also be set to the string
pattern. This will keep the pattern on the line intact as long as there isnt an unambiguous completion with which it could be replaced.
Note that the matcher specifications defined globally or used by the completion functions will not
be used.
_menu This completer is a simple example function implemented to show how menu completion can be
done in shell code. It should be used as the first completer and has the effect of making the code
perform menu completion. Note that this is independent of the setting of the
MENU_COMPLETE option and does not work with the other menu completion widgets such as
reversemenucomplete, or acceptandmenucomplete.
_oldlist This completer controls how the standard completion widgets behave when there is an existing list
of completions which may have been generated by a special completion (i.e. a separatelybound
completion command). It allows the ordinary completion keys to continue to use the list of completions thus generated, instead of producing a new list of ordinary contextual completions. It
should appear in the list of completers before any of the widgets which generate matches. It uses
two styles: oldlist and oldmenu, see the section Completion System Configuration above.
_prefix This completer can be used to try completion with the suffix (everything after the cursor) ignored.
In other words, the suffix will not be considered to be part of the word to complete and hence does
not need to be matched. It uses the completer style to decide which other completers to call to try
to generate matches. If this style is unset, the list of completers set for the current context is used
except, of course, the _prefix completer itself. Furthermore, if this completer appears more
than once in the list of completers only those completers not already tried by the last invocation of
_prefix will be called.
For example, consider this global completer style:
zstyle :completion: completer \
_complete _prefix _correct _prefix:foo
Here, the _prefix completer tries normal completion but ignoring the suffix. If that doesnt generate any matches, and neither does the call to the _correct completer after it, _prefix will be
called a second time and, now only trying correction with the suffix ignored. If you want to use

zsh 4.0.4

Last change: October 26, 2001

29

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

_prefix as the last resort and try only normal completion, you can use:
zstyle :completion: completer _complete ... _prefix
zstyle :completion::prefix: completer _complete
The addspace style is also used. If it is set to true then _prefix will insert a space between the
matches generated (if any) and the suffix.
Note that this completer is only useful if the COMPLETE_IN_WORD option is set; otherwise,
the cursor will be moved to the end of the current word before the completion code is called and
hence there will be no suffix.
BINDABLE COMMANDS

In addition to the contextdependent completions provided, which are expected to work in an intuitively
obvious way, there are a few widgets implementing special behaviour which can be bound separately to
keys. The following is a list of these and their default bindings.
_bash_completions
This function is used by two widgets, _bash_completeword and _bash_listchoices. It exists to
provide compatibility with completion bindings in bash. The last character of the binding determines what is completed: !, command names; $, environment variables; @, host names; /,
file names; user names. In bash, the binding preceded by \e gives completion, and preceded
by X lists options. As some of these bindings clash with standard zsh bindings, only \e and
X are bound by default. To add the rest, the following should be added to .zshrc after compinit has been run:
for key in ! $ @ / ; do
bindkey " \e$key" _bash_completeword
bindkey " X$key" _bash_listchoices
done
This includes the bindings for in case they were already bound to something else; the completion code does not override user bindings.
_correct_filename (XC)
Correct the filename path at the cursor position. Allows up to six errors in the name. Can also be
called with an argument to correct a filename path, independently of zle; the correction is printed
on standard output.
_correct_word (Xc)
Performs correction of the current argument using the usual contextual completions as possible
choices. This stores the string correctword in the function field of the context name and then
calls the _correct completer.
_expand_alias (Xa)
This function can be used as a completer and as a bindable command. It expands the word the cursor is on if it is an alias. The types of aliases expanded can be controlled with the regular, global
and disabled styles.
When used as a bindable command there is one additional feature that can be selected by setting
the complete style to true. In this case, if the word isnt the name of an alias, _expand_alias
tries to complete the word to a full alias name without expanding it (but leaving the cursor directly
after the completed word so that invoking _expand_alias once more will expand the
nowcomplete alias name).
_expand_word (Xe)
Performs expansion on the current word: equivalent to the standard expandword command, but
using the _expand completer. Before calling it, the function field is set to expandword.
_generic
This function is not defined as a widget and not bound by default. However, it can be used to

zsh 4.0.4

Last change: October 26, 2001

30

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

define a widget and will then store the name of the widget in the function field of the context and
call the completion system. This allows custom completion widgets with their own set of style settings to be easily defined. For example, to define a widget that does normal completion and starts
menu selection, one could do:
zle C foo completeword _generic
bindkey ... foo
zstyle :completion:foo: menu yes select=1
_history_complete_word (\e/)
Complete words from the shells command history. This uses the list, removealldups, sort, and
stop styles.
_most_recent_file (Xm)
Complete the name of the most recently modified file matching the pattern on the command line
(which may be blank). If given a numeric argument N, complete the Nth most recently modified
file. Note the completion, if any, is always unique.
_next_tags (Xn)
This command alters the set of matches used to that for the next tag, or set of tags, either as given
by the tagorder style or as set by default; these matches would otherwise not be available. Successive invocations of the command cycle through all possible sets of tags.
_read_comp (XR)
Prompt the user for a string, and use that to perform completion on the current word. There are
two possibilities for the string. First, it can be a set of words beginning _, for example _files /,
in which case the function with any arguments will be called to generate the completions. Unambiguous parts of the function name will be completed automatically (normal completion is not
available at this point) until a space is typed.
Second, any other string will be passed as a set of arguments to compadd and should hence be an
expression specifying what should be completed.
A very restricted set of editing commands is available when reading the string: DEL and H
delete the last character; U deletes the line, and C and G abort the function, while RET
accepts the completion. Note the string is used verbatim as a command line, so arguments must be
quoted in accordance with standard shell rules.
Once a string has been read, the next call to _read_comp will use the existing string instead of
reading a new one. To force a new string to be read, call _read_comp with a numeric argument.
_complete_debug (X?)
This widget performs ordinary completion, but captures in a temporary file a trace of the shell
commands executed by the completion system. Each completion attempt gets its own file. A
command to view each of these files is pushed onto the editor buffer stack.
_complete_help (Xh)
This widget displays information about the context names, the tags, and the completion functions
used when completing at the current cursor position. If given a numeric argument other than 1 (as
in ESC2 Xh), then the styles used and the contexts for which they are used will be shown, too.
Note that the information about styles may be incomplete; it depends on the information available
from the completion functions called, which in turn is determined by the users own styles and
other settings.
_complete_tag (Xt)
This widget completes symbol tags created by the etags or ctags programmes (note there is no
connection with the completion systems tags) stored in a file TAGS, in the format used by etags,
or tags, in the format created by ctags. It will look back up the path hierarchy for the first
occurrence of either file; if both exist, the file TAGS is preferred. You can specify the full path to
a TAGS or tags file by setting the parameter $TAGSFILE or $tagsfile respectively. The

zsh 4.0.4

Last change: October 26, 2001

31

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

corresponding completion tags used are etags and vtags, after emacs and vi respectively.
UTILITY FUNCTIONS

Descriptions follow for utility functions that may be useful when writing completion functions. Most of
these reside in the Base subdirectory. Like the example functions for commands in the distribution, the utility functions generating matches all follow the convention of returning zero if they generated completions
and nonzero if no matching completions could be added.
When writing completion functions or other ZLE widgets that call completion, it might be interesting to
know about two more features offered by the _main_complete function. The arrays compprefuncs and
comppostfuncs may be set to contain names of functions that are to be called immediately before or after
completion has been tried. The functions will only be called once, unless they put themselves into the
arrays again.
_all_labels [ 12VJ ] tag name descr [ command args ... ]
This is a convenient interface to the _next_label function below, implementing the loop shown in
the _next_label example. The command is the one that should be called to generate the matches.
The options stored in the parameter name will automatically be inserted into the args given to the
command. Normally, they are put directly after the command, but if one of the args is a single
hyphen, they are inserted directly before that. If the hyphen is the last argument, that will be
removed from the argument list before the command is called. This allows _all_labels to be used
in almost all cases where the matches can be generated by a single call to the compadd builtin
command or by a call to one of the utility functions.
For example:
local expl
...
if _requested foo; then
...
_all_labels foo expl ... compadd ... $matches
fi
Will complete the strings from the matches parameter, using compadd with additional options
which will take precedence over those generated by _all_labels.
_alternative [ C name ] specs ...
This function is useful in simple cases where multiple tags are available. Essentially, it implements a loop like the one described for the _tags function above.
The tags to use and the action to perform if a tag is requested are described using the specs which
are of the form: tag:descr:action. The tags are offered using _tags and if the tag is requested, the
action is executed with the given description descr. The actions supported are those used by the
_arguments function (described below), without the >state and =... forms.
For example, the action may be a simple function call. With that one could do:
_alternative \
users:user:_users \
hosts:host:_hosts
to offer usernames and hostnames as possible matches (which are generated by the _users and
_hosts functions respectively).
Note that, like _arguments this will also use _all_labels to execute the actions, so one doesnt
need to call that explicitly unless another tag is to be used, for example in a function called from
_alternative.
Like _tags this function supports the C option to give a different name for the argument context
field.
_arguments spec ...

zsh 4.0.4

Last change: October 26, 2001

32

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

This function can be used to complete words on the line by describing the options and arguments
which may be passed to the command for which completion is being performed. The description
is given as arguments to this function, with each spec describing one option or normal argument of
the command. The forms of spec understood are:
n:message:action
n::message:action
This describes the nth normal argument. The message will be printed above the matches
generated and the action says what can be completed in this position (see below). If there
are two colons before the message, this describes an optional argument. If the message
contains only white space, nothing will be printed above the matches unless the action
adds an explanation string itself.
:message:action
::message:action
Like the previous one, but describing the next argument. I.e. if you want to describe all
arguments a command can get, you can leave out the numbers in the description and just
use this form to describe them one after another in the order they have to appear on the
line.
:message:action
::message:action
:::message:action
This describes how arguments (usually nonoption arguments, those not beginning with
or +) are to be completed when no description with one of the first two forms was given.
This also means that any number of arguments can be completed.
With two colons before the message, the words special array and the CURRENT special
parameter are modified to refer only to the normal arguments when the action is executed
or evaluated. With three colons before the message they are modified to refer only to the
normal arguments covered by this description.
optspec[description ...]
This describes an option and (if description is given) the arguments that have to come
after the option. If no description is given, this means to offer only the option name as a
possible completion in the right places. (Note that the brackets, above, around description, indicate that zero or more descriptions may appear; but the brackets are not themselves part of this format. If brackets are used, they are part of the optspec; see below.)
In the descriptions below, the option names represented by optname are normally taken to
be multicharacter names, and a word from the line is considered to contain only one
option (or none). By giving the s option to _arguments before the first spec, each
optname is considered to be a single character and each word from the line may contain
more than one such option letter. However, words beginning with two hyphens (like
prefix) are still considered to contain only one option name. This allows the use of
the s option to describe singleletter options together with such long option names.
The s option may be combined with the option w to say that more option characters are
to be expected even after an option that takes an argument. For example, if a command
takes the options a and b, where a takes an argument in the next word, _arguments
would normally not complete the other option directly after a, but it would allow that
if given the w option.
Similarly, the option W may be given together with s to force completion of
singleletter options even after options that get an argument in the same word. For example, if a command takes the options a and b, where a needs an argument in the same
word, directly after the option character, _arguments would normally only execute the
action for that argument and not offer other singleletter options as possible completions.

zsh 4.0.4

Last change: October 26, 2001

33

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

If given the W option, it will offer other options as possible completions after executing
the action for the argument. Note that, depending on the action, this may mean that the
other options cant really be completed, but at least they will be listed. For more control,
use an utility function like _guard in the arguments action.
The forms of optspec are:
optspec

If the option may be given more than once, a star () must be added in front of
one of the following forms of optspec. Otherwise, if the option is already on the
line and to the left of the cursor, it is not offered as a possible completion again.

optname
+optname
In the simplest form the optspec is just the option name beginning with a minus
or a plus sign, such as foo. The first argument for the option (if any) must
follow as a separate word directly after the option.
If the command accepts the option with either a leading minus or a leading plus
sign, use either +optname or +optname to define both variants at once.
In all the following forms, the leading may be replaced or paired with + in
this way.
optname
The first argument of the option must come directly after the option name in the
same word, as in foo:....
optname+
The first argument may appear immediately after optname in the same word, or
may instead appear as a separate word after the option.
optname=
The argument may appear as the next word, or in same word as the option name
provided that it is separated from it by an equals sign.
optname=
The argument to the option must appear after an equals sign in the same word,
and may not be given in the next argument.
optspec[explanation]
An explanation string may be appended to any of the preceding forms of optspec
by enclosing it in brackets, as in q[query operation].
The verbose style is used to decide if these explanation strings should be
displayed with the option in a completion listing.
If no bracketed explanation string is given but the autodescription style is set
and only one argument is described for this optspec, the value of the style is
displayed, with any appearance of the sequence %d in it replaced by the message of the first description that follows the optspec; see below.
Note that the special meaning of a leading or trailing or + in optspec means that when the command to be completed accepts options like + or =, the second character has to be quoted with
a backslash, as in \+.
Each description following an optspec must take one of the following forms:
:message:action
::message:action
Describes a mandatory argument with one colon, or an optional argument with two
colons. As in other forms of spec, the message will be printed above the matches

zsh 4.0.4

Last change: October 26, 2001

34

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

generated (unless it contains only white space, see above) and the action says what can be
completed in this position.
:pattern:message:action
:pattern::message:action
:pattern:::message:action
This describes multiple arguments. Only the last description may be given in this form.
If the pattern is empty (i.e., ::), all following words on the line are to be completed as
described by the action; otherwise, all words up to a word matching the pattern are to be
completed using the action.
When the message is preceded by two colons, the words special array and the
CURRENT special parameter are modified during the execution or evaluation of the
action to refer only to the words after the option. When preceded by three colons, they
are modified to refer only to the words covered by this description.
Note that only one such :specification is useful and no other argument specification
may be given after it.
To include a colon in any optname, message, or action anywhere above, it has to be preceded by a
backslash, as \:.
Each of the six forms of spec (yes, there are six, keep track of the nestings) may be preceded by a list of
option names and argument numbers with which the option or argument described is mutually exclusive.
This list is given in parentheses, as in (two three 1)one:... or (foo):.... In the first example, the
options two and three and the first argument will not be offered as possible completions if the option
one is on the line before the cursor, and in the second example the option foo will not be offered if the
argument described by the specification is on the line.
The list may also contain a single star () as one of its elements to specify that the description for the rest
arguments (i.e. a specification of the form :...) should not be used, a colon (:) to specify that the descriptions for all normal (nonoption) arguments should not be used and a hyphen () to specify that the
descriptions for all options should not be used. This paragraph desperately needs rewriting.
To simplify writing writing functions that call _arguments more than once, the specs may also start with
the character ! (exclamation mark) to make the spec not be completed. However, if this is used with one
of the forms describing options, the option (and its arguments, if it takes any) will be understood and
skipped if they appear on the command line. Its just that the option itself will not be completed. This is
intended to be used with an array containing the options used in the first call to arguments. The second
call can then use \!${global_options} to ignore those options and complete only the ones understood in
the current context.
In every case above, the action determines how the possible completions should be generated. In places
where no sensible matches can be generated, the action should consist of only a space. This will make the
message be displayed but no possible completions listed. Note that even in this case the colon at the end of
the message is needed. The only case where it can be left is when neither a message, nor a action is given.
Except for the >string form below, the action will be executed by calling the _all_labels function to process all tag labels, so one doesnt need to call that explicitly unless another tag is to be used, for example in
a function called in the action.
When only one of a fixed set of strings can be completed, the action can consist of these strings as a list in
parentheses, as in:
:foo:(foo bar baz)
Such a list in doubled parentheses should contain strings consisting of the string to complete followed by
\: and a description, as in:

zsh 4.0.4

Last change: October 26, 2001

35

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

:foo:((a\:bar b\:baz))
The matches will be listed together with their descriptions if the description style for the values tag is set.
An action of the form >string is used by functions that implement a state machine. In this case, the
strings (with all leading and trailing spaces and tabs removed) of all actions that have to be used will be
stored in the global array state. The function returns with a nonzero return value if the cursor is not in a
position where options can be completed or if the current word could not be completed to an option. But if
the R option is given to _arguments, the function will instead return with a return value of 300 (to make
it distinguishable from other return values) after setting the global context, line and opt_args parameters as described below, and without resetting any changes made to the special parameters such as PREFIX
and words. This enables wrapper functions around _arguments to be able to find out if they have to make
sure that the special completion parameters are not reset when they return.
Note that this means that a function calling _arguments with at least one action containing such a
>string has to declare appropriate local parameters as in:
local context state line
typeset A opt_args
This will ensure that _arguments does not create unused global parameters.
A string in braces is evaluated to generate the matches and if the action does not begin with an opening
parentheses or brace, it is also split into separate words and executed. If the action starts with a space, this
list of words will be invoked unchanged, otherwise it will be invoked with some extra strings placed after
the first word which can be given as arguments to the compadd builtin command and which make sure that
the message given in the description will be shown above the matches. These arguments are taken from the
array parameter expl which will be set up before executing the action and hence may be used in it (normally in an expansion like $expl[@]).
If the action starts with = (an equals sign followed by a space), _arguments will insert the contents of the
argument field of the current context as the new first element in the words special array and increments the
value of the CURRENT special parameter. In other words, it inserts a dummy element in the words array
and makes CURRENT still point to the word in that array where the cursor is. This is only really useful
when used with one of the forms that make _arguments modify the words array to contain only some of
the words from the line, i.e. one of the argument description forms where the message is preceded by two or
three colons. For example, when the function called in the action for such an argument itself uses _arguments, the dummy element is needed to make that second call to _arguments use all words from the restricted range for argument parsing. Without the inserted dummy element, the first word in the range would
be taken (by the second _arguments) to be the command name and hence ignored.
During the evaluation or execution of the action the array line will be set to the command name and normal arguments from the command line, i.e. to the words from the command line excluding all options and
their arguments. These are stored in the associative array opt_args, using the option names as keys and
their arguments as the values. For options that have more than one argument these are given as one string,
separated by colons. All colons in the original arguments are preceded with backslashes.
The parameter context (set only in the calling function when using an action of the form >string, not
during the evaluation of other actions) is set to the automatically created context names. These are either
strings of the form optionoptn for the nth argument of the option opt, or strings of the form
argumentn for the nth argument (for rest arguments the n is the string rest). For example, when completing the argument of the o option, the name is optiono1 and for the second normal (nonoption)
argument it is argument2.
Also, during the evaluation of the action, the context name in the curcontext parameter is changed by
appending the same string that is stored in the context parameter.
It is also possible to specify multiple sets of options and arguments with the sets separated by single
hyphens. The specifications before the first hyphen are shared by all sets given after the first hyphen. The
first word in every other set gives the name of the set. This name may appear in exclusion lists in the

zsh 4.0.4

Last change: October 26, 2001

36

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

specifications, either alone or before one of the possible values described above (with a between the
name and the rest).
For example:
_arguments \
a \
set1 \
c \
set2 \
d \
:arg:(x2 y2)
This defines two sets. When the command line contains the option c, the d option and the argument
will not be considered possible completions. When it contains d or an argument, the option c will not
be completed any more, but if a is given, both sets will still be considered valid, because it appears
before the first hyphen, so both sets contain this option.
If the namestring is of the form (name) then all specifications in the set have an implicit exclusion list
containing the name of the set, i.e. all specifications are mutual exclusive with all other specifications in the
same set. This is useful for defining multiple sets of options which are mutually exclusive and in which the
options are aliases for each other. E.g.:
_arguments \
a b \
(compress) \
{c, compress}[compress] \
(uncompress) \
{d, decompress}[decompress]
Note that using multiple sets will be slower than using only one set because the completion code has to
parse the command line once for every set. So more than one set should only be used if the command syntax is too complicated. Note also that an option specification with restarguments (as in foo::...) often
allows the use of multiple sets to be avoided.
To simplify the specifications for commands with standard option parsing, the options S and A may be
given. With S, no option will be completed after a on the line and this argument will otherwise be
ignored. With A, no options will be completed after the first nonoption argument on the line. The A has
to be followed by a pattern matching all strings which are not to be taken as arguments. For example, to
make _arguments stop completing options after the first normal argument, but ignoring all strings starting
with a hyphen even if they are not described by one of the optspecs, one would use: A " " .
Another option supported is O name. The name will be taken as the name of an array and its elements
will be given to functions called to generate matches when executing the actions. For example, this allows
one to give options for the compadd builtin that should be used for all actions.
Also, the M option followed by a string may be given before the first description. The string will be used
as the match specification when completing option names and values instead of the default r:[_]=
r:=.
Finally, the option C can be given to make _arguments modify the curcontext parameter when an action
of the form >state is used. This parameter is used to keep track of the current context and in this case it
(and not the parameter context as explained above) has to be made local to make sure that calling functions
dont use the modified value. Also, the local version of curcontext has to be initialised with the old value
as in:
local curcontext=" $curcontext"
The function can also be made to automatically complete long options for commands that support the
help option as, for example, most of the GNU commands do. For this, the string must be given as
one argument and if it is, the command from the line is invoked with the help option and its output is

zsh 4.0.4

Last change: October 26, 2001

37

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

parsed to find possible option names. Note that this means that you should be careful to make sure that this
feature is not used for a command that does not support this option.
For such automatically found options that get an argument after an =, the function also tries to automatically find out what should be completed as the argument. The possible completions for optionarguments
can be described with the arguments after the (which are not used as described above). Each argument
contains one description of the form pattern:message:action. The message and the action have the same
format as for the normal option descriptions described above. The action will be executed to complete arguments of options whose description in the output of the command from the line with the help option
matches the pattern. For example:
_arguments \:toggle:(yes no) \
=FILE:file:_files \
=DIR:directory:_files /
Here, yes and no will be completed as the argument of options whose description ends in a star, file
names for options that contain the substring =FILE in the description, and paths for options whose
description contains =DIR. In fact, the last two patterns are not needed since this function always completes files for option descriptions containing =FILE and paths for option descriptions that contain
=DIR or =PATH. These builtin patterns can be overridden by patterns given as arguments, however.
Note also that _arguments tries to find out automatically if the argument for an option is optional. If it fails
to automatically detect this, the colon before the message can be doubled to tell it about this as described
for the normal option descriptions above.
If the pattern ends in (), this will removed from the pattern and the action will be used only directly after
the =, not in the next word. I.e., this is like a normal specification as described above using =.
The option i patterns (which must be given after the ) can be used to give patterns for options which
should not be completed. The patterns can be given as the name of an array parameter or as a literal list in
parentheses. E.g. i " ( (endis)ableFEATURE)" will make the options enableFEATURE and
disableFEATURE be ignored. The option s pairs (again, after the ) can be used to describe
option aliases. Each pair consists of a pattern and a replacement. E.g. some configurescripts describe
options only as enablefoo, but also accept disablefoo. To allow completion of the second form,
one would use s " (# enable disable)" .
Example:
_arguments l+:left border: \
format:paper size:(letter A4) \
copy:output file:_files::resolution:(300 600) \
:postscript file:_files g \.\(ps\eps\) \
:page number:
This describes three options: l, format, and copy. The first one gets one argument described as
left border for which no completion will be offered because of the empty action. The argument may come
directly after the l or it may be given as the next word on the line. The format option gets one argument (in the next word) described as paper size for which only the strings letter and A4 will be completed. The copy option differs from the first two in that it may appear more than once on the command
line and in that it accepts two arguments. The first one is mandatory and will be completed as a filename.
The second one is optional (because of the second colon before the description resolution) and will be
completed from the strings 300 and 600.
The last two descriptions say what should be completed as arguments. The first one describes the first argument as a postscript file and makes files ending in ps or eps be completed. The last description says
that all other arguments are page numbers but does not give possible completions.
_cache_invalid cache_identifier
This function returns 0 if the completions cache corresponding to the given cache identifier needs rebuilding. It determines this by looking up the cachepolicy style for the current context, and if it exists, runs the

zsh 4.0.4

Last change: October 26, 2001

38

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

function of the same name, supplying the full path to the relevant cache file as the only argument.
Example:
_example_caching_policy () {
# rebuild if cache is more than a week old
oldp=( " $1" (Nmw+1) )
(( $#oldp ))
}
_call_function return name [ args ... ]
If a function name exists, it is called with the arguments args. Unless it is the empty string or a single
hyphen, return is taken as the name of a parameter and the return status from the called function is stored in
it. The return value of _call_function itself is zero if the function name exists and was called and nonzero
otherwise.
_call_program tag string ...
This function is used in places where a command is called, making it possible for the user to override the
default command call. It looks up the command style with the supplied tag. If the style is set, its value is
used as the command to execute.
In any case, the strings from the call to _call_program or from the style are concatenated with spaces
between them and the resulting string is evaluated. The return value is the return value of the command
called.
_combination [ s pattern ] tag style specs ... field opts ...
This function is used to complete combinations of values such as pairs of hostnames and usernames. The
possible values will be taken from the style whose name is given as the second argument. The first argument is the tag to use to do the lookup.
The style name should consist of multiple parts separated by hyphens which are then used as field names.
Known values for such fields can be given after the second argument in arguments of the form
field=pattern. The first argument without an equals sign is taken as the name of the field for which completions should be generated.
The matches generated will be taken from the value of the style. These values should contain the possible
values for the combinations where the values for the different fields are separated by colons or characters
matching the pattern given after the s option to _combination; normally this is used to define character
classes like the s " [:@]" used for the usershosts style.
Only the values for the requested fields for which the patterns given in the field=pattern match the respective fields in the strings from the style value are generated as possible matches.
If no style with the given name is defined for the given tag but a function named with the name of the
requested field preceded by an underscore is defined, that function will be called to generate the matches.
This is also done if none of the strings in the value of the style match all the patterns given as arguments.
If the same name is used for more than one field, in both the field=pattern and the argument that gives the
field name to complete for, the number of the field (starting with one) may be given after the fieldname,
separated from it by a colon.
All arguments after the requested field name are passed to compadd when generating matches from the
style value, or to the functions for the fields if they are called.
_contexts names ...
This function looks up the definitions for the context and command names given as arguments and calls the
handler functions for them if there is a definition (given with the compdef function). For example, the
function completing inside subscripts might use _contexts math to include the completions generated
for mathematical environments.
_describe [ o ] descr name1 [ name2 ] opts ... ...
This function is useful for preparing a list of command options or arguments, together with their

zsh 4.0.4

Last change: October 26, 2001

39

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

descriptions descr, as matches. Multiple groups separated by can be supplied, potentially with different
completion options opts.
The descr is taken as a string to display above the matches if the format style for the descriptions tag is
set. After this come one or two names of arrays followed by options to pass to compadd. The first array
contains the possible completions with their descriptions in the form completion:description. If a second
array is given, it should have the same number of elements as the first one and the corresponding elements
are added as possible completions instead of the completion strings from the first array. The completion list
will retain the descriptions from the first array. Finally, a set of completion options can appear.
If the option o appears before the first argument, the matches added will be treated as option names (typically following a , or + on the command line). This makes _describe use the prefixhidden,
prefixneeded and verbose styles to find out if the strings should be added at all and if the descriptions
should be shown. Without the o option, only the verbose style is used.
_describe uses the _all_labels function to generate the matches, so it does not need to appear inside a loop
over tag labels.
_description [ 12VJ ] tag name descr [ specs ... ]
This function is called before completions are added (typically by a call to compadd); it tests various styles
and arranges for any necessary options to be passed on to compadd. The styles are tested in the current
context using the given tag; options are put into the array called name for passing on to compadd; the
description for the current set of matches is passed in descr. The styles tested are: format (which is first
tested for the given tag and then for the descriptions tag if that isnt defined), hidden, matcher,
ignoredpatterns and groupname (the last are tested only for the tag given as the first argument). This
function also calls the _setup function which tests some more styles.
The string returned by the format style (if any) will be modified so that the sequence %d is replaced by
the descr given as the third argument without any leading or trailing white space. If, after removing the
white space, the descr is the empty string, the format style will not be used and the options put into the
name array will not contain an explanation string to be displayed above the matches. If _description is
called with more than three arguments, the additional specs should be of the form char:str and every
appearance of %char in the format string will be replaced by string.
The options placed in the array will also make sure that the matches are placed in a separate group, depending on the value of the groupname style. Normally a sorted group will be used for this (with the J
option), but if an option starting with V, J, 1, or 2 is given, that option will be included in the
array, so that it is possible to make the group unsorted by giving the option V, 1V, or 2V.
In most cases, the function will be used like this:
local expl
_description files expl file
compadd " $expl[@]" " $files[@]"
Note the use of the parameter expl, the hyphen, and the list of matches. Almost all calls to compadd
within the completion system use a similar format; this ensures that userspecified styles are correctly
passed down to the builtins which implement the internals of completion.
_files
The function _files uses the filepatterns style and calls _path_files with all the arguments it was passed
except for g and /. These two options are used depending on the setting of the filepatterns style.
See _path_files below for a description of the full set of options accepted by _files.
_gnu_generic
This function is a simple wrapper around the _arguments function described above. It can be used to
automatically complete long options for commands that understand the help option. It is not intended
to be used from completion functions but as a toplevel completion function in its own right. For example,
to enable option completion for the commands foo and bar, one would call:

zsh 4.0.4

Last change: October 26, 2001

40

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

compdef _gnu_generic foo bar


in one of the initialization files after the call to compinit.
The default installation uses this function only to generate completions for some GNUcommands because
to complete the options, the command has to be called and hence it shouldnt be used if one cant be sure
that the command understands the help option.
_guard [ options ] pattern [ descr ]
This function is intended to be used in an action of functions like _arguments. It returns immediately with
a nonzero return value if the string to be completed does not match the pattern. If the pattern matches, the
descr is displayed and the function returns zero if the word to complete is not empty and nonzero otherwise.
The pattern may be preceded by those options understood by compadd that are passed down from
_description, namely M, J, V, 1, 2, n, F and X. All of these options, except X, will be ignored.
If the X option appears, the description following it will be used as the string to display if the pattern
matches, unless the option descr is given to _guard itself, which will then take precedence.
As an example, consider a command taking the options n and none, where n has to be followed by a
numeric value in the same word. By using either of:
_argument n:numeric value:_guard " [09]#" none
or
_argument n: :_guard " [09]#" " numeric value" none
_arguments can be made to both display the message numeric value and complete options after
n<TAB>. If the n is already followed by one or more digits (matching the pattern given to _guard),
only the message will be displayed and if the n is followed by another character, only options are completed.
_message [ r ] descr
The descr is used like the third argument to the _description function. However, the resulting string will
always be shown whether or not matches were generated. This is useful to display help texts in places
where no completions can be generated automatically.
This function also uses the format style for the messages tag in preference to the format style for the
descriptions tag. The latter is used only if the former is unset.
If the r option is given, no style is used and the descr is used literally as the string to display. This is only
used in cases where that string is taken from some preprocessed argument list containing an expanded
description.
_multi_parts sep array
This function receives two arguments: a separator character and an array. As usual, the array may be either
the name of an array parameter or a literal array in the form (foo bar) (i.e. a list of words separated by
white space in parentheses). With these arguments, this function will complete to strings from the array
where the parts separated by the separator character are completed independently. For example, the _tar
function from the distribution caches the pathnames from the tar file in an array, and then calls this function
to complete these names in the way normal filenames are completed by the _path_files function, by using
_multi_parts / patharray.
If the i option is present, then any time there is a unique match it will immediately be inserted even if that
requires additional separators to be inserted as well. When completing from a fixed set of possible completions which are really words, this is often the expected behaviour; however, if _multi_parts should behave
like completing pathnames, the i option should not be used.
Like other utility functions, this function accepts the V, J, 1, 2, n, f, X, M, P,
S, r, R, and q options and passes them to the compadd builtin.
_next_label [ 12VJ ] tag name descr [ options ... ]

zsh 4.0.4

Last change: October 26, 2001

41

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

This function should be called repeatedly to generate the tag labels. On each call it will check if another tag
label is to be used and, if there is at least one, zero is returned. If no more tag labels are to be used, a
nonzero status is returned.
The 12JV options and the first three arguments are given to the _description function using the tag label
instead of the first argument as appropriate. The options given after the descr should be other options to be
used for compadd or whatever function is to be called to add the matches. _next_label will store these
options in the parameter whose name is given as the second argument. This is done in such a way that the
description given by the user to the tagorder style is preferred over the one given to _next_label.
Note that this function must not be called without a previous call to _tags or _requested because it uses the
tag label for the current tag found by these functions.
A normal use of this function for the tag labels of the tag foo looks like this:
local expl ret=1
...
if _requested foo; then
...
while _next_label foo expl ...; do
compadd " $expl[@]" ... && ret=0
done
...
fi
return ret
_normal
This function is used for normal command completion. It has two tasks: completing the first word on the
command line as the name of a command, and completing the arguments to this command. In the second
case, the name of the command is looked up to see if special completions exists, including completions
defined for patterns which match the name. If none is found, completion is performed for the context
default.
The function can also be called by other completion functions which need to treat a range of words as a
command line. For example, the function to complete after the precommand specifiers such as nohup
removes the first word from the words array, decrements the CURRENT parameter, then calls _normal
again, with the effect that nohup cmd ... is treated the same way was cmd ....
If the command name matches a pattern, the parameter _compskip is checked after the call to the
corresponding completion function. This has the same effect here as in the first context: if it is set, no
more completion functions are called even if there are no matches so far.
_options
This can be used to complete option names. It uses a matching specification that ignores a leading no,
ignores underscores and allows the user to type uppercase letters which will match their lowercase counterparts. All arguments passed to this function are propagated unchanged to the compadd builtin.
_options_set and _options_unset
These functions complete only set or unset options, with the same matching specification used in the
_options function.
Note that you need to uncomment a few lines in the _main_complete function for these functions to work
properly. The lines in question are used to store the option settings in effect before the completion widget
locally sets the options it needs. Hence these options are not generally used by the completion system.
_parameters
This should be used to complete parameter names. _parameters can take a g pattern option which
specifies that only parameters whose type matches the pattern should be completed. Strings of the same
form as those returned by the t parameter expansion flag are used here when matching the type. All other

zsh 4.0.4

Last change: October 26, 2001

42

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

arguments are passed unchanged to the compadd builtin.


_path_files
The function _path_files is used throughout the completion system to complete filenames. It allows completion of partial paths. For example, the string /u/i/s/sig may be completed to
/usr/include/sys/signal.h.
The options accepted by both _path_files and _files are:
f

Complete all filenames. This is the default.

Specifies that only directories should be completed.

g pattern
Specifies that only files matching the pattern should be completed.
W paths
Specifies path prefixes that are to be prepended to the string from the line to generate the filenames
but that should not be inserted in the line or shown in a completion listing. Here, paths may be the
name of an array parameter, a literal list of paths enclosed in parentheses or an absolute pathname.
F

This option from the compadd builtin gives direct control over which filenames should be
ignored. If the option is not present, the ignoredpatterns style is used.

These functions also accept the J, V, 1, 2, n, X, M, P, S, q, r, and R


options from the compadd builtin.
Finally, the _path_files function uses the styles expand, ambiguous, specialdirs, listsuffixes and
filesort.
_regex_arguments name specs ...
This function is a compiler to generate a completion function. The first argument specifies the name of the
generated function while the remaining arguments specify a completion as a set of regular expressions with
actions. The generated function has the structure of a finitestate machine whose states correspond to the
state (i.e. the context) of the completion. This state machine uses a command line, which comes from the
concatenation of the words array up to the current cursor position using null characters as separators with
no extra quotation. This is analysed and at the end the appropriate action is executed.
Specification arguments take one of following forms, in which metacharacters such as (, ), # and
should be quoted.
/pattern/ [%lookahead%] [guard] [:tag:descr:action]
This is a primitive element, corresponding to one state of the compiled state machine. The state is
entered if (#b)((#B)pattern)(#B)lookahead matches the command line string. If it matches,
guard is evaluated and its return status is examined; if this is successful, the state is entered, otherwise the test fails and other candidates are tried. The pattern string [] is guaranteed never to
match.
If the test succeeds and the state is entered, the left part of the command line string matched as pattern is removed and the next state is tried, proceeding from inside to outside and from left to right.
If no test succeeds and the remaining command line string contains no null character, the completion target is restricted to the remainder of the command line string and actions for the target are
executed. In this case, nothing is actually removed from the command line string so that any previous or neighbouring state may also have actionss. actionss evaluation are ordered by the
tagorder style and specified tag by _alternative. So, the various formats supported by _alternative can be used in action. descr is used for setting up the array parameter expl.
/pattern/+ [%lookahead%] [guard] [:tag:descr:action]
This is similar to /pattern/ ... but the left part of the command line string is also considered as
part of the completion target.
/pattern/ [%lookahead%] [guard] [:tag:descr:action]

zsh 4.0.4

Last change: October 26, 2001

43

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

This is similar to /pattern/ ... but the actions of the current and previous states are ignored even if
the following states pattern matches the empty string.
( spec ) This groups specs.
spec #

This allows any number of repetitions of spec.

spec spec
This represents the concatenation of two specs.
spec spec
Either of the two specs can be matched.
_requested [ 12VJ ] tag [ name descr [ command args ... ] ]
This function is called to decide whether a tag already registered by a call to _tags (see below) is requested
and hence completion should be performed for it; it returns status zero if the tag is requested and nonzero
otherwise. This will usually be done in a loop such as the following:
_tags foo bar baz
while _tags; do
if _requested foo; then
... # perform completion for foo
fi
... # test the tags bar and baz in the same way
... # exit loop if matches were generated
done
Note that the test for whether matches were generated is not performed until the end of the _tags loop. This
is so that the user can specify a set of tags to be tested at the same time in the tagorder parameter.
If the name and the descr are given, _requested calls the _description function with these arguments,
including the options.
If the command is given, the _all_labels function will be called immediately with the same arguments.
This is often useful to do both the testing of the tag, getting the description for the matches and adding the
matches at once. For example:
local expl ret=1
_tags foo bar baz
while _tags; do
_requested foo expl description \
compadd foobar foobaz && ret=0
...
(( ret )) break
done
Note that this means that the command has to accept the options that have to be passed down to compadd.
_retrieve_cache cache_identifier
This function retrieves completion information from the file given by cache_identifier, stored in a directory
specified by the cachepath style (defaults to /.zsh/cache). The return value is zero if retrieval was successful. It will only attempt retrieval if the usecache style is set, so you can call this function without
worrying about whether the user wanted to use the caching layer.
See _store_cache below for more details.
_sep_parts
This function is passed alternating arrays and separators as arguments. The arrays specify completions for
parts of strings to be separated by the separators. The arrays may be the names of array parameters or a
quoted list of words in parentheses. For example, with the array hosts=(ftp news) the call _sep_parts
(foo bar) @ hosts will complete the string f to foo and the string b@n to bar@news.

zsh 4.0.4

Last change: October 26, 2001

44

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPSYS ( 1 )

This function passes the V, J, 1, 2, n, X, M, P, S, r, R, and q options


and their arguments to the compadd builtin used to add the matches.
_setup tag [ group ]
This function expects a tag as its argument and sets up the special parameters used by the completion system appropriately for the tag, using styles such as listcolors and lastprompt.
The optional group gives the name of the group in which the matches will be placed. If it is not given, the
tag is used as the group name.
Note that this function is called automatically from _description so that one normally doesnt have to call
it explicitly.
_store_cache cache_identifier vars ...
This function, when combined with _retrieve_cache and _cache_invalid, makes it easy to implement a
caching layer for your completion functions. If a completion function needs to perform a costly operation
in order to generate data which is used to calculate completions, you can store that data in variables, and
use this function to dump the values of those variables to a file. Then, if they are needed in subsequent
shell invocations, they can be retrieved quickly from that file via _retrieve_cache, avoiding the need for
repeating the costly operation.
The cache_identifier specifies the file which the data should be dumped to, and is stored in a directory
specified by the cachepath style (defaults to /.zsh/cache). The remaining vars arguments are the variables to dump to the file.
The return value is zero if storage was successful. The function will only attempt storage if the usecache
style is set, so you can call this function without worrying about whether the user wanted to use the caching
layer.
If your completion function avoids calling _retrieve_cache when it already has the completion data in the
environment, it should probably at least call _cache_invalid to check whether this data and the data cached
on disk is still valid.
See the _perl_modules completion function for a simple example of usage of this caching layer.
_tags [ C name [ tags ... ] ]
If called with arguments, these are taken as the names of the tags for the types of matches the calling completion function can generate in the current context. These tags are stored internally and sorted by using the
tagorder style. Following calls to this function without arguments from the same function will then select
the first, second, etc. set of tags requested by the user. To test if a certain tag should be tried, the
_requested function has to be called (see above).
The return value is zero if at least one of the tags is requested and nonzero otherwise.
This function also accepts the C option followed by a name. This name is temporarily (i.e. not visible outside _tags) stored in the argument field of the context name in the curcontext parameter. This allows _tags
to be made to use a more specific context name without having to change and reset the curcontext parameter (which would otherwise have the same effect).
_values specs ...
This is used to complete values (strings) and their arguments or lists of such values. It can be used in two
ways.
If the first argument is the option O name, this will be used in the same way as by the _arguments function, in other words the elements of the name array will be given to calls to compadd and when executing
an action.
Otherwise, if the first argument (or the first argument after the O name option if that is used) is the
option s, the next argument is used as the character that separates multiple values. Thus the values completed appear in the same word on the command line, unlike completion using _arguments.

zsh 4.0.4

Last change: October 26, 2001

45

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

The first argument (after the options and separator character if they are given) is used as a string to print as
a description before listing the values.
All other arguments describe the possible values and their arguments in the same format used for the
description of options by the _arguments function (see above). The only differences are that no minus or
plus sign is required at the beginning, that values can have only one argument and that those forms of
actions beginning with an equal sign are not supported.
The character separating a value from its argument can be set using the option S (like s, followed by the
character to use as the separator in the next argument). If this option is not used, the equal sign will be used
as the separator.
Example:
_values s , description \
foo[bar] \
(two)one[number]:first count: \
two[another number]::second count:(1 2 3)
This describes three possible values: foo, one, and two. The first is described as bar, takes no argument and may appear more than once. The second is described as number, may appear more than once,
and takes one mandatory argument described as first count for which no action is specified so that it will
not be completed automatically. The (two) at the beginning says that if the value one is on the line, the
value two will not be considered to be a possible completion anymore. Finally, the last value (two) is
described as another number and takes an optional argument described as second count which will be
completed from the strings 1, 2, and 3. The _values function will complete lists of these values
separated by commas.
Like _arguments this function temporarily adds another context name component to the current context
name while executing the action. Here this name is just the name of the value for which the argument is
completed.
To decide if the descriptions for the values (not those for the arguments) should be printed, the style verbose is used.
One last difference from _arguments is that this function uses the associative array val_args to report
values and their arguments, although otherwise this is the same as the opt_args association used by _arguments. This also means that the function calling _values should declare the state, line, context and
val_args parameters as in:
local context state line
typeset A val_args
when using an action of the form >string. With this function the context parameter will be set to the
name of the value whose argument is to be completed.
Note also that _values normally adds the character used as the separator between values as a
autoremovable suffix so that users dont have to type it themselves. But when using a >string action
_values cant do that because the matches for the argument will be generated by the calling function. To
get the usual behaviour, the implementor of the calling function has to add the suffix directly by passing the
options qS x (where x is the separator character specified with the s option of _values) to the function
generating the matches or to the compadd builtin.
Like _arguments, _values supports the C option in which case you have to make the parameter curcontext local instead of context (as described above).
_wanted [ C name ] [ 12VJ ] tag name descr command args ...
In many contexts, completion will generate one particular set of matches (usually corresponding to a single
tag); however, it is still necessary to decide whether the user requires matches of this type. This function is
useful in such a case.

zsh 4.0.4

Last change: October 26, 2001

46

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPSYS ( 1 )

Like _requested, it should be passed arguments as for _description. It calls _tags with the given tag and
if that returns zero (so that the tag is requested by the user) it calls _description. Hence to offer only one
tag and immediately use the description generated:
_wanted tag expl description \
compadd matches...
Unlike _requested, however, _wanted cannot be called without the command. This is because _wanted
also implements the loop over the tags, not just the one for the labels; conversely, it should not be called in
the middle of a _tags loop.
Note that, as for _requested, the command has to accept the options that have to be passed down to compadd.
Like _tags this function supports the C option to give a different name for the argument context field.
COMPLETION DIRECTORIES

In the source distribution, the files are contained in various subdirectories of the Completion directory.
They may have been installed in the same structure, or into one single function directory. The following is
a description of the files found in the original directory structure. If you wish to alter an installed file, you
will need to copy it to some directory which appears earlier in your fpath than the standard directory where
it appears.
Base

The core functions and special completion widgets automatically bound to keys. You will certainly need most of these, though will probably not need to alter them. Many of these are documented above.

Zsh

Functions for completing arguments of shell builtin commands and utility functions for this.
Some of these are also used by functions from the Unix directory.

Unix

Functions for completing arguments of external commands and suites of commands. They may
need modifying for your system, although in many cases some attempt is made to decide which
version of a command is present. For example, completion for the mount command tries to determine the system it is running on, while completion for many other utilities try to decide whether
the GNU version of the command is in use, and hence whether the help option is supported..

X, AIX, BSD, ...


Completion and utility function for commands available only on some systems.

zsh 4.0.4

Last change: October 26, 2001

47

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPCTL ( 1 )

NAME

zshcompctl zsh programmable completion


SYNOPSIS

This version of zsh has two ways of performing completion of words on the command line. New users of
the shell may prefer to use the newer and more powerful system based on shell functions; this is described
in zshcompsys(1), and the basic shell mechanisms which support it are described in zshcompwid(1). This
manual entry describes the older compctl command.
DESCRIPTION

compctl [ CDT ] options [ command ... ]


compctl [ CDT ] options [ x pattern options ... ] [ + options [ x ... ] ... [+] ] [ command ... ]
compctl M matchspecs ...
compctl L [ CDTM ] [ command ... ]
compctl + command ...
Control the editors completion behavior according to the supplied set of options. Various editing commands, notably expandorcompleteword, usually bound to tab, will attempt to complete a word typed
by the user, while others, notably deletecharorlist, usually bound to D in EMACS editing mode, list
the possibilities; compctl controls what those possibilities are. They may for example be filenames (the
most common case, and hence the default), shell variables, or words from a userspecified list.
COMMAND FLAGS

Completion of the arguments of a command may be different for each command or may use the default.
The behavior when completing the command word itself may also be separately specified. These
correspond to the following flags and arguments, all of which (except for L) may be combined with any
combination of the options described subsequently in the section Option Flags:
command ...
controls completion for the named commands, which must be listed last on the command line. If
completion is attempted for a command with a pathname containing slashes and no completion
definition is found, the search is retried with the last pathname component. If the command starts
with a =, completion is tried with the pathname of the command.
Any of the command strings may be patterns of the form normally used for filename generation.
These should be be quoted to protect them from immediate expansion; for example the command
string foo arranges for completion of the words of any command beginning with foo. When
completion is attempted, all pattern completions are tried in the reverse order of their definition
until one matches. By default, completion then proceeds as normal, i.e. the shell will try to generate more matches for the specific command on the command line; this can be overridden by
including tn in the flags for the pattern completion.
Note that aliases are expanded before the command name is determined unless the
COMPLETE_ALIASES option is set. Commands may not be combined with the C, D or T
flags.

zsh 4.0.4

controls completion when the command word itself is being completed. If no compctl C command has been issued, the names of any executable command (whether in the path or specific to
the shell, such as aliases or functions) are completed.

controls default completion behavior for the arguments of commands not assigned any special
behavior. If no compctl D command has been issued, filenames are completed.

supplies completion flags to be used before any other processing is done, even before processing
for compctls defined for specific commands. This is especially useful when combined with
extended completion (the x flag, see the section Extended Completion below). Using this flag
you can define default behavior which will apply to all commands without exception, or you can
alter the standard behavior for all commands. For example, if your access to the user database is
too slow and/or it contains too many users (so that completion after is too slow to be usable),

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPCTL ( 1 )

you can use


compctl T x s[] C[0,[/]#] k friends S/ tn
to complete the strings in the array friends after a . The C[...] argument is necessary so that this
form of completion is not tried after the directory name is finished.
L

lists the existing completion behavior in a manner suitable for putting into a startup script; the
existing behavior is not changed. Any combination of the above forms, or the M flag (which
must follow the L flag), may be specified, otherwise all defined completions are listed. Any other
flags supplied are ignored.

no argument
If no argument is given, compctl lists all defined completions in an abbreviated form; with a list
of options, all completions with those flags set (not counting extended completion) are listed.
If the + flag is alone and followed immediately by the command list, the completion behavior for all the
commands in the list is reset to the default. In other words, completion will subsequently use the options
specified by the D flag.
The form with M as the first and only option defines global matching specifications (see zshcompwid).
The match specifications given will be used for every completion attempt (only when using compctl, not
with the new completion system) and are tried in the order in which they are defined until one generates at
least one match. E.g.:
compctl M m:{azAZ}={AZaz}
This will first try completion without any global match specifications (the empty string) and, if that generates no matches, will try case insensitive completion.
OPTION FLAGS

[ fcFBdeaRGovNAIOPZEnbjrzu/12 ]
[ k array ] [ g globstring ] [ s subststring ]
[ K function ]
[ Q ] [ P prefix ] [ S suffix ]
[ W fileprefix ] [ H num pattern ]
[ q ] [ X explanation ] [ Y explanation ]
[ y funcorvar ] [ l cmd ] [ h cmd ] [ U ]
[ t continue ] [ J name ] [ V name ]
[ M matchspec ]
The remaining options specify the type of command arguments to look for during completion. Any combination of these flags may be specified; the result is a sorted list of all the possibilities. The options are as
follows.
Simple Flags

These produce completion lists made up by the shell itself:

zsh 4.0.4

Filenames and filesystem paths.

Just filesystem paths.

Command names, including aliases, shell functions, builtins and reserved words.

Function names.

Names of builtin commands.

Names of external commands.

Reserved words.

Alias names.

Names of regular (nonglobal) aliases.

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPCTL ( 1 )

Names of global aliases.

This can be combined with F, B, w, a, R and G to get names of disabled functions, builtins, reserved words or aliases.

This option (to show enabled commands) is in effect by default, but may be combined with d;
de in combination with F, B, w, a, R and G will complete names of functions, builtins,
reserved words or aliases whether or not they are disabled.

Names of shell options (see zshoptions(1)).

Names of any variable defined in the shell.

Names of scalar (nonarray) parameters.

Array names.

Names of integer variables.

Names of readonly variables.

Names of parameters used by the shell (including special parameters).

Names of shell special parameters.

Names of environment variables.

Named directories.

Key binding names.

Job names: the first word of the job leaders command line. This is useful with the kill builtin.

Names of running jobs.

Names of suspended jobs.

User names.

Flags with Arguments

These have user supplied arguments to determine how the list of completions is to be made up:
k array
Names taken from the elements of $array (note that the $ does not appear on the command line).
Alternatively, the argument array itself may be a set of space or commaseparated values in
parentheses, in which any delimiter may be escaped with a backslash; in this case the argument
should be quoted. For example,
compctl k " (cputime filesize datasize stacksize
coredumpsize resident descriptors)" limit
g globstring
The globstring is expanded using filename globbing; it should be quoted to protect it from
immediate expansion. The resulting filenames are taken as the possible completions. Use (/)
instead of / for directories. The fignore special parameter is not applied to the resulting files.
More than one pattern may be given separated by blanks. (Note that brace expansion is not part of
globbing. Use the syntax (eitheror) to match alternatives.)
s subststring
The subststring is split into words and these words are than expanded using all shell expansion
mechanisms (see zshexpn(1)). The resulting words are taken as possible completions. The fignore
special parameter is not applied to the resulting files. Note that g is faster for filenames.
K function
Call the given function to get the completions. Unless the name starts with an underscore, the
function is passed two arguments: the prefix and the suffix of the word on which completion is to
be attempted, in other words those characters before the cursor position, and those from the cursor

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPCTL ( 1 )

position onwards. The whole command line can be accessed with the c and l flags of the read
builtin. The function should set the variable reply to an array containing the completions (one
completion per element); note that reply should not be made local to the function. From such a
function the command line can be accessed with the c and l flags to the read builtin. For example,
function whoson { reply=(users); }
compctl K whoson talk
completes only loggedon users after talk. Note that whoson must return an array, so
reply=users would be incorrect.
H num pattern
The possible completions are taken from the last num history lines. Only words matching pattern
are taken. If num is zero or negative the whole history is searched and if pattern is the empty
string all words are taken (as with ). A typical use is
compctl D f + H 0
which forces completion to look back in the history list for a word if no filename matches.
Control Flags

These do not directly specify types of name to be completed, but manipulate the options that do:
Q

This instructs the shell not to quote any metacharacters in the possible completions. Normally the
results of a completion are inserted into the command line with any metacharacters quoted so that
they are interpreted as normal characters. This is appropriate for filenames and ordinary strings.
However, for special effects, such as inserting a backquoted expression from a completion array
(k) so that the expression will not be evaluated until the complete line is executed, this option
must be used.

P prefix
The prefix is inserted just before the completed string; any initial part already typed will be completed and the whole prefix ignored for completion purposes. For example,
compctl j P " %" kill
inserts a % after the kill command and then completes job names.
S suffix
When a completion is found the suffix is inserted after the completed string. In the case of menu
completion the suffix is inserted immediately, but it is still possible to cycle through the list of
completions by repeatedly hitting the same key.
W fileprefix
With directory fileprefix: for command, file, directory and globbing completion (options c, f,
/, g), the file prefix is implicitly added in front of the completion. For example,
compctl / W /Mail maildirs
completes any subdirectories to any depth beneath the directory /Mail, although that prefix does
not appear on the command line. The fileprefix may also be of the form accepted by the k flag,
i.e. the name of an array or a literal list in parenthesis. In this case all the directories in the list will
be searched for possible completions.
q

If used with a suffix as specified by the S option, this causes the suffix to be removed if the next
character typed is a blank or does not insert anything or if the suffix consists of only one character
and the next character typed is the same character; this the same rule used for the
AUTO_REMOVE_SLASH option. The option is most useful for list separators (comma, colon,
etc.).

l cmd This option restricts the range of command line words that are considered to be arguments. If
combined with one of the extended completion patterns p[...], r[...], or R[...] (see the section

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPCTL ( 1 )

Extended Completion below) the range is restricted to the range of arguments specified in the
brackets. Completion is then performed as if these had been given as arguments to the cmd supplied with the option. If the cmd string is empty the first word in the range is instead taken as the
command name, and command name completion performed on the first word in the range. For
example,
compctl x r[exec,;] l find
completes arguments between exec and the following ; (or the end of the command line if
there is no such string) as if they were a separate command line.
h cmd Normally zsh completes quoted strings as a whole. With this option, completion can be done
separately on different parts of such strings. It works like the l option but makes the completion
code work on the parts of the current word that are separated by spaces. These parts are completed
as if they were arguments to the given cmd. If cmd is the empty string, the first part is completed
as a command name, as with l.
U

Use the whole list of possible completions, whether or not they actually match the word on the
command line. The word typed so far will be deleted. This is most useful with a function (given
by the K option) which can examine the word components passed to it (or via the read builtins
c and l flags) and use its own criteria to decide what matches. If there is no completion, the original word is retained. Since the produced possible completions seldom have interesting common
prefixes and suffixes, menu completion is started immediately if AUTO_MENU is set and this
flag is used.

y funcorvar
The list provided by funcorvar is displayed instead of the list of completions whenever a listing
is required; the actual completions to be inserted are not affected. It can be provided in two ways.
Firstly, if funcorvar begins with a $ it defines a variable, or if it begins with a left parenthesis a
literal array, which contains the list. A variable may have been set by a call to a function using the
K option. Otherwise it contains the name of a function which will be executed to create the list.
The function will be passed as an argument list all matching completions, including prefixes and
suffixes expanded in full, and should set the array reply to the result. In both cases, the display list
will only be retrieved after a complete list of matches has been created.
Note that the returned list does not have to correspond, even in length, to the original set of
matches, and may be passed as a scalar instead of an array. No special formatting of characters is
performed on the output in this case; in particular, newlines are printed literally and if they appear
output in columns is suppressed.
X explanation
Print explanation when trying completion on the current set of options. A %n in this string is
replaced by the number of matches that were added for this explanation string. The explanation
only appears if completion was tried and there was no unique match, or when listing completions.
Explanation strings will be listed together with the matches of the group specified together with
the X option (using the J or V option). If the same explanation string is given to multiple X
options, the string appears only once (for each group) and the number of matches shown for the
%n is the total number of all matches for each of these uses. In any case, the explanation string
will only be shown if there was at least one match added for the explanation string.
The sequences %B, %b, %S, %s, %U, and %u specify output attributes (bold, standout, and
underline) and %{...%} can be used to include literal escape sequences as in prompts.
Y explanation
Identical to X, except that the explanation first undergoes expansion following the usual rules for
strings in double quotes. The expansion will be carried out after any functions are called for the
K or y options, allowing them to set variables.
t continue

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPCTL ( 1 )

The continuestring contains a character that specifies which set of completion flags should be
used next. It is useful:
(i) With T, or when trying a list of pattern completions, when compctl would usually continue
with ordinary processing after finding matches; this can be suppressed with tn.
(ii) With a list of alternatives separated by +, when compctl would normally stop when one of the
alternatives generates matches. It can be forced to consider the next set of completions by adding
t+ to the flags of the alternative before the +.
(iii) In an extended completion list (see below), when compctl would normally continue until a set
of conditions succeeded, then use only the immediately following flags. With t, compctl will
continue trying extended completions after the next ; with tx it will attempt completion with
the default flags, in other words those before the x.
J name
This gives the name of the group the matches should be placed in. Groups are listed and sorted
separately; likewise, menu completion will offer the matches in the groups in the order in which
the groups were defined. If no group name is explicitly given, the matches are stored in a group
named default. The first time a group name is encountered, a group with that name is created.
After that all matches with the same group name are stored in that group.
This can be useful with nonexclusive alternative completions. For example, in
compctl f J files t+ + v J variables foo
both files and variables are possible completions, as the t+ forces both sets of alternatives before
and after the + to be considered at once. Because of the J options, however, all files are listed
before all variables.
V name
Like J, but matches within the group will not be sorted in listings nor in menu completion. These
unsorted groups are in a different name space from the sorted ones, so groups defined as J files
and V files are distinct.
1

If given together with the V option, makes only consecutive duplicates in the group be removed.
Note that groups with and without this flag are in different name spaces.

If given together with the J or V option, makes all duplicates be kept. Again, groups with and
without this flag are in different name spaces.

M matchspec
This defines additional matching control specifications that should be used only when testing
words for the list of flags this flag appears in. The format of the matchspec string is described in
zshcompwid.
ALTERNATIVE COMPLETION

compctl [ CDT ] options + options [ + ... ] [ + ] command ...


The form with + specifies alternative options. Completion is tried with the options before the first +. If
this produces no matches completion is tried with the flags after the + and so on. If there are no flags after
the last + and a match has not been found up to that point, default completion is tried. If the list of flags
contains a t with a + character, the next list of flags is used even if the current list produced matches.
EXTENDED COMPLETION

compctl [ CDT ] options x pattern options ...


[ command ... ]
compctl [ CDT ] options [ x pattern options ... ]
[ + options [ x ... ] ... [+] ] [ command ... ]
The form with x specifies extended completion for the commands given; as shown, it may be combined
with alternative completion using +. Each pattern is examined in turn; when a match is found, the

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCOMPCTL ( 1 )

corresponding options, as described in the section Option Flags above, are used to generate possible completions. If no pattern matches, the options given before the x are used.
Note that each pattern should be supplied as a single argument and should be quoted to prevent expansion
of metacharacters by the shell.
A pattern is built of subpatterns separated by commas; it matches if at least one of these subpatterns
matches (they are ored). These subpatterns are in turn composed of other subpatterns separated by
white spaces which match if all of the subpatterns match (they are anded). An element of the
subpatterns is of the form c[...][...], where the pairs of brackets may be repeated as often as necessary,
and matches if any of the sets of brackets match (an or). The example below makes this clearer.
The elements may be any of the following:
s[string]...
Matches if the current word on the command line starts with one of the strings given in brackets.
The string is not removed and is not part of the completion.
S[string]...
Like s[string] except that the string is part of the completion.
p[from,to]...
Matches if the number of the current word is between one of the from and to pairs inclusive. The
comma and to are optional; to defaults to the same value as from. The numbers may be negative:
n refers to the nth last word on the line.
c[offset,string]...
Matches if the string matches the word offset by offset from the current word position. Usually
offset will be negative.
C[offset,pattern]...
Like c but using pattern matching instead.
w[index,string]...
Matches if the word in position index is equal to the corresponding string. Note that the word
count is made after any alias expansion.
W[index,pattern]...
Like w but using pattern matching instead.
n[index,string]...
Matches if the current word contains string. Anything up to and including the indexth occurrence
of this string will not be considered part of the completion, but the rest will. index may be negative to count from the end: in most cases, index will be 1 or 1. For example,
compctl s users x n[1,@] k hosts talk
will usually complete usernames, but if you insert an @ after the name, names from the array hosts
(assumed to contain hostnames, though you must make the array yourself) will be completed.
Other commands such as rcp can be handled similarly.
N[index,string]...
Like n except that the string will be taken as a character class. Anything up to and including the
indexth occurrence of any of the characters in string will not be considered part of the completion.
m[min,max]...
Matches if the total number of words lies between min and max inclusive.
r[str1,str2]...
Matches if the cursor is after a word with prefix str1. If there is also a word with prefix str2 on the
command line after the one matched by str1 it matches only if the cursor is before this word. If the
comma and str2 are omitted, it matches if the cursor is after a word with prefix str1.
R[str1,str2]...

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPCTL ( 1 )

Like r but using pattern matching instead.


q[str]... Matches the word currently being completed is in single quotes and the str begins with the letter
s, or if completion is done in double quotes and str starts with the letter d, or if completion is
done in backticks and str starts with a b.
EXAMPLE

compctl u x s[+] c[1,f],s[f+] \


g /Mail/(:t) s[f],c[1,f] f mail
This is to be interpreted as follows:
If the current command is mail, then
if ((the current word begins with + and the previous word is f)
or (the current word begins with f+)), then complete the
nondirectory part (the :t glob modifier) of files in the directory
/Mail; else
if the current word begins with f or the previous word was f, then
complete any file; else
complete user names.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

NAME

zshmodules zsh loadable modules


DESCRIPTION

Some optional parts of zsh are in modules, separate from the core of the shell. Each of these modules may
be linked in to the shell at build time, or can be dynamically linked while the shell is running if the installation supports this feature. The modules that are bundled with the zsh distribution are:
zsh/cap Builtins for manipulating POSIX.1e (POSIX.6) capability (privilege) sets.
zsh/clone
A builtin that can clone a running shell onto another terminal.
zsh/compctl
The compctl builtin for controlling completion.
zsh/complete
The basic completion code.
zsh/complist
Completion listing extensions.
zsh/computil
A module with utility builtins needed for the shell function based completion system.
zsh/deltochar
A ZLE function duplicating EMACS zaptochar.
zsh/example
An example of how to write a module.
zsh/files
Some basic file manipulation commands as builtins.
zsh/mapfile
Access to external files via a special associative array.
zsh/mathfunc
Standard scientific functions for use in mathematical evaluations.
zsh/parameter
Access to internal hash tables via special associative arrays.
zsh/sched
A builtin that provides a timed execution facility within the shell.
zsh/stat A builtin command interface to the stat system call.
zsh/termcap
Interface to the termcap database.
zsh/terminfo
Interface to the terminfo database.
zsh/zftp
A builtin FTP client.
zsh/zle The Zsh Line Editor, including the bindkey and vared builtins.
zsh/zleparameter
Access to internals of the Zsh Line Editor via parameters.
zsh/zprof
A module allowing profiling for shell functions.
zsh/zpty
A builtin for starting a command in a pseudoterminal.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

zsh/zutil
Some utility builtins, e.g. the one for supporting configuration via styles.
THE ZSH/CAP MODULE

The zsh/cap module is used for manipulating POSIX.1e (POSIX.6) capability sets. If the operating system
does not support this interface, the builtins defined by this module will do nothing. The builtins in this
module are:
cap [ capabilities ]
Change the shells process capability sets to the specified capabilities, otherwise display the
shells current capabilities.
getcap filename ...
This is a builtin implementation of the POSIX standard utility. It displays the capability sets on
each specified filename.
setcap capabilities filename ...
This is a builtin implementation of the POSIX standard utility. It sets the capability sets on each
specified filename to the specified capabilities.
THE ZSH/CLONE MODULE

The zsh/clone module makes available one builtin command:


clone tty
Creates a forked instance of the current shell, attached to the specified tty. In the new shell, the
PID, PPID and TTY special parameters are changed appropriately. $! is set to zero in the new
shell, and to the new shells PID in the original shell.
The return value of the builtin is zero in both shells if successful, and nonzero on error.
THE ZSH/COMPCTL MODULE

The zsh/compctl module makes available two builtin commands. compctl, is the old, deprecated way to
control completions for ZLE. See zshcompctl(1). The other builtin command, compcall can be used in
userdefined completion widgets, see zshcompwid(1).
THE ZSH/COMPLETE MODULE

The zsh/complete module makes available several builtin commands which can be used in userdefined
completion widgets, see zshcompwid(1).
THE ZSH/COMPLIST MODULE

The zsh/complist module offers three extensions to completion listings: the ability to highlight matches in
such a list, the ability to scroll through long lists and a different style of menu completion.
Colored completion listings

Whenever one of the parameters ZLS_COLORS or ZLS_COLOURS is set and the zsh/complist module
is loaded or linked into the shell, completion lists will be colored. Note, however, that complist will not
automatically be loaded if it is not linked in: on systems with dynamic loading, zmodload zsh/complist
is required.
The parameters ZLS_COLORS and ZLS_COLOURS describe how matches are highlighted. To turn on
highlighting an empty value suffices, in which case all the default values given below will be used. The
format of the value of these parameters is the same as used by the GNU version of the ls command: a
colonseparated list of specifications of the form name=value. The name may be one of the following
strings, most of which specify file types for which the value will be used. The strings and their default
values are:

zsh 4.0.4

no 0

for normal text (i.e. when displaying something other than a matched file)

fi 0

for regular files

di 32

for directories

ln 36

for symbolic links

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

pi 31

for named pipes (FIFOs)

so 33

for sockets

ZSHMODULES ( 1 )

bd 44;37
for block devices
cd 44;37
for character devices
ex 35

for executable files

mi none
for a nonexistent file (default is the value defined for fi)
lc \e[

for the left code (see below)

rc m

for the right code

tc 0

for the character indicating the file type printed after filenames if the LIST_TYPES option is set

sp 0

for the spaces printed after matches to align the next column

ec none for the end code


Apart from these strings, the name may also be an asterisk () followed by any string. The value given for
such a string will be used for all files whose name ends with the string. The name may also be an equals
sign (=) followed by a pattern. The value given for this pattern will be used for all matches (not just
filenames) whose display string are matched by the pattern. Definitions for both of these take precedence
over the values defined for file types and the form with the leading asterisk takes precedence over the form
with the leading equal sign.
The last form also allows different parts of the displayed strings to be colored differently. For this, the pattern has to use the (#b) globbing flag and pairs of parentheses surrounding the parts of the strings that are
to be colored differently. In this case the value may consist of more than one color code separated by equal
signs. The first code will be used for all parts for which no explicit code is specified and the following
codes will be used for the parts matched by the subpatterns in parentheses. For example, the specification
=(#b)(?)(?)=0=3=7 will be used for all matches which are at least two characters long and will use the
code 3 for the first character, 7 for the last character and 0 for the rest.
All three forms of name may be preceded by a pattern in parentheses. If this is given, the value will be used
only for matches in groups whose names are matched by the pattern given in the parentheses. For example,
(g)m=43 highlights all matches beginning with m in groups whose names begin with g using the
color code 43. In case of the lc, rc, and ec codes, the group pattern is ignored.
Note also that all patterns are tried in the order in which they appear in the parameter value until the first
one matches which is then used.
When printing a match, the code prints the value of lc, the value for the filetype or the last matching
specification with a , the value of rc, the string to display for the match itself, and then the value of ec if
that is defined or the values of lc, no, and rc if ec is not defined.
The default values are ISO 6429 (ANSI) compliant and can be used on vt100 compatible terminals such as
xterms. On monochrome terminals the default values will have no visible effect. The colors function from
the contribution can be used to get associative arrays containing the codes for ANSI terminals (see the section Other Functions in zshcontrib(1)). For example, after loading colors, one could use $colors[red] to
get the code for foreground color red and $colors[bggreen] for the code for background color green.
If the completion system invoked by compinit is used, these parameters should not be set directly because
the system controls them itself. Instead, the listcolors style should be used (see the section Completion
System Configuration in zshcompsys(1)).

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHMODULES ( 1 )

Scrolling in completion listings

To enable scrolling through a completion list, the LISTPROMPT parameter must be set. Its value will be
used as the prompt; if it is the empty string, a default prompt will be used. The value may contain escapes
of the form %x. It supports the escapes %B, %b, %S, %s, %U, %u and %{...%} used also
in shell prompts as well as three pairs of additional sequences: a %l or %L is replaced by the number of
the last line shown and the total number of lines in the form number/total; a %m or %M is replaced
with the number of the last match shown and the total number of matches; and %p or %P is replaced
with Top, Bottom or the position of the first line shown in percent of the total number of lines, respectively. In each of these cases the form with the uppercase letter will be replaced with a string of fixed
width, padded to the right with spaces, while the lowercase form will not be padded.
If the parameter LISTPROMPT is set, the completion code will not ask if the list should be shown.
Instead it immediately starts displaying the list, stopping after the first screenful, showing the prompt at the
bottom, waiting for a keypress after temporarily switching to the listscroll keymap. Some of the zle functions have a special meaning while scrolling lists:
sendbreak
stops listing discarding the key pressed
acceptline, downhistory, downlineorhistory
downlineorsearch, vidownlineorhistory
scrolls forward one line
completeword, menucomplete, expandorcomplete
expandorcompleteprefix, menucompleteorexpand
scrolls forward one screenful
Every other character stops listing and immediately processes the key as usual. Any key that is not bound
in the listscroll keymap or that is bound to undefinedkey is looked up in the keymap currently selected.
As for the ZLS_COLORS and ZLS_COLOURS parameters, LISTPROMPT should not be set directly
when using the shell function based completion system. Instead, the listprompt style should be used.
Menu selection

The zsh/complist module also offers an alternative style of selecting matches from a list, called menu selection, which can be used if the shell is set up to return to the last prompt after showing a completion list (see
the ALWAYS_LAST_PROMPT option in zshoptions(1)). It can be invoked directly by the widget
menuselect defined by the module. Alternatively, the parameter MENUSELECT can be set to an
integer, which gives the minimum number of matches that must be present before menu selection is
automatically turned on. This second method requires that menu completion be started, either directly from
a widget such as menucomplete, or due to one of the options MENU_COMPLETE or AUTO_MENU
being set. If MENUSELECT is set, but is 0, 1 or empty, menu selection will always be started during an
ambiguous menu completion.
When using the completion system based on shell functions, the MENUSELECT parameter should not be
used (like the ZLS_COLORS and ZLS_COLOURS parameters described above). Instead, the menu
style should be used with the select=... keyword.
After menu selection is started, the matches will be listed. If there are more matches than fit on the screen,
only the first screenful is shown. The matches to insert into the command line can be selected from this list.
In the list one match is highlighted using the value for ma from the ZLS_COLORS or ZLS_COLOURS
parameter. The default value for this is 7 which forces the selected match to be highlighted using standout mode on a vt100compatible terminal. If neither ZLS_COLORS nor ZLS_COLOURS is set, the
same terminal control sequence as for the %S escape in prompts is used.
If there are more matches than fit on the screen and the parameter MENUPROMPT is set, its value will be
shown below the matches. It supports the same escape sequences as LISTPROMPT, but the number of
the match or line shown will be that of the one where the mark is placed. If its value is the empty string, a
default prompt will be used.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHMODULES ( 1 )

The MENUSCROLL parameter can be used to specify how the list is scrolled. If the parameter is unset,
this is done line by line, if it is set to 0 (zero), the list will scroll half the number of lines of the screen. If
the value is positive, it gives the number of lines to scroll and if it is negative, the list will be scrolled the
number of lines of the screen minus the (absolute) value.
As for the ZLS_COLORS, ZLS_COLOURS and LISTPROMPT parameters, neither MENUPROMPT
nor MENUSCROLL should be set directly when using the shell function based completion system.
Instead, the selectprompt and selectscroll styles should be used.
The completion code sometimes decides not to show all of the matches in the list. These hidden matches
are either matches for which the completion function which added them explicitly requested that they not
appear in the list (using the n option of the compadd builtin command) or they are matches which duplicate a string already in the list (because they differ only in things like prefixes or suffixes that are not
displayed). In the list used for menu selection, however, even these matches are shown so that it is possible
to select them. To highlight such matches the hi and du capabilities in the ZLS_COLORS and
ZLS_COLOURS parameters are supported for hidden matches of the first and second kind, respectively.
Selecting matches is done by moving the mark around using the zle movement functions. When not all
matches can be shown on the screen at the same time, the list will scroll up and down when crossing the top
or bottom line. The following zle functions have special meaning during menu selection:
acceptline
accepts the current match and leaves menu selection
sendbreak
leaves menu selection and restores the previous contents of the command line
redisplay, clearscreen
execute their normal function without leaving menu selection
acceptandhold, acceptandmenucomplete
accept the currently inserted match and continue selection allowing to select the next match to
insert into the line
acceptandinfernexthistory
accepts the current match and then tries completion with menu selection again; in the case of files
this allows one to select a directory and immediately attempt to complete files in it; if there are no
matches, a message is shown and one can use undo to go back to completion on the previous
level, every other key leaves menu selection (including the other zle functions which are otherwise
special during menu selection)
undo

removes matches inserted during the menu selection by one of the three functions before

downhistory, downlineorhistory
vidownlineorhistory, downlineorsearch
moves the mark one line down
uphistory, uplineorhistory
viuplineorhistory, uplineorsearch
moves the mark one line up
forwardchar, viforwardchar
moves the mark one column right
backwardchar, vibackwardchar
moves the mark one column left
forwardword, viforwardword
viforwardwordend, emacsforwardword
moves the mark one screenful down
backwardword, vibackwardword, emacsbackwardword

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

moves the mark one screenful up


viforwardblankword, viforwardblankwordend
moves the mark to the first line of the next group of matches
vibackwardblankword
moves the mark to the last line of the previous group of matches
beginningofhistory
moves the mark to the first line
endofhistory
moves the mark to the last line
beginningofbufferorhistory, beginningofline
beginningoflinehist, vibeginningofline
moves the mark to the leftmost column
endofbufferorhistory, endofline
endoflinehist, viendofline
moves the mark to the rightmost column
completeword, menucomplete, expandorcomplete
expandorcompleteprefix, menuexpandorcomplete
moves the mark to the next match
reversemenucomplete
moves the mark to the previous match
All movement functions wrap around at the edges; any other zle function not listed leaves menu selection
and executes that function. It is possible to make widgets in the above list do the same by using the form of
the widget with a . in front. For example, the widget .acceptline has the effect of leaving menu selection and accepting the entire command line.
During this selection the widget uses the keymap menuselect. Any key that is not defined in this keymap
or that is bound to undefinedkey is looked up in the keymap currently selected. This is used to ensure
that the most important keys used during selection (namely the cursor keys, return, and TAB) have sensible
defaults. However, keys in the menuselect keymap can be modified directly using the bindkey builtin
command (see zshmodules(1)). For example, to make the return key leave menu selection without accepting
the match currently selected one could call
bindkey M menuselect M sendbreak
after loading the zsh/complist module.
THE ZSH/COMPUTIL MODULE

The zsh/computil module adds several builtin commands that are used by some of the completion functions in the completion system based on shell functions (see zshcompsys(1) ). Except for compquote these
builtin commands are very specialised and thus not very interesting when writing your own completion
functions. In summary, these builtin commands are:
comparguments
This is used by the _arguments function to do the argument and command line parsing. Like
compdescribe it has an option i to do the parsing and initialize some internal state and various
options to access the state information to decide what should be completed.
compdescribe
This is used by the _describe function to build the displays for the matches and to get the strings
to add as matches with their options. On the first call one of the options i or I should be supplied as the first argument. In the first case, display strings without the descriptions will be generated, in the second case, the string used to separate the matches from their descriptions must be
given as the second argument and the descriptions (if any) will be shown. All other arguments are

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

like the definition arguments to _describe itself.


Once compdescribe has been called with either the i or the I option, it can be repeatedly called
with the g option and the names of five arrays as its arguments. This will step through the
different sets of matches and store the options in the first array, the strings with descriptions in the
second, the matches for these in the third, the strings without descriptions in the fourth, and the
matches for them in the fifth array. These are then directly given to compadd to register the
matches with the completion code.
compfiles
Used by the _path_files function to optimize complex recursive filename generation (globbing). It
does three things. With the p and P options it builds the glob patterns to use, including the
paths already handled and trying to optimize the patterns with respect to the prefix and suffix from
the line and the match specification currently used. The i option does the directory tests for the
ignoreparents style and the r option tests if a component for some of the matches are equal to
the string on the line and removes all other matches if that is true.
compgroups
Used by the _tags function to implement the internals of the grouporder style. This only takes
its arguments as names of completion groups and creates the groups for it (all six types: sorted and
unsorted, both without removing duplicates, with removing all duplicates and with removing consecutive duplicates).
compquote [ p ] names ...
There may be reasons to write completion functions that have to add the matches using the Q
option to compadd and perform quoting themselves. Instead of interpreting the first character of
the all_quotes key of the compstate special association and using the q flag for parameter expansions, one can use this builtin command. The arguments are the names of scalar or array parameters and the values of these parameters are quoted as needed for the innermost quoting level. If the
p option is given, quoting is done as if there is some prefix before the values of the parameters, so
that a leading equal sign will not be quoted.
The return value is nonzero in case of an error and zero otherwise.
comptags
comptry
These implement the internals of the tags mechanism.
compvalues
Like comparguments, but for the _values function.
THE ZSH/DELTOCHAR MODULE

The zsh/deltochar module makes available two ZLE functions:


deletetochar
Read a character from the keyboard, and delete from the cursor position up to and including the
next (or, with repeat count n, the nth) instance of that character. Negative repeat counts mean
delete backwards.
zaptochar
This behaves like deletetochar, except that the final occurrence of the character itself is not
deleted.
THE ZSH/EXAMPLE MODULE

The zsh/example module makes available one builtin command:


example [ flags ] [ args ... ]
Displays the flags and arguments it is invoked with.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

The purpose of the module is to serve as an example of how to write a module.


THE ZSH/FILES MODULE

The zsh/files module makes some standard commands available as builtins:


chgrp [ Rs ] group filename ...
Changes group of files specified. This is equivalent to chown with a userspec argument of
:group.
chown [ Rs ] userspec filename ...
Changes ownership and group of files specified.
The userspec can be in four forms:
user
change owner to user; do not change group
user:: change owner to user; do not change group
user:
change owner to user; change group to users primary group
user:group
change owner to user; change group to group
:group do not change owner; change group to group
In each case, the : may instead be a .. The rule is that if there is a : then the separator is :,
otherwise if there is a . then the separator is ., otherwise there is no separator.
Each of user and group may be either a username (or group name, as appropriate) or a decimal
user ID (group ID). Interpretation as a name takes precedence, if there is an allnumeric username
(or group name).
The R option causes chown to recursively descend into directories, changing the ownership of all
files in the directory after changing the ownership of the directory itself.
The s option is a zsh extension to chown functionality. It enables paranoid behaviour, intended
to avoid security problems involving a chown being tricked into affecting files other than the ones
intended. It will refuse to follow symbolic links, so that (for example) chown luser
/tmp/foo/passwd cant accidentally chown /etc/passwd if /tmp/foo happens to be a link to /etc.
It will also check where it is after leaving directories, so that a recursive chown of a deep directory
tree cant end up recursively chowning /usr as a result of directories being moved up the tree.
ln [ dfis ] filename dest
ln [ dfis ] filename ... dir
Creates hard (or, with s, symbolic) links. In the first form, the specified destination is created, as
a link to the specified filename. In the second form, each of the filenames is taken in turn, and
linked to a pathname in the specified directory that has the same last pathname component.
Normally, ln will not attempt to create hard links to directories. This check can be overridden
using the d option. Typically only the superuser can actually succeed in creating hard links to
directories. This does not apply to symbolic links in any case.
By default, existing files cannot be replaced by links. The i option causes the user to be queried
about replacing existing files. The f option causes existing files to be silently deleted, without
querying. f takes precedence.
mkdir [ p ] [ m mode ] dir ...
Creates directories. With the p option, nonexisting parent directories are first created if necessary, and there will be no complaint if the directory already exists. The m option can be used to
specify (in octal) a set of file permissions for the created directories, otherwise mode 777 modified
by the current umask (see umask(2)) is used.
mv [ fi ] filename dest
mv [ fi ] filename ... dir
Moves files. In the first form, the specified filename is moved to the specified destination. In the
second form, each of the filenames is taken in turn, and moved to a pathname in the specified

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

directory that has the same last pathname component.


By default, the user will be queried before replacing any file that the user cannot write to, but writable files will be silently removed. The i option causes the user to be queried about replacing any
existing files. The f option causes any existing files to be silently deleted, without querying. f
takes precedence.
Note that this mv will not move files across devices. Historical versions of mv, when actual
renaming is impossible, fall back on copying and removing files; if this behaviour is desired, use
cp and rm manually. This may change in a future version.
rm [ dfirs ] filename ...
Removes files and directories specified.
Normally, rm will not remove directories (except with the r option). The d option causes rm to
try removing directories with unlink (see unlink(2)), the same method used for files. Typically
only the superuser can actually succeed in unlinking directories in this way. d takes precedence
over r.
By default, the user will be queried before removing any file that the user cannot write to, but writable files will be silently removed. The i option causes the user to be queried about removing any
files. The f option causes files to be silently deleted, without querying, and suppresses all error
indications. f takes precedence.
The r option causes rm to recursively descend into directories, deleting all files in the directory
before removing the directory with the rmdir system call (see rmdir(2)).
The s option is a zsh extension to rm functionality. It enables paranoid behaviour, intended to
avoid common security problems involving a rootrun rm being tricked into removing files other
than the ones intended. It will refuse to follow symbolic links, so that (for example) rm
/tmp/foo/passwd cant accidentally remove /etc/passwd if /tmp/foo happens to be a link to /etc.
It will also check where it is after leaving directories, so that a recursive removal of a deep directory tree cant end up recursively removing /usr as a result of directories being moved up the tree.
rmdir dir ...
Removes empty directories specified.
sync

Calls the system call of the same name (see sync(2)), which flushes dirty buffers to disk. It might
return before the I/O has actually been completed.

THE ZSH/MAPFILE MODULE

The zsh/mapfile module provides one special associative array parameter of the same name.
mapfile This associative array takes as keys the names of files; the resulting value is the content of the file.
The value is treated identically to any other text coming from a parameter. The value may also be
assigned to, in which case the file in question is written (whether or not it originally existed); or an
element may be unset, which will delete the file in question. For example, vared
mapfile[myfile] works as expected, editing the file myfile.
When the array is accessed as a whole, the keys are the names of files in the current directory, and
the values are empty (to save a huge overhead in memory). Thus ${(k)mapfile} has the same
affect as the glob operator (D), since files beginning with a dot are not special. Care must be
taken with expressions such as rm ${(k)mapfile}, which will delete every file in the current directory without the usual rm test.
The parameter mapfile may be made readonly; in that case, files referenced may not be written or
deleted.
Limitations

Although reading and writing of the file in question is efficiently handled, zshs internal memory management may be arbitrarily baroque. Thus it should not automatically be assumed that use of mapfile
represents a gain in efficiency over use of other mechanisms. Note in particular that the whole contents of

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

the file will always reside physically in memory when accessed (possibly multiple times, due to standard
parameter substitution operations). In particular, this means handling of sufficiently long files (greater than
the machines swap space, or than the range of the pointer type) will be incorrect.
No errors are printed or flagged for nonexistent, unreadable, or unwritable files, as the parameter mechanism is too low in the shell execution hierarchy to make this convenient.
It is unfortunate that the mechanism for loading modules does not yet allow the user to specify the name of
the shell parameter to be given the special behaviour.
THE ZSH/MATHFUNC MODULE

The zsh/mathfunc module provides standard mathematical functions for use when evaluating mathematical
formulae. The syntax agrees with normal C and FORTRAN conventions, for example,
(( f = sin(0.3) ))
assigns the sine of 0.3 to the parameter f.
Most functions take floating point arguments and return a floating point value. However, any necessary
conversions from or to integer type will be performed automatically by the shell. Apart from atan with a
second argument and the abs, int and float functions, all functions behave as noted in the manual page for
the corresponding C function, except that any arguments out of range for the function in question will be
detected by the shell and an error reported.
The following functions take a single floating point argument: acos, acosh, asin, asinh, atan, atanh, cbrt,
ceil, cos, cosh, erf, erfc, exp, expm1, fabs, floor, gamma, j0, j1, lgamma, log, log10, log1p, logb, sin,
sinh, sqrt, tan, tanh, y0, y1. The atan function can optionally take a second argument, in which case it
behaves like the C function atan2. The ilogb function takes a single floating point argument, but returns an
integer.
The function signgam takes no arguments, and returns an integer, which is the C variable of the same
name, as described in gamma(3). Note that it is therefore only useful immediately after a call to gamma or
lgamma. Note also that signgam() and signgam are distinct expressions.
The following functions take two floating point arguments: copysign, fmod, hypot, nextafter.
The following take an integer first argument and a floating point second argument: jn, yn.
The following take a floating point first argument and an integer second argument: ldexp, scalb.
The function abs does not convert the type of its single argument; it returns the absolute value of either a
floating point number or an integer. The functions float and int convert their arguments into a floating
point or integer value (by truncation) respectively.
Note that the C pow function is available in ordinary math evaluation as the operator and is not provided here.
THE ZSH/PARAMETER MODULE

The zsh/parameter module gives access to some of the internal hash tables used by the shell by defining
some special parameters.
options The keys for this associative array are the names of the options that can be set and unset using the
setopt and unsetopt builtins. The value of each key is either the string on if the option is currently
set, or the string off if the option is unset. Setting a key to one of these strings is like setting or
unsetting the option, respectively. Unsetting a key in this array is like setting it to the value off.
commands
This array gives access to the command hash table. The keys are the names of external commands,
the values are the pathnames of the files that would be executed when the command would be
invoked. Setting a key in this array defines a new entry in this table in the same way as with the
hash builtin. Unsetting a key as in unset " commands[foo]" removes the entry for the given key
from the command hash table.
functions

zsh 4.0.4

Last change: October 26, 2001

10

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHMODULES ( 1 )

This associative array maps names of enabled functions to their definitions. Setting a key in it is
like defining a function with the name given by the key and the body given by the value. Unsetting
a key removes the definition for the function named by the key.
dis_functions
Like functions but for disabled functions.
builtins This associative array gives information about the builtin commands currently enabled. The keys
are the names of the builtin commands and the values are either undefined for builtin commands
that will automatically be loaded from a module if invoked or defined for builtin commands that
are already loaded.
dis_builtins
Like builtins but for disabled builtin commands.
reswords
This array contains the enabled reserved words.
dis_reswords
Like reswords but for disabled reserved words.
aliases This maps the names of the regular aliases currently enabled to their expansions.
dis_aliases
Like raliases but for disabled regular aliases.
galiases Like raliases, but for global aliases.
dis_galiases
Like galiases but for disabled global aliases.
parameters
The keys in this associative array are the names of the parameters currently defined. The values are
strings describing the type of the parameter, in the same format used by the t parameter flag, see
zshexpn(1) . Setting or unsetting keys in this array is not possible.
modules
An associative array giving information about modules. The keys are the names of the modules
loaded, registered to be autoloaded, or aliased. The value says which state the named module is in
and is one of the strings loaded, autoloaded, or alias:name, where name is the name the
module is aliased to.
Setting or unsetting keys in this array is not possible.
dirstack
A normal array holding the elements of the directory stack. Note that the output of the dirs builtin
command includes one more directory, the current working directory.
history This associative array maps history event numbers to the full history lines.
historywords
A special array containing the words stored in the history.
jobdirs This associative array maps job numbers to the directories from which the job was started (which
may not be the current directory of the job).
jobtexts
This associative array maps job numbers to the texts of the command lines that were used to start
the jobs.
jobstates
This associative array gives information about the states of the jobs currently known. The keys are
the job numbers and the values are strings of the form jobstate:mark:pid=state.... The jobstate
gives the state the whole job is currently in, one of running, suspended, or done. The mark

zsh 4.0.4

Last change: October 26, 2001

11

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

is + for the current job, for the previous job and empty otherwise. This is followed by one
pid=state for every process in the job. The pids are, of course, the process IDs and the state
describes the state of that process.
nameddirs
This associative array maps the names of named directories to the pathnames they stand for.
userdirs
This associative array maps user names to the pathnames of their home directories.
funcstack
This array contains the names of the functions currently being executed. The first element is the
name of the function using the parameter.
THE ZSH/SCHED MODULE

The zsh/sched module makes available one builtin command:


sched [+]hh:mm command ...
sched [ item ]
Make an entry in the scheduled list of commands to execute. The time may be specified in either
absolute or relative time. With no arguments, prints the list of scheduled commands. With the
argument item, removes the given item from the list.
THE ZSH/STAT MODULE

The zsh/stat module makes available one builtin command:


stat [ gnNolLtTrs ] [ f fd ] [ H hash ] [ A array ] [ F fmt ] [ +element ] [ file ... ]
The command acts as a front end to the stat system call (see stat(2)). If the stat call fails, the
appropriate system error message printed and status 1 is returned. The fields of struct stat give
information about the files provided as arguments to the command. In addition to those available
from the stat call, an extra element link is provided. These elements are:
device The number of the device on which the file resides.
inode

The unique number of the file on this device (inode number).

mode

The mode of the file; that is, the files type and access permissions. With the s option,
this will be returned as a string corresponding to the first column in the display of the ls l
command.

nlink

The number of hard links to the file.

uid

The user ID of the owner of the file. With the s option, this is displayed as a user name.

gid

The group ID of the file. With the s option, this is displayed as a group name.

rdev

The raw device number. This is only useful for special devices.

size

The size of the file in bytes.

atime
mtime
ctime The last access, modification and inode change times of the file, respectively, as the
number of seconds since midnight GMT on 1st January, 1970. With the s option, these
are printed as strings for the local time zone; the format can be altered with the F option,
and with the g option the times are in GMT.
blksize The number of bytes in one allocation block on the device on which the file resides.

zsh 4.0.4

block

The number of disk blocks used by the file.

link

If the file is a link and the L option is in effect, this contains the name of the file linked
to, otherwise it is empty. Note that if this element is selected (stat +link) then the L
option is automatically used.

Last change: October 26, 2001

12

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

A particular element may be selected by including its name preceded by a + in the option list;
only one element is allowed. The element may be shortened to any unique set of leading characters. Otherwise, all elements will be shown for all files.
Options:
A array
Instead of displaying the results on standard output, assign them to an array, one struct
stat element per array element for each file in order. In this case neither the name of the
element nor the name of the files appears in array unless the t or n options were given,
respectively. If t is given, the element name appears as a prefix to the appropriate array
element; if n is given, the file name appears as a separate array element preceding all the
others. Other formatting options are respected.
H hash
Similar to A, but instead assign the values to hash. The keys are the elements listed
above. If the n option is provided then the name of the file is included in the hash with
key name.
f fd

Use the file on file descriptor fd instead of named files; no list of file names is allowed in
this case.

F fmt Supplies a strftime (see strftime(3)) string for the formatting of the time elements. The
s option is implied.
g

Show the time elements in the GMT time zone. The s option is implied.

List the names of the type elements (to standard output or an array as appropriate) and
return immediately; options other than A and arguments are ignored.

Perform an lstat (see lstat(2)) rather than a stat system call. In this case, if the file is a
link, information about the link itself rather than the target file is returned. This option is
required to make the link element useful.

Always show the names of files. Usually these are only shown when output is to standard
output and there is more than one file in the list.

Never show the names of files.

If a raw file mode is printed, show it in octal, which is more useful for human consumption than the default of decimal. A leading zero will be printed in this case. Note that
this does not affect whether a raw or formatted file mode is shown, which is controlled by
the r and s options, nor whether a mode is shown at all.

Print raw data (the default format) alongside string data (the s format); the string data
appears in parentheses after the raw data.

Print mode, uid, gid and the three time elements as strings instead of numbers. In each
case the format is like that of ls l.

Always show the type names for the elements of struct stat. Usually these are only
shown when output is to standard output and no individual element has been selected.

Never show the type names of the struct stat elements.

THE ZSH/TERMCAP MODULE

The zsh/termcap module makes available one builtin command:


echotc cap [ arg ... ]
Output the termcap value corresponding to the capability cap, with optional arguments.
The zsh/termcap module makes available one parameter:

zsh 4.0.4

Last change: October 26, 2001

13

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

termcap
An associative array that maps termcap capability codes to their values.
THE ZSH/TERMINFO MODULE

The zsh/terminfo module makes available one builtin command:


echoti cap
Output the terminfo value corresponding to the capability cap.
The zsh/terminfo module makes available one parameter:
terminfo
An associative array that maps terminfo capability names to their values.
THE ZSH/ZFTP MODULE

The zsh/zftp module makes available one builtin command:


zftp subcommand [ args ]
The zsh/zftp module is a client for FTP (file transfer protocol). It is implemented as a builtin to
allow full use of shell command line editing, file I/O, and job control mechanisms. Often, users
will access it via shell functions providing a more powerful interface; a set is provided with the
zsh distribution and is described in zshzftpsys(1). However, the zftp command is entirely usable in
its own right.
All commands consist of the command name zftp followed by the name of a subcommand. These
are listed below. The return status of each subcommand is supposed to reflect the success or
failure of the remote operation. See a description of the variable ZFTP_VERBOSE for more
information on how responses from the server may be printed.
Subcommands

open host [ user [ password [ account ] ] ]


Open a new FTP session to host, which may be the name of a TCP/IP connected host or an IP
number in the standard dot notation. Remaining arguments are passed to the login subcommand.
Note that if no arguments beyond host are supplied, open will not automatically call login. If no
arguments at all are supplied, open will use the parameters set by the params subcommand.
After a successful open, the shell variables ZFTP_HOST, ZFTP_IP and ZFTP_SYSTEM are
available; see Variables below.
login [ name [ password [ account ] ] ]
user [ name [ password [ account ] ] ]
Login the user name with parameters password and account. Any of the parameters can be omitted, and will be read from standard input if needed (name is always needed). If standard input is a
terminal, a prompt for each one will be printed on standard error and password will not be echoed.
If any of the parameters are not used, a warning message is printed.
After a successful login, the shell variables ZFTP_USER, ZFTP_ACCOUNT and ZFTP_PWD
are available; see Variables below.
This command may be reissued when a user is already logged in, and the server will first be reinitialized for a new user.
params [ host [ user [ password [ account ] ] ] ]
params
Store the given parameters for a later open command with no arguments. Only those given on the
command line will be remembered. If no arguments are given, the parameters currently set are
printed, although the password will appear as a line of stars; the return value is one if no parameters were set, zero otherwise.
Any of the parameters may be specified as a ?, which may need to be quoted to protect it from
shell expansion. In this case, the appropriate parameter will be read from stdin as with the login
subcommand, including special handling of password. If the ? is followed by a string, that is

zsh 4.0.4

Last change: October 26, 2001

14

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

used as the prompt for reading the parameter instead of the default message (any necessary punctuation and whitespace should be included at the end of the prompt). The first letter of the parameter (only) may be quoted with a \; hence an argument " \\$word" guarantees that the string from
the shell parameter $word will be treated literally, whether or not it begins with a ?.
If instead a single is given, the existing parameters, if any, are deleted. In that case, calling
open with no arguments will cause an error.
The list of parameters is not deleted after a close, however it will be deleted if the zsh/zftp module
is unloaded.
For example,
zftp params ftp.elsewhere.xx juser ?Password for juser:
will store the host ftp.elsewhere.xx and the user juser and then prompt the user for the
corresponding password with the given prompt.
test

Test the connection; if the server has reported that it has closed the connection (maybe due to a
timeout), return status 2; if no connection was open anyway, return status 1; else return status 0.
The test subcommand is silent, apart from messages printed by the $ZFTP_VERBOSE mechanism, or error messages if the connection closes. There is no network overhead for this test.
The test is only supported on systems with either the select(2) or poll(2) system calls; otherwise
the message not supported on this system is printed instead.
The test subcommand will automatically be called at the start of any other subcommand for the
current session when a connection is open.

cd directory
Change the remote directory to directory. Also alters the shell variable ZFTP_PWD.
cdup

Change the remote directory to the one higher in the directory tree. Note that cd .. will also work
correctly on nonUNIX systems.

dir [ args... ]
Give a (verbose) listing of the remote directory. The args are passed directly to the server. The
commands behaviour is implementation dependent, but a UNIX server will typically interpret
args as arguments to the ls command and with no arguments return the result of ls l. The directory is listed to standard output.
ls [ args ]
Give a (short) listing of the remote directory. With no args, produces a raw list of the files in the
directory, one per line. Otherwise, up to vagaries of the server implementation, behaves similar to
dir.
type [ type ]
Change the type for the transfer to type, or print the current type if type is absent. The allowed
values are A (ASCII), I (Image, i.e. binary), or B (a synonym for I).
The FTP default for a transfer is ASCII. However, if zftp finds that the remote host is a UNIX
machine with 8bit byes, it will automatically switch to using binary for file transfers upon open.
This can subsequently be overridden.
The transfer type is only passed to the remote host when a data connection is established; this
command involves no network overhead.
ascii

The same as type A.

binary The same as type I.


mode [ S B ]
Set the mode type to stream (S) or block (B). Stream mode is the default; block mode is not
widely supported.

zsh 4.0.4

Last change: October 26, 2001

15

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHMODULES ( 1 )

remote files...
local [ files... ]
Print the size and last modification time of the remote or local files. If there is more than one item
on the list, the name of the file is printed first. The first number is the file size, the second is the
last modification time of the file in the format CCYYMMDDhhmmSS consisting of year, month,
date, hour, minutes and seconds in GMT. Note that this format, including the length, is
guaranteed, so that time strings can be directly compared via the [[ builtins < and > operators,
even if they are too long to be represented as integers.
Not all servers support the commands for retrieving this information. In that case, the remote
command will print nothing and return status 2, compared with status 1 for a file not found.
The local command (but not remote) may be used with no arguments, in which case the information comes from examining file descriptor zero. This is the same file as seen by a put command
with no further redirection.
get file [...]
Retrieve all files from the server, concatenating them and sending them to standard output.
put file [...]
For each file, read a file from standard input and send that to the remote host with the given name.
append file [...]
As put, but if the remote file already exists, data is appended to it instead of overwriting it.
getat file point
putat file point
appendat file point
Versions of get, put and append which will start the transfer at the given point in the remote file.
This is useful for appending to an incomplete local file. However, note that this ability is not
universally supported by servers (and is not quite the behaviour specified by the standard).
delete file [...]
Delete the list of files on the server.
mkdir directory
Create a new directory directory on the server.
rmdir directory
Delete the directory directory on the server.
rename oldname newname
Rename file oldname to newname on the server.
site args...
Send a hostspecific command to the server. You will probably only need this if instructed by the
server to use it.
quote args...
Send the raw FTP command sequence to the server. You should be familiar with the FTP command set as defined in RFC959 before doing this. Useful commands may include STAT and
HELP. Note also the mechanism for returning messages as described for the variable
ZFTP_VERBOSE below, in particular that all messages from the control connection are sent to
standard error.
close
quit

Close the current data connection. This unsets the shell parameters ZFTP_HOST, ZFTP_IP,
ZFTP_SYSTEM, ZFTP_USER, ZFTP_ACCOUNT, ZFTP_PWD, ZFTP_TYPE and
ZFTP_MODE.

session [ sessname ]
Allows multiple FTP sessions to be used at once. The name of the session is an arbitrary string of

zsh 4.0.4

Last change: October 26, 2001

16

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHMODULES ( 1 )

characters; the default session is called default. If this command is called without an argument,
it will list all the current sessions; with an argument, it will either switch to the existing session
called sessname, or create a new session of that name.
Each session remembers the status of the connection, the set of connectionspecific shell parameters (the same set as are unset when a connection closes, as given in the description of close), and
any user parameters specified with the params subcommand. Changing to a previous session
restores those values; changing to a new session initialises them in the same way as if zftp had just
been loaded. The name of the current session is given by the parameter ZFTP_SESSION.
rmsession [ sessname ]
Delete a session; if a name is not given, the current session is deleted. If the current session is
deleted, the earliest existing session becomes the new current session, otherwise the current session is not changed. If the session being deleted is the only one, a new session called default is
created and becomes the current session; note that this is a new session even if the session being
deleted is also called default. It is recommended that sessions not be deleted while background
commands which use zftp are still active.
Parameters

The following shell parameters are used by zftp. Currently none of them are special.
ZFTP_TMOUT
Integer. The time in seconds to wait for a network operation to complete before returning an error.
If this is not set when the module is loaded, it will be given the default value 60. A value of zero
turns off timeouts. If a timeout occurs on the control connection it will be closed. Use a larger
value if this occurs too frequently.
ZFTP_IP
Readonly. The IP address of the current connection in dot notation.
ZFTP_HOST
Readonly. The hostname of the current remote server. If the host was opened as an IP number,
ZFTP_HOST contains that instead; this saves the overhead for a name lookup, as IP numbers are
most commonly used when a nameserver is unavailable.
ZFTP_SYSTEM
Readonly. The system type string returned by the server in response to an FTP SYST request.
The most interesting case is a string beginning " UNIX Type: L8" , which ensures maximum compatibility with a local UNIX host.
ZFTP_TYPE
Readonly. The type to be used for data transfers , either A or I. Use the type subcommand to
change this.
ZFTP_USER
Readonly. The username currently logged in, if any.
ZFTP_ACCOUNT
Readonly. The account name of the current user, if any. Most servers do not require an account
name.
ZFTP_PWD
Readonly. The current directory on the server.
ZFTP_CODE
Readonly. The three digit code of the last FTP reply from the server as a string. This can still be
read after the connection is closed, and is not changed when the current session changes.
ZFTP_REPLY
Readonly. The last line of the last reply sent by the server. This can still be read after the connection is closed, and is not changed when the current session changes.

zsh 4.0.4

Last change: October 26, 2001

17

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

ZFTP_SESSION
Readonly. The name of the current FTP session; see the description of the session subcommand.
ZFTP_PREFS
A string of preferences for altering aspects of zftps behaviour. Each preference is a single character. The following are defined:
P

Passive: attempt to make the remote server initiate data transfers. This is slightly more
efficient than sendport mode. If the letter S occurs later in the string, zftp will use sendport mode if passive mode is not available.

Sendport: initiate transfers by the FTP PORT command. If this occurs before any P in
the string, passive mode will never be attempted.

Dumb: use only the bare minimum of FTP commands. This prevents the variables
ZFTP_SYSTEM and ZFTP_PWD from being set, and will mean all connections default
to ASCII type. It may prevent ZFTP_SIZE from being set during a transfer if the server
does not send it anyway (many servers do).

If ZFTP_PREFS is not set when zftp is loaded, it will be set to a default of PS, i.e. use passive
mode if available, otherwise fall back to sendport mode.
ZFTP_VERBOSE
A string of digits between 0 and 5 inclusive, specifying which responses from the server should be
printed. All responses go to standard error. If any of the numbers 1 to 5 appear in the string, raw
responses from the server with reply codes beginning with that digit will be printed to standard
error. The first digit of the three digit reply code is defined by RFC959 to correspond to:
1.

A positive preliminary reply.

2.

A positive completion reply.

3.

A positive intermediate reply.

4.

A transient negative completion reply.

5.

A permanent negative completion reply.

It should be noted that, for unknown reasons, the reply Service not available, which forces termination of a connection, is classified as 421, i.e. transient negative, an interesting interpretation of
the word transient.
The code 0 is special: it indicates that all but the last line of multiline replies read from the server
will be printed to standard error in a processed format. By convention, servers use this mechanism
for sending information for the user to read. The appropriate reply code, if it matches the same
response, takes priority.
If ZFTP_VERBOSE is not set when zftp is loaded, it will be set to the default value 450, i.e.,
messages destined for the user and all errors will be printed. A null string is valid and specifies
that no messages should be printed.
Functions

zftp_chpwd
If this function is set by the user, it is called every time the directory changes on the server, including when a user is logged in, or when a connection is closed. In the last case, $ZFTP_PWD will
be unset; otherwise it will reflect the new directory.
zftp_progress
If this function is set by the user, it will be called during a get, put or append operation each time
sufficient data has been received from the host. During a get, the data is sent to standard output, so
it is vital that this function should write to standard error or directly to the terminal, not to standard
output.

zsh 4.0.4

Last change: October 26, 2001

18

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

When it is called with a transfer in progress, the following additional shell parameters are set:
ZFTP_FILE
The name of the remote file being transferred from or to.
ZFTP_TRANSFER
A G for a get operation and a P for a put operation.
ZFTP_SIZE
The total size of the complete file being transferred: the same as the first value provided
by the remote and local subcommands for a particular file. If the server cannot supply
this value for a remote file being retrieved, it will not be set. If input is from a pipe the
value may be incorrect and correspond simply to a full pipe buffer.
ZFTP_COUNT
The amount of data so far transferred; a number between zero and $ZFTP_SIZE, if that
is set. This number is always available.
The function is initially called with ZFTP_TRANSFER set appropriately and ZFTP_COUNT
set to zero. After the transfer is finished, the function will be called one more time with
ZFTP_TRANSFER set to GF or PF, in case it wishes to tidy up. It is otherwise never called
twice with the same value of ZFTP_COUNT.
Sometimes the progress meter may cause disruption. It is up to the user to decide whether the
function should be defined and to use unfunction when necessary.
Problems

A connection may not be opened in the left hand side of a pipe as this occurs in a subshell and the file information is not updated in the main shell. In the case of type or mode changes or closing the connection in a
subshell, the information is returned but variables are not updated until the next call to zftp. Other status
changes in subshells will not be reflected by changes to the variables (but should be otherwise harmless).
Deleting sessions while a zftp command is active in the background can have unexpected effects, even if it
does not use the session being deleted. This is because all shell subprocesses share information on the state
of all connections, and deleting a session changes the ordering of that information.
On some operating systems, the control connection is not valid after a fork(), so that operations in subshells, on the left hand side of a pipeline, or in the background are not possible, as they should be. This is
presumably a bug in the operating system.
THE ZSH/ZLE MODULE

The zsh/zle module contains the Zsh Line Editor. See zshzle(1).
THE ZSH/ZLEPARAMETER MODULE

The zsh/zleparameter module defines two special parameters that can be used to access internal information of the Zsh Line Editor (see zshzle(1)).
keymaps
This array contains the names of the keymaps currently defined.
widgets This associative array contains one entry per widget defined. The name of the widget is the key
and the value gives information about the widget. It is either the string builtin for builtin widgets, a string of the form user:name for userdefined widgets, where name is the name of the shell
function implementing the widget, or it is a string of the form completion:type:name, for completion widgets. In the last case type is the name of the builtin widgets the completion widget imitates in its behavior and name is the name of the shell function implementing the completion
widget.
THE ZSH/ZPROF MODULE

When loaded, the zsh/zprof causes shell functions to be profiled. The profiling results can be obtained with
the zprof builtin command made available by this module. There is no way to turn profiling off other than
unloading the module.

zsh 4.0.4

Last change: October 26, 2001

19

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

zprof [ c ]
Without the c option, zprof lists profiling results to standard output. The format is comparable to
that of commands like gprof.
At the top there is a summary listing all functions that were called at least once. This summary is
sorted in decreasing order of the amount of time spent in each. The lines contain the number of
the function in order, which is used in other parts of the list in suffixes of the form [num].RE,
then the number of calls made to the function. The next three columns list the time in milliseconds spent in the function and its descendents, the average time in milliseconds spent in the
function and its descendents per call and the percentage of time spent in all shell functions used in
this function and its descendents. The following three columns give the same information, but
counting only the time spent in the function itself. The final column shows the name of the function.
After the summary, detailed information about every function that was invoked is listed, sorted in
decreasing order of the amount of time spent in each function and its descendents. Each of these
entries consists of descriptions for the functions that called the function described, the function
itself, and the functions that were called from it. The description for the function itself has the
same format as in the summary (and shows the same information). The other lines dont show the
number of the function at the beginning and have their function named indented to make it easier
to distinguish the line showing the function described in the section from the surrounding lines.
The information shown in this case is almost the same as in the summary, but only refers to the
call hierarchy being displayed. For example, for a calling function the column showing the total
running time lists the time spent in the described function and its descendents only for the times
when it was called from that particular calling function. Likewise, for a called function, this
columns lists the total time spent in the called function and its descendents only for the times when
it was called from the function described.
Also in this case, the column showing the number of calls to a function also shows a slash and
then the total number of invocations made to the called function.
As long as the zsh/zprof module is loaded, profiling will be done and multiple invocations of the
zprof builtin command will show the times and numbers of calls since the module was loaded.
With the c option, the zprof builtin command will reset its internal counters and will not show
the listing. )
THE ZSH/ZPTY MODULE

The zsh/zpty module offers one builtin:


zpty [ e ] [ b ] name [ arg ... ]
The arguments following name are concatenated with spaces between, then executed as a command, as if passed to the eval builtin. The command runs under a newly assigned
pseudoterminal; this is useful for running commands noninteractively which expect an interactive environment. The name is not part of the command, but is used to refer to this command in
later calls to zpty.
With the e option, the pseudoterminal is set up so that input characters are echoed.
With the b option, input to and output from the pseudoterminal are made nonblocking.
zpty d [ names ... ]
The second form, with the d option, is used to delete commands previously started, by supplying
a list of their names. If no names are given, all commands are deleted. Deleting a command
causes the HUP signal to be sent to the corresponding process.
zpty w [ n ] name [ strings ... ]
The w option can be used to send the to command name the given strings as input (separated by
spaces). If the n option is not given, a newline is added at the end.

zsh 4.0.4

Last change: October 26, 2001

20

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

If no strings are provided, the standard input is copied to the pseudoterminal; this may stop
before copying the full input if the pseudoterminal is nonblocking.
Note that the command under the pseudoterminal sees this input as if it were typed, so beware
when sending special tty driver characters such as worderase, linekill, and endoffile.
zpty r [ t ] name [ param [ pattern ] ]
The r option can be used to read the output of the command name. With only a name argument,
the output read is copied to the standard output. Unless the pseudoterminal is nonblocking,
copying continues until the command under the pseudoterminal exits; when nonblocking, only
as much output as is immediately available is copied. The return value is zero if any output is
copied.
When also given a param argument, at most one line is read and stored in the parameter named
param. Less than a full line may be read if the pseudoterminal is nonblocking. The return
value is zero if at least one character is stored in param.
If a pattern is given as well, output is read until the whole string read matches the pattern, even in
the nonblocking case. The return value is zero if the string read matches the pattern, or if the
command has exited but at least one character could still be read. As of this writing, a maximum
of one megabyte of output can be consumed this way; if a full megabyte is read without matching
the pattern, the return value is nonzero.
In all cases, the return value is nonzero if nothing could be read, and is 2 if this is because the
command has finished.
If the r option is combined with the t option, zpty tests whether output is available before trying
to read. If no output is available, zpty immediately returns the value 1.
zpty t name
The t option without the r option can be used to test whether the command name is still running. It returns a zero value if the command is running and a nonzero value otherwise.
zpty [ L ]
The last form, without any arguments, is used to list the commands currently defined. If the L
option is given, this is done in the form of calls to the zpty builtin.
THE ZSH/ZUTIL MODULE

The zsh/zutil module only adds some builtins:


zstyle [ L ]
zstyle [ e ] pattern style strings ...
zstyle d [ pattern [ styles ... ] ]
zstyle g name [ pattern [ style ] ]
zstyle abs context style name [ sep ]
zstyle Tt context style [ strings ...]
zstyle m context style pattern
This builtin command is used to define and lookup styles. Styles are pairs of names and values,
where the values consist of any number of strings. They are stored together with patterns and
lookup is done by giving a string, called the context, which is compared to the patterns. The
definition stored for the first matching pattern will be returned.
For ordering of comparisons, patterns are searched from most specific to least specific, and patterns that are equally specific keep the order in which they were defined. A pattern is considered
to be more specific than another if it contains more components (substrings separated by colons) or
if the patterns for the components are more specific, where simple strings are considered to be
more specific than patterns and complex patterns are considered to be more specific than the pattern .

zsh 4.0.4

Last change: October 26, 2001

21

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHMODULES ( 1 )

The first form (without arguments) lists the definitions in the order zstyle will test them. If the L
option is given, listing is done in the form of calls to zstyle. Forms with arguments:
zstyle [ e ] pattern style strings ...
Defines the given style for the pattern with the strings as the value. If the e option is
given, the strings will be concatenated (separated by spaces) and the resulting string will
be evaluated (in the same way as it is done by the eval builtin command) when the style
is looked up. In this case the parameter reply must be assigned to set the strings
returned after the evaluation. Before evaluating the value, reply is unset, and if it is still
unset after the evaluation, the style is treated as if it were not set.
zstyle d [ pattern [ styles ... ] ]
Delete style definitions. Without arguments all definitions are deleted, with a pattern all
definitions for that pattern are deleted and if any styles are given, then only those styles
are deleted for the pattern.
zstyle g name [ pattern [ style ] ]
Retrieve a style definition. The name is used as the name of an array in which the results
are stored. Without any further arguments, all patterns defined are returned. With a pattern the styles defined for that pattern are returned and with both a pattern and a style, the
value strings of that combination is returned.
The other forms can be used to look up or test patterns.
zstyle s context style name [ sep ]
The parameter name is set to the value of the style interpreted as a string. If the value
contains several strings they are concatenated with spaces (or with the sep string if that is
given) between them.
zstyle b context style name
The value is stored in name as a boolean, i.e. as the string yes if the value has only one
string and that string is equal to one of yes, true, on, or 1. If the value is any other
string or has more than one string, the parameter is set to no.
zstyle a context style name
The value is stored in name as an array. If name is declared as an associative array, the
first, third, etc. strings are used as the keys and the other strings are used as the values.
zstyle t context style [ strings ...]
zstyle T context style [ strings ...]
Test the value of a style, i.e. the t option only returns a status (sets $?). Without any
strings the return status is zero if the style is defined for at least one matching pattern, has
only one string in its value, and that is equal to one of true, yes, on or 1. If any
strings are given the status is zero if and only if at least one of the strings is equal to at
least one of the strings in the value. If the style is not defined, the status is 2.
The T option tests the values of the style like t, but it returns zero (rather than 2) if the
style is not defined for any matching pattern.
zstyle m context style pattern
Match a value. Returns status zero if the pattern matches at least one of the strings in the
value.
zformat f param format specs ...
zformat a array sep specs ...
This builtin provides two different forms of formatting. The first form is selected with the f
option. In this case the format string will be modified by replacing sequences starting with a percent sign in it with strings from the specs. Each spec should be of the form char:string which
will cause every appearance of the sequence %char in format to be replaced by the string. The
% sequence may also contain optional minimum and maximum field width specifications

zsh 4.0.4

Last change: October 26, 2001

22

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHMODULES ( 1 )

between the % and the char in the form %min.maxc, i.e. the minimum field width is given
first and if the maximum field width is used, it has to be preceded by a dot. Specifying a minimum
field width makes the result be padded with spaces to the right if the string is shorter than the
requested width. Padding to the left can be achieved by giving a negative minimum field width. If
a maximum field width is specified, the string will be truncated after that many characters. After
all % sequences for the given specs have been processed, the resulting string is stored in the
parameter param.
The second form, using the a option, can be used for aligning strings. Here, the specs are of the
form left:right where left and right are arbitrary strings. These strings are modified by replacing the colons by the sep string and padding the left strings with spaces to the right so that the sep
strings in the result (and hence the right strings after them) are all aligned if the strings are printed
below each other. All strings without a colon are left unchanged and all strings with an empty
right string have the trailing colon removed. In both cases the lengths of the strings are not used to
determine how the other strings are to be aligned. The resulting strings are stored in the array.
zregexparse
This implements some internals of the _regex_arguments function.
zparseopts [ D ] [ K ] [ E ] [ a array ] [ A assoc ] specs
This builtin simplifies the parsing of options in positional parameters, i.e. the set of arguments
given by $. Each spec describes one option and must be of the form opt[=array]. If an option
described by opt is found in the positional parameters it is copied into the array specified with the
a option; if the optional =array is given, it is instead copied into that array.
Note that it is an error to give any spec without an =array unless one of the a or A options is
used.
Unless the E option is given, parsing stops at the first string that isnt described by one of the
specs. Even with E, parsing always stops at a positional parameter equal to or .
The opt description must be one of the following. Any of the special characters can appear in the
option name provided it is preceded by a backslash.
name
name+ The name is the name of the option without the leading . To specify a GNUstyle
long option, one of the usual two leading must be included in name; for example, a
file option is represented by a name of file.
If a + appears after name, the option is appended to array each time it is found in the
positional parameters; without the + only the last occurrence of the option is preserved.
If one of these forms is used, the option takes no argument, so parsing stops if the next
positional parameter does not also begin with (unless the E option is used).
name:
name:
name:: If one or two colons are given, the option takes an argument; with one colon, the argument is mandatory and with two colons it is optional. The argument is appended to the
array after the option itself.
An optional argument is put into the same array element as the option name (note that
this makes empty strings as arguments indistinguishable). A mandatory argument is
added as a separate element unless the : form is used, in which case the argument is
put into the same element.
A + as described above may appear between the name and the first colon.
The options of zparseopts itself are:

zsh 4.0.4

Last change: October 26, 2001

23

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHMODULES ( 1 )

a array
As described above, this names the default array in which to store the recognised options.
A assoc
If this is given, the options and their values are also put into an associative array with the option
names as keys and the arguments (if any) as the values.
D

If this option is given, all options found are removed from the positional parameters of the calling
shell or shell function, up to but not including any not described by the specs. This is similar to
using the shift builtin.

With this option, the arrays specified with the a and A options and with the =array forms are
kept unchanged when none of the specs for them is used. This allows assignment of default values
to them before calling zparseopts.

This changes the parsing rules to not stop at the first string that isnt described by one of the specs.
It can be used to test for or (if used together with D) extract options and their arguments, ignoring
all other options and arguments that may be in the positional parameters.

For example,
set a bx c y cz baz cend
zparseopts a=foo b:=bar c+:=bar
will have the effect of
foo=(a)
bar=(b x c y c z)
The arguments from baz on will not be used.
As an example for the E option, consider:
set a x b y c z arg1 arg2
zparseopts E D b:=bar
will have the effect of
bar=(b y)
set a x c z arg1 arg2
I.e., the option b and its arguments are taken from the positional parameters and put into the array bar.

zsh 4.0.4

Last change: October 26, 2001

24

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZFTPSYS ( 1 )

NAME

zshzftpsys zftp function frontend


DESCRIPTION

This describes the set of shell functions supplied with the source distribution as an interface to the zftp builtin command, allowing you to perform FTP operations from the shell command line or within functions or
scripts. The interface is similar to a traditional FTP client (e.g. the ftp command itself, see ftp(1)), but as it
is entirely done within the shell all the familiar completion, editing and globbing features, and so on, are
present, and macros are particularly simple to write as they are just ordinary shell functions.
The prerequisite is that the zftp command, as described in zshmodules(1) , must be available in the version
of zsh installed at your site. If the shell is configured to load new commands at run time, it probably is:
typing zmodload zsh/zftp will make sure (if that runs silently, it has worked). If this is not the case, it is
possible zftp was linked into the shell anyway: to test this, type which zftp and if zftp is available you
will get the message zftp: shell builtin command.
Commands given directly with zftp builtin may be interspersed between the functions in this suite; in a few
cases, using zftp directly may cause some of the status information stored in shell parameters to become
invalid. Note in particular the description of the variables $ZFTP_TMOUT, $ZFTP_PREFS and
$ZFTP_VERBOSE for zftp.
INSTALLATION

You should make sure all the functions from the Functions/Zftp directory of the source distribution are
available; they all begin with the two letters zf. They may already have been installed on your system;
otherwise, you will need to find them and copy them. The directory should appear as one of the elements
of the $fpath array (this should already be the case if they were installed), and at least the function zfinit
should be autoloaded; it will autoload the rest. Finally, to initialize the use of the system you need to call
the zfinit function. The following code in your .zshrc will arrange for this; assume the functions are stored
in the directory /myfns:
fpath=(/myfns $fpath)
autoload U zfinit
zfinit
Note that zfinit assumes you are using the zmodload method to load the zftp command. If it is already
built into the shell, change zfinit to zfinit n. It is helpful (though not essential) if the call to zfinit appears
after any code to initialize the new completion system, else unnecessary compctl commands will be given.
FUNCTIONS

The sequence of operations in performing a file transfer is essentially the same as that in a standard FTP
client. Note that, due to a quirk of the shells getopts builtin, for those functions that handle options you
must use rather than to ensure the remaining arguments are treated literally (a single is treated
as an argument).
Opening a connection

zfparams [ host [ user [ password ... ] ] ]


Set or show the parameters for a future zfopen with no arguments. If no arguments are given, the
current parameters are displayed (the password will be shown as a line of asterisks). If a host is
given, and either the user or password is not, they will be prompted for; also, any parameter given
as ? will be prompted for, and if the ? is followed by a string, that will be used as the prompt.
As zfopen calls zfparams to store the parameters, this usually need not be called directly.
A single argument will delete the stored parameters. This will also cause the memory of the
last directory (and so on) on the other host to be deleted.
zfopen [ 1 ] [ host [ user [ password [ account ] ] ] ]
If host is present, open a connection to that host under username user with password password
(and, on the rare occasions when it is necessary, account account). If a necessary parameter is
missing or given as ? it will be prompted for. If host is not present, use a previously stored set of

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZFTPSYS ( 1 )

parameters.
If the command was successful, and the terminal is compatible with xterm or is suncmd, a summary will appear in the title bar, giving the local host:directory and the remote host:directory;
this is handled by the function zftp_chpwd, described below.
Normally, the host, user and password are internally recorded for later reopening, either by a
zfopen with no arguments, or automatically (see below). With the option 1, no information is
stored. Also, if an open command with arguments failed, the parameters will not be retained (and
any previous parameters will also be deleted). A zfopen on its own, or a zfopen 1, never alters
the stored parameters.
Both zfopen and zfanon (but not zfparams) understand URLs of the form ftp://host/path... as
meaning to connect to the host, then change directory to path (which must be a directory, not a
file). The ftp:// can be omitted; the trailing / is enough to trigger recognition of the path. Note
prefixes other than ftp: are not recognized, and that all characters after the first slash beyond host
are significant in path.
zfanon [ 1 ] host
Open a connection host for anonymous FTP. The username used is anonymous. The password
(which will be reported the first time) is generated as user@host; this is then stored in the shell
parameter $EMAIL_ADDR which can alternatively be set manually to a suitable string.
Directory management

zfcd [ dir ]
zfcd
zfcd old new
Change the current directory on the remote server: this is implemented to have many of the
features of the shell builtin cd.
In the first form with dir present, change to the directory dir. The command zfcd .. is treated
specially, so is guaranteed to work on nonUNIX servers (note this is handled internally by zftp).
If dir is omitted, has the effect of zfcd .
The second form changes to the directory previously current.
The third form attempts to change the current directory by replacing the first occurrence of the
string old with the string new in the current directory.
Note that in this command, and indeed anywhere a remote filename is expected, the string which
on the local host corresponds to is converted back to a before being passed to the remote
machine. This is convenient because of the way expansion is performed on the command line
before zfcd receives a string. For example, suppose the command is zfcd /foo. The shell will
expand this to a full path such as zfcd /home/user2/pws/foo. At this stage, zfcd recognises the
initial path as corresponding to and will send the directory to the remote host as /foo, so that
the will be expanded by the server to the correct remote host directory. Other named directories of the form name are not treated in this fashion.
zfhere Change directory on the remote server to the one corresponding to the current local directory, with
special handling of as in zfcd. For example, if the current local directory is /foo/bar, then
zfhere performs the effect of zfcd /foo/bar.
zfdir [ rfd ] [ ] [ diroptions ] [ dir ]
Produce a long directory listing. The arguments diroptions and dir are passed directly to the
server and their effect is implementation dependent, but specifying a particular remote directory
dir is usually possible. The output is passed through a pager given by the environment variable
$PAGER or defaulting to more.
The directory is usually cached for reuse. In fact, two caches are maintained. One is for use
when there is no diroptions or dir, i.e. a full listing of the current remote directory; it is flushed
when the current remote directory changes. The other is kept for repeated use of zfdir with the

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZFTPSYS ( 1 )

same arguments; for example, repeated use of zfdir /pub/gnu will only require the directory to
be retrieved on the first call. Alternatively, this cache can be reviewed with the r option. As
relative directories will confuse zfdir, the f option can be used to force the cache to be flushed
before the directory is listed. The option d will delete both caches without showing a directory
listing; it will also delete the cache of file names in the current remote directory, if any.
zfls [ lsoptions ] [ dir ]
List files on the remote server. With no arguments, this will produce a simple list of file names for
the current remote directory. Any arguments are passed directly to the server. No pager and no
caching is used.
Status commands

zftype [ type ]
With no arguments, show the type of data to be transferred, usually ASCII or binary. With an
argument, change the type: the types A or ASCII for ASCII data and B or BINARY, I or
IMAGE for binary data are understood caseinsensitively.
zfstat [ v ]
Show the status of the current or last connection, as well as the status of some of zftps status variables. With the v option, a more verbose listing is produced by querying the server for its version
of events, too.
Retrieving files

The commands for retrieving files all take at least two options. G suppresses remote filename expansion
which would otherwise be performed (see below for a more detailed description of that). t attempts to set
the modification time of the local file to that of the remote file: this requires version 5 of perl, see the
description of the function zfrtime below for more information.
zfget [ Gtc ] file1 ...
Retrieve all the listed files file1 ... one at a time from the remote server. If a file contains a /, the
full name is passed to the remote server, but the file is stored locally under the name given by the
part after the final /. The option c (cat) forces all files to be sent as a single stream to standard
output; in this case the t option has no effect.
zfuget [ Gvst ] file1 ...
As zfget, but only retrieve files where the version on the remote server is newer (has a later
modification time), or where the local file does not exist. If the remote file is older but the files
have different sizes, or if the sizes are the same but the remote file is newer, the user will usually
be queried. With the option s, the command runs silently and will always retrieve the file in
either of those two cases. With the option v, the command prints more information about the
files while it is working out whether or not to transfer them.
zfcget [ Gt ] file1 ...
As zfget, but if any of the local files exists, and is shorter than the corresponding remote file, the
command assumes that it is the result of a partially completed transfer and attempts to transfer the
rest of the file. This is useful on a poor connection which keeps failing.
Note that this requires a commonly implemented, but nonstandard, version of the FTP protocol,
so is not guaranteed to work on all servers.
zfgcp [ Gt ] remotefile localfile
zfgcp [ Gt ] rfile1 ... ldir
This retrieves files from the remote server with arguments behaving similarly to the cp command.
In the first form, copy remotefile from the server to the local file localfile.
In the second form, copy all the remote files rfile1 ... into the local directory ldir retaining the same
basenames. This assumes UNIX directory semantics.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZFTPSYS ( 1 )

Sending files

zfput [ r ] file1 ...


Send all the file1 ... given separately to the remote server. If a filename contains a /, the full
filename is used locally to find the file, but only the basename is used for the remote file name.
With the option r, if any of the files are directories they are sent recursively with all their subdirectories, including files beginning with .. This requires that the remote machine understand
UNIX file semantics, since / is used as a directory separator.
zfuput [ vs ] file1 ...
As zfput, but only send files which are newer than their local equivalents, or if the remote file does
not exist. The logic is the same as for zfuget, but reversed between local and remote files.
zfcput file1 ...
As zfput, but if any remote file already exists and is shorter than the local equivalent, assume it is
the result of an incomplete transfer and send the rest of the file to append to the existing part. As
the FTP append command is part of the standard set, this is in principle more likely to work than
zfcget.
zfpcp localfile remotefile
zfpcp lfile1 ... rdir
This sends files to the remote server with arguments behaving similarly to the cp command.
With two arguments, copy localfile to the server as remotefile.
With more than two arguments, copy all the local files lfile1 ... into the existing remote directory
rdir retaining the same basenames. This assumes UNIX directory semantics.
A problem arises if you attempt to use zfpcp lfile1 rdir, i.e. the second form of copying but with
two arguments, as the command has no simple way of knowing if rdir corresponds to a directory
or a filename. It attempts to resolve this in various ways. First, if the rdir argument is . or .. or
ends in a slash, it is assumed to be a directory. Secondly, if the operation of copying to a remote
file in the first form failed, and the remote server sends back the expected failure code 553 and a
reply including the string Is a directory, then zfpcp will retry using the second form.
Closing the connection

zfclose Close the connection.


Session management

zfsession [ lvod ] [ sessname ]


Allows you to manage multiple FTP sessions at once. By default, connections take place in a session called default; by giving the command zfsession sessname you can change to a new or
existing session with a name of your choice. The new session remembers its own connection, as
well as associated shell parameters, and also the host/user parameters set by zfparams. Hence you
can have different sessions set up to connect to different hosts, each remembering the appropriate
host, user and password.
With no arguments, zfsession prints the name of the current session; with the option l it lists all
sessions which currently exist, and with the option v it gives a verbose list showing the host and
directory for each session, where the current session is marked with an asterisk. With o, it will
switch to the most recent previous session.
With d, the given session (or else the current one) is removed; everything to do with it is completely forgotten. If it was the only session, a new session called default is created and made
current. It is safest not to delete sessions while background commands using zftp are active.
zftransfer sess1:file1 sess2:file2
Transfer files between two sessions; no local copy is made. The file is read from the session sess1
as file1 and written to session sess1 as file file2; file1 and file2 may be relative to the current directories of the session. Either sess1 or sess2 may be omitted (though the colon should be retained if
there is a possibility of a colon appearing in the file name) and defaults to the current session; file2

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZFTPSYS ( 1 )

may be omitted or may end with a slash, in which case the basename of file1 will be added. The
sessions sess1 and sess2 must be distinct.
The operation is performed using pipes, so it is required that the connections still be valid in a subshell, which is not the case under some versions operating systems, presumably due to a system
bug.
Bookmarks

The two functions zfmark and zfgoto allow you to bookmark the present location (host, user and directory) of the current FTP connection for later use. The file to be used for storing and retrieving bookmarks is
given by the parameter $ZFTP_BMFILE; if not set when one of the two functions is called, it will be set
to the file .zfbkmarks in the directory where your zsh startup files live (usually ).
zfmark [ bookmark ]
If given an argument, mark the current host, user and directory under the name bookmark for later
use by zfgoto. If there is no connection open, use the values for the last connection immediately
before it was closed; it is an error if there is none. Any existing bookmark under the same name
will be silently replaced.
If not given an argument, list the existing bookmarks and the points to which they refer in the form
user@host:directory; this is the format in which they are stored, and the file may be edited
directly.
zfgoto [ n ] bookmark
Return to the location given by bookmark, as previously set by zfmark. If the location has user
ftp or anonymous, open the connection with zfanon, so that no password is required. If the
user and host parameters match those stored for the current session, if any, those will be used, and
again no password is required. Otherwise a password will be prompted for.
With the option n, the bookmark is taken to be a nickname stored by the ncftp program in its
bookmark file, which is assumed to be /.ncftp/bookmarks. The function works identically in
other ways. Note that there is no mechanism for adding or modifying ncftp bookmarks from the
zftp functions.
Other functions

Mostly, these functions will not be called directly (apart from zfinit), but are described here for completeness. You may wish to alter zftp_chpwd and zftp_progress, in particular.
zfinit [ n ]
As described above, this is used to initialize the zftp function system. The n option should be
used if the zftp command is already built into the shell.
zfautocheck [ dn ]
This function is called to implement automatic reopening behaviour, as described in more detail
below. The options must appear in the first argument; n prevents the command from changing to
the old directory, while d prevents it from setting the variable do_close, which it otherwise does
as a flag for automatically closing the connection after a transfer. The host and directory for the
last session are stored in the variable $zflastsession, but the internal host/user/password parameters must also be correctly set.
zfcd_match prefix suffix
This performs matching for completion of remote directory names. If the remote server is UNIX,
it will attempt to persuade the server to list the remote directory with subdirectories marked, which
usually works but is not guaranteed. On other hosts it simply calls zfget_match and hence completes all files, not just directories. On some systems, directories may not even look like
filenames.
zfget_match prefix suffix
This performs matching for completion of remote filenames. It caches files for the current directory (only) in the shell parameter $zftp_fcache. It is in the form to be called by the K option of

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZFTPSYS ( 1 )

compctl, but also works when called from a widgetstyle completion function with prefix and
suffix set appropriately.
zfrglob varname
Perform remote globbing, as describes in more detail below. varname is the name of a variable
containing the pattern to be expanded; if there were any matches, the same variable will be set to
the expanded set of filenames on return.
zfrtime lfile rfile [ time ]
Set the local file lfile to have the same modification time as the remote file rfile, or the explicit time
time in FTP format CCYYMMDDhhmmSS for the GMT timezone.
Currently this requires perl version 5 to perform the conversion from GMT to local time. This is
unfortunately difficult to do using shell code alone.
zftp_chpwd
This function is called every time a connection is opened, or closed, or the remote directory
changes. This version alters the title bar of an xtermcompatible or suncmd terminal emulator
to reflect the local and remote hostnames and current directories. It works best when combined
with the function chpwd. In particular, a function of the form
chpwd() {
if [[ n $ZFTP_USER ]]; then
zftp_chpwd
else
# usual chpwd e.g put host:directory in title bar
fi
}
fits in well.
zftp_progress
This function shows the status of the transfer. It will not write anything unless the output is going
to a terminal; however, if you transfer files in the background, you should turn off progress reports
by hand using zstyle :zftp: progress none. Note also that if you alter it, any output must be
to standard error, as standard output may be a file being received. The form of the progress meter,
or whether it is used at all, can be configured without altering the function, as described in the next
section.
zffcache
This is used to implement caching of files in the current directory for each session separately. It is
used by zfget_match and zfrglob.
MISCELLANEOUS FEATURES
Configuration

Various styles are available using the standard shell style mechanism, described in zshmodules(1). Briefly,
the command zstyle :zftp: style value .... defines the style to have value value (more than one may be
given, although that is not useful in the cases described here). These values will then be used throughout
the zftp function system. For more precise control, the first argument, which gives a context in which the
style applies, can be modified to include a particular function, as for example :zftp:zfget: the style will
then have the given value only in the zfget function. Values for the same style in different contexts may be
set; the most specific function will be used, where strings are held to be more specific than patterns, and
longer patterns and shorter patterns. Note that only the top level function name, as called by the user, is
used; calling of lower level functions is transparent to the user. Hence modifications to the title bar in
zftp_chpwd use the contexts :zftp:zfopen, :zftp:zfcd, etc., depending where it was called from. The following styles are understood:
progress
Controls the way that zftp_progress reports on the progress of a transfer. If empty, unset, or

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHZFTPSYS ( 1 )

none, no progress report is made; if bar a growing bar of inverse video is shown; if percent
(or any other string, though this may change in future), the percentage of the file transferred is
shown. The bar meter requires that the width of the terminal be available via the $COLUMNS
parameter (normally this is set automatically). If the size of the file being transferred is not available, bar and percent meters will simply show the number of bytes transferred so far.
When zfinit is run, if this style is not defined for the context :zftp:, it will be set to bar.
update Specifies the minimum time interval between updates of the progress meter in seconds. No update
is made unless new data has been received, so the actual time interval is limited only by
$ZFTP_TIMEOUT.
As described for progress, zfinit will force this to default to 1.
remoteglob
If set to 1, yes or true, filename generation (globbing) is performed on the remote machine
instead of by zsh itself; see below.
titlebar If set to 1, yes or true, zftp_chpwd will put the remote host and remote directory into the
titlebar of terminal emulators such as xterm or suncmd that allow this.
As described for progress, zfinit will force this to default to 1.
chpwd If set to 1 yes or true, zftp_chpwd will call the function chpwd when a connection is closed.
This is useful if the remote host details were put into the terminal title bar by zftp_chpwd and
your usual chpwd also modifies the title bar.
When zfinit is run, it will determine whether chpwd exists and if so it will set the default value for
the style to 1 if none exists already.
Note that there is also an associative array zfconfig which contains values used by the function system.
This should not be modified or overwritten.
Remote globbing

The commands for retrieving files usually perform filename generation (globbing) on their arguments; this
can be turned off by passing the option G to each of the commands. Normally this operates by retrieving a
complete list of files for the directory in question, then matching these locally against the pattern supplied.
This has the advantage that the full range of zsh patterns (respecting the setting of the option
EXTENDED_GLOB) can be used. However, it means that the directory part of a filename will not be
expanded and must be given exactly. If the remote server does not support the UNIX directory semantics,
directory handling is problematic and it is recommended that globbing only be used within the current
directory. The list of files in the current directory, if retrieved, will be cached, so that subsequent globs in
the same directory without an intervening zfcd are much faster.
If the remoteglob style (see above) is set, globbing is instead performed on the remote host: the server is
asked for a list of matching files. This is highly dependent on how the server is implemented, though typically UNIX servers will provide support for basic glob patterns. This may in some cases be faster, as it
avoids retrieving the entire list of directory contents.
Automatic and temporary reopening

As described for the zfopen command, a subsequent zfopen with no parameters will reopen the connection
to the last host (this includes connections made with the zfanon command). Opened in this fashion, the
connection starts in the default remote directory and will remain open until explicitly closed.
Automatic reopening is also available. If a connection is not currently open and a command requiring a
connection is given, the last connection is implicitly reopened. In this case the directory which was current
when the connection was closed again becomes the current directory (unless, of course, the command given
changes it). Automatic reopening will also take place if the connection was close by the remote server for
whatever reason (e.g. a timeout). It is not available if the 1 option to zfopen or zfanon was used.

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHZFTPSYS ( 1 )

Furthermore, if the command issued is a file transfer, the connection will be closed after the transfer is
finished, hence providing a oneshot mode for transfers. This does not apply to directory changing or listing commands; for example a zfdir may reopen a connection but will leave it open. Also, automatic closure will only ever happen in the same command as automatic opening, i.e a zfdir directly followed by a
zfget will never close the connection automatically.
Information about the previous connection is given by the zfstat function. So, for example, if that reports:
Session:
default
Not connected.
Last session: ftp.bar.com:/pub/textfiles
then the command zfget file.txt will attempt to reopen a connection to ftp.bar.com, retrieve the file
/pub/textfiles/file.txt, and immediately close the connection again. On the other hand, zfcd .. will open the
connection in the directory /pub and leave it open.
Note that all the above is local to each session; if you return to a previous session, the connection for that
session is the one which will be reopened.
Completion

Completion of local and remote files, directories, sessions and bookmarks is supported. The older,
compctlstyle completion is defined when zfinit is called; support for the new widgetbased completion
system is provided in the function Completion/Zsh/Command/_zftp, which should be installed with the
other functions of the completion system and hence should automatically be available.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCONTRIB ( 1 )

NAME

zshcontrib user contributions to zsh


DESCRIPTION

The Zsh source distribution includes a number of items contributed by the user community. These are not
inherently a part of the shell, and some may not be available in every zsh installation. The most significant
of these are documented here. For documentation on other contributed items such as shell functions, look
for comments in the function source files.
UTILITIES
Accessing OnLine Help

The key sequence ESC h is normally bound by ZLE to execute the runhelp widget (see zshzle(1)). This
invokes the runhelp command with the command word from the current input line as its argument. By
default, runhelp is an alias for the man command, so this often fails when the command word is a shell
builtin or a userdefined function. By redefining the runhelp alias, one can improve the online help provided by the shell.
The helpfiles utility, found in the Util directory of the distribution, is a Perl program that can be used to
process the zsh manual to produce a separate help file for each shell builtin and for many other shell
features as well. The autoloadable runhelp function, found in Functions/Misc, searches for these
helpfiles and performs several other tests to produce the most complete help possible for the command.
There may already be a directory of help files on your system; look in /usr/share/zsh or
/usr/local/share/zsh and subdirectories below those, or ask your system administrator.
To create your own help files with helpfiles, choose or create a directory where the individual command
help files will reside. For example, you might choose /zsh_help. If you unpacked the zsh distribution in
your home directory, you would use the commands:
mkdir /zsh_help
cd /zsh_help
man zshall colcrt \
perl /zsh4.0.4/Util/helpfiles
Next, to use the runhelp function, you need to add lines something like the following to your .zshrc or
equivalent startup file:
unalias runhelp
autoload runhelp
HELPDIR=/zsh_help
The HELPDIR parameter tells runhelp where to look for the help files. If your system already has a help
file directory installed, set HELPDIR to the path of that directory instead.
Note that in order for autoload runhelp to work, the runhelp file must be in one of the directories
named in your fpath array (see zshparam(1)). This should already be the case if you have a standard zsh
installation; if it is not, copy Functions/Misc/runhelp to an appropriate directory.
Recompiling Functions

If you frequently edit your zsh functions, or periodically update your zsh installation to track the latest
developments, you may find that function digests compiled with the zcompile builtin are frequently out of
date with respect to the function source files. This is not usually a problem, because zsh always looks for
the newest file when loading a function, but it may cause slower shell startup and function loading. Also, if
a digest file is explicitly used as an element of fpath, zsh wont check whether any of its source files has
changed.
The zrecompile autoloadable function, found in Functions/Misc, can be used to keep function digests up
to date.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCONTRIB ( 1 )

zrecompile [ qt ] [ name ... ]


zrecompile [ qt ] p args [ args ... ]
This tries to find .zwc files and automatically recompile them if at least one of the original files
is newer than the compiled file. This works only if the names stored in the compiled files are full
paths or are relative to the directory that contains the .zwc file.
In the first form, each name is the name of a compiled file or a directory containing .zwc files that
should be checked. If no arguments are given, the directories and .zwc files in fpath are used.
When t is given, no compilation is performed, but a return status of zero (true) is set if there are
files that need to be recompiled and nonzero (false) otherwise. The q option quiets the chatty
output that describes what zrecompile is doing.
Without the t option, the return status is zero if all files that needed recompilation could be compiled and nonzero if compilation for at least one of the files failed.
If the p option is given, the args are interpreted as one or more sets of arguments for zcompile,
separated by . For example:
zrecompile p \
R /.zshrc \
M /.zcompdump \
/zsh/comp.zwc /zsh/Completion//_
This compiles /.zshrc into /.zshrc.zwc if that doesnt exist or if it is older than /.zshrc. The
compiled file will be marked for reading instead of mapping. The same is done for /.zcompdump
and /.zcompdump.zwc, but this compiled file is marked for mapping. The last line recreates the
file /zsh/comp.zwc if any of the files matching the given pattern is newer than it.
Without the p option, zrecompile does not create function digests that do not already exist, nor
does it add new functions to the digest.
The following shell loop is an example of a method for creating function digests for all functions in your
fpath, assuming that you have write permission to the directories:
for ((i=1; i <= $#fpath; ++i)); do
dir=$fpath[i]
zwc=${dir:t}.zwc
if [[ $dir == (...) $dir == (...)/ ]]; then
continue
fi
files=($dir/(N.))
if [[ w $dir:h && n $files ]]; then
files=(${${(M)files%//}#/})
if ( cd $dir:h &&
zrecompile p U z $zwc $files ); then
fpath[i]=$fpath[i].zwc
fi
fi
done
The U and z options are appropriate for functions in the default zsh installation fpath; you may need to
use different options for your personal function directories.
Once the digests have been created and your fpath modified to refer to them, you can keep them up to date
by running zrecompile with no arguments.
Keyboard Definition

The large number of possible combinations of keyboards, workstations, terminals, emulators, and window
systems makes it impossible for zsh to have builtin key bindings for every situation. The zkbd utility,
found in Functions/Misc, can help you quickly create key bindings for your configuration.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCONTRIB ( 1 )

Run zkbd either as an autoloaded function, or as a shell script:


zsh f /zsh4.0.4/Functions/Misc/zkbd
When you run zkbd, it first asks you to enter your terminal type; if the default it offers is correct, just press
return. It then asks you to press a number of different keys to determine characteristics of your keyboard
and terminal; zkbd warns you if it finds anything out of the ordinary, such as a Delete key that sends neither H nor ?.
The keystrokes read by zkbd are recorded as a definition for an associative array named key, written to a
file in the subdirectory .zkbd within either your HOME or ZDOTDIR directory. The name of the file is
composed from the TERM, VENDOR and OSTYPE parameters, joined by hyphens.
You may read this file into your .zshrc or another startup file with the "source" or "." commands, then reference the key parameter in bindkey commands, like this:
source ${ZDOTDIR:$HOME}/.zkbd/$TERM$VENDOR$OSTYPE
[[ n ${key[Left]} ]] && bindkey " ${key[Left]}" backwardchar
[[ n ${key[Right]} ]] && bindkey " ${key[Right]}" forwardchar
# etc.
Note that in order for autoload zkbd to work, the zkdb file must be in one of the directories named in
your fpath array (see zshparam(1)). This should already be the case if you have a standard zsh installation;
if it is not, copy Functions/Misc/zkbd to an appropriate directory.
Dumping Shell State

Occasionally you may encounter what appears to be a bug in the shell, particularly if you are using a beta
version of zsh or a development release. Usually it is sufficient to send a description of the problem to one
of the zsh mailing lists (see zsh(1)), but sometimes one of the zsh developers will need to recreate your
environment in order to track the problem down.
The script named reporter, found in the Util directory of the distribution, is provided for this purpose. (It
is also possible to autoload reporter, but reporter is not installed in fpath by default.) This script outputs
a detailed dump of the shell state, in the form of another script that can be read with zsh f to recreate that
state.
To use reporter, read the script into your shell with the . command and redirect the output into a file:
. /zsh4.0.4/Util/reporter > zsh.report
You should check the zsh.report file for any sensitive information such as passwords and delete them by
hand before sending the script to the developers. Also, as the output can be voluminous, its best to wait for
the developers to ask for this information before sending it.
You can also use reporter to dump only a subset of the shell state. This is sometimes useful for creating
startup files for the first time. Most of the output from reporter is far more detailed than usually is necessary for a startup file, but the aliases, options, and zstyles states may be useful because they include only
changes from the defaults. The bindings state may be useful if you have created any of your own keymaps,
because reporter arranges to dump the keymap creation commands as well as the bindings for every keymap.
As is usual with automated tools, if you create a startup file with reporter, you should edit the results to
remove unnecessary commands. Note that if youre using the new completion system, you should not
dump the functions state to your startup files with reporter; use the compdump function instead (see
zshcompsys(1)).
reporter [ state ... ]
Print to standard output the indicated subset of the current shell state. The state arguments may be
one or more of:
all
Output everything listed below.
aliases Output alias definitions.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCONTRIB ( 1 )

bindings
Output ZLE key maps and bindings.
completion
Output oldstyle compctl commands. New completion is covered by functions and
zstyles.
functions
Output autoloads and function definitions.
limits Output limit commands.
options Output setopt commands.
styles Same as zstyles.
variables
Output shell parameter assignments, plus export commands for any environment variables.
zstyles Output zstyle commands.
If the state is omitted, all is assumed.
With the exception of all, every state can be abbreviated by any prefix, even a single letter; thus a is the
same as aliases, z is the same as zstyles, etc.
PROMPT THEMES
Installation

You should make sure all the functions from the Functions/Prompts directory of the source distribution
are available; they all begin with the string prompt_ except for the special functionpromptinit. You
also need the colors function from Functions/Misc. All of these functions may already have been
installed on your system; if not, you will need to find them and copy them. The directory should appear as
one of the elements of the fpath array (this should already be the case if they were installed), and at least
the function promptinit should be autoloaded; it will autoload the rest. Finally, to initialize the use of the
system you need to call the promptinit function. The following code in your .zshrc will arrange for this;
assume the functions are stored in the directory /myfns:
fpath=(/myfns $fpath)
autoload U promptinit
promptinit
Theme Selection

Use the prompt command to select your preferred theme. This command may be added to your .zshrc following the call to promptinit in order to start zsh with a theme already selected.
prompt [ c l ]
prompt [ p h ] [ theme ... ]
prompt [ s ] theme [ arg ... ]
Set or examine the prompt theme. With no options and a theme argument, the theme with that
name is set as the current theme. The available themes are determined at run time; use the l
option to see a list. The special theme random selects at random one of the available themes and
sets your prompt to that.
In some cases the theme may be modified by one or more arguments, which should be given after
the theme name. See the help for each theme for descriptions of these arguments.
Options are:
c
l
p
h
s

zsh 4.0.4

Show the currently selected theme and its parameters, if any.


List all available prompt themes.
Preview the theme named by theme, or all themes if no theme is given.
Show help for the theme named by theme, or for the prompt function if no theme is
given.
Set theme as the current theme and save state.

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCONTRIB ( 1 )

prompt_theme_setup
Each available theme has a setup function which is called by the prompt function to install that
theme. This function may define other functions as necessary to maintain the prompt, including
functions used to preview the prompt or provide help for its use. You should not normally call a
themes setup function directly.
ZLE FUNCTIONS
Widgets

These functions all implement userdefined ZLE widgets (see zshzle(1)) which can be bound to keystrokes
in interactive shells. To use them, your .zshrc should contain lines of the form
autoload function
zle N function
followed by an appropriate bindkey command to associate the function with a key sequence. Suggested
bindings are described below.
cyclecompletionpositions
After inserting an unambiguous string into the command line, the new function based completion
system may know about multiple places in this string where characters are missing or differ from
at least one of the possible matches. It will then place the cursor on the position it considers to be
the most interesting one, i.e. the one where one can disambiguate between as many matches as
possible with as little typing as possible.
This widget allows the cursor to be easily moved to the other interesting spots. It can be invoked
repeatedly to cycle between all positions reported by the completion system.
editcommandline
Edit the command line using your visual editor, as in ksh.
bindkey M vicmd v editcommandline
historysearchend
This function implements the widgets historybeginningsearchbackwardend and
historybeginningsearchforwardend. These commands work by first calling the corresponding builtin widget (see History Control in zshzle(1)) and then moving the cursor to the end of the
line. The original cursor position is remembered and restored before calling the builtin widget a
second time, so that the same search is repeated to look farther through the history.
Although you autoload only one function, the commands to use it are slightly different because it
implements two widgets.
zle N historybeginningsearchbackwardend \
historysearchend
zle N historybeginningsearchforwardend \
historysearchend
bindkey \eP historybeginningsearchbackwardend
bindkey \eN historybeginningsearchforwardend
incarg Typing the keystrokes for this widget with the cursor placed on or to the left of an integer causes
that integer to be incremented by one. With a numeric prefix argument, the number is incremented
by the amount of the argument (decremented if the prefix argument is negative). The shell parameter incarg may be set to change the default increment something other than one.
bindkey X+ incarg
incrementalcompleteword
This allows incremental completion of a word. After starting this command, a list of completion
choices can be shown after every character you type, which you can delete with H or DEL.
Pressing return accepts the completion so far and returns you to normal editing (that is, the command line is not immediately executed). You can hit TAB to do normal completion, G to abort

zsh 4.0.4

Last change: October 26, 2001

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCONTRIB ( 1 )

back to the state when you started, and D to list the matches.
This works only with the new function based completion system.
bindkey Xi incrementalcompleteword
insertfiles
This function allows you type a file pattern, and see the results of the expansion at each step.
When you hit return, all expansions are inserted into the command line.
bindkey Xf insertfiles
predicton
This set of functions implements predictive typing using history search. After predicton, typing
characters causes the editor to look backward in the history for the first line beginning with what
you have typed so far. After predictoff, editing returns to normal for the line found. In fact, you
often dont even need to use predictoff, because if the line doesnt match something in the history, adding a key performs standard completion, and then inserts itself if no completions were
found. However, editing in the middle of a line is liable to confuse prediction; see the toggle style
below.
With the function based completion system (which is needed for this), you should be able to type
TAB at almost any point to advance the cursor to the next interesting character position (usually the end of the current word, but sometimes somewhere in the middle of the word). And of
course as soon as the entire line is what you want, you can accept with return, without needing to
move the cursor to the end first.
The first time predicton is used, it creates several additional widget functions:
deletebackwardandpredict
Replaces the backwarddeletechar widget. You do not need to bind this yourself.
insertandpredict
Implements predictive typing by replacing the selfinsert widget. You do not need to
bind this yourself.
predictoff
Turns off predictive typing.
Although you autoload only the predicton function, it is necessary to create a keybinding for
predictoff as well.
zle N predicton
zle N predictoff
bindkey XZ predicton
bindkey Z predictoff
smartinsertlastword
This function may replace the insertlastword widget, like so:
zle N insertlastword smartinsertlastword
With a numeric prefix, it behaves like insertlastword, except that words in comments are
ignored when INTERACTIVE_COMMENTS is set.
Otherwise, the rightmost interesting word from the previous command is found and inserted.
The default definition of interesting is that the word contains at least one alphabetic character,
slash, or backslash. This definition may be overridden by use of the match style. The context
used to look up the style is the widget name, so usually the context is :insertlastword. However, you can bind this function to different widgets to use different patterns:
zle N insertlastassignment smartinsertlastword
zstyle :insertlastassignment match [[:alpha:]][][[:alnum:]]#=
bindkey \e= insertlastassignment

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCONTRIB ( 1 )

Styles

The behavior of several of the above widgets can be controlled by the use of the zstyle mechanism. In particular, widgets that interact with the completion system pass along their context to any completions that
they invoke.
breakkeys
This style is used by the incrementalcompleteword widget. Its value should be a pattern, and
all keys matching this pattern will cause the widget to stop incremental completion without the
key having any further effect. Like all styles used directly by incrementalcompleteword, this
style is looked up using the context :incremental.
completer
The incrementalcompleteword and insertandpredict widgets set up their toplevel context
name before calling completion. This allows one to define different sets of completer functions for
normal completion and for these widgets. For example, to use completion, approximation and
correction for normal completion, completion and correction for incremental completion and only
completion for prediction one could use:
zstyle :completion: completer \
_complete _correct _approximate
zstyle :completion:incremental: completer \
_complete _correct
zstyle :completion:predict: completer \
_complete
It is a good idea to restrict the completers used in prediction, because they may be automatically
invoked as you type. The _list and _menu completers should never be used with prediction. The
_approximate, _correct, _expand, and _match completers may be used, but be aware that they
may change characters anywhere in the word behind the cursor, so you need to watch carefully
that the result is what you intended.
cursor The insertandpredict widget uses this style, in the context :predict, to decide where to place
the cursor after completion has been tried. Values are:
complete
The cursor is left where it was when completion finished, but only if it is after a character
equal to the one just inserted by the user. If it is after another character, this value is the
same as key.
key

The cursor is left after the nth occurrence of the character just inserted, where n is the
number of times that character appeared in the word before completion was attempted. In
short, this has the effect of leaving the cursor after the character just typed even if the
completion code found out that no other characters need to be inserted at that position.

Any other value for this style unconditionally leaves the cursor at the position where the completion code left it.
list

When using the incrementalcompleteword widget, this style says if the matches should be
listed on every key press (if they fit on the screen). Use the context prefix
:completion:incremental.
The insertandpredict widget uses this style to decide if the completion should be shown even
if there is only one possible completion. This is done if the value of this style is the string always.
In this case the context is :predict (not :completion:predict).

match This style is used by smartinsertlastword to provide a pattern (using full


EXTENDED_GLOB syntax) that matches an interesting word. The context is the name of the
widget to which smartinsertlastword is bound (see above). The default behavior of
smartinsertlastword is equivalent to:

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCONTRIB ( 1 )

zstyle :insertlastword match [[:alpha:]/\\]


However, you might want to include words that contain spaces:
zstyle :insertlastword match [[:alpha:][:space:]/\\]
Or include numbers as long as the word is at least two characters long:
zstyle :insertlastword match ([[:digit:]]?[[:alpha:]/\\])
The above example causes redirections like "2>" to be included.
prompt The incrementalcompleteword widget shows the value of this style in the status line during
incremental completion. The string value may contain any of the following substrings in the
manner of the PS1 and other prompt parameters:
%c

Replaced by the name of the completer function that generated the matches (without the
leading underscore).

%l

When the list style is set, replaced by ... if the list of matches is too long to fit on the
screen and with an empty string otherwise. If the list style is false or not set, %l is
always removed.

%n

Replaced by the number of matches generated.

%s

Replaced by no match, no prefix, or an empty string if there is no completion


matching the word on the line, if the matches have no common prefix different from the
word on the line, or if there is such a common prefix, respectively.

%u

Replaced by the unambiguous part of all matches, if there is any, and if it is different
from the word on the line.

Like breakkeys, this uses the :incremental context.


stopkeys
This style is used by the incrementalcompleteword widget. Its value is treated similarly to the
one for the breakkeys style (and uses the same context: :incremental). However, in this case
all keys matching the pattern given as its value will stop incremental completion and will then execute their usual function.
toggle

This boolean style is used by predicton and its related widgets in the context :predict. If set to
one of the standard true values, predictive typing is automatically toggled off in situations where
it is unlikely to be useful, such as when editing a multiline buffer or after moving into the middle
of a line and then deleting a character. The default is to leave prediction turned on until an explicit
call to predictoff.

verbose This boolean style is used by predicton and its related widgets in the context :predict. If set to
one of the standard true values, these widgets display a message below the prompt when the
predictive state is toggled. This is most useful in combination with the toggle style. The default
does not display these messages.
OTHER FUNCTIONS

There are a large number of helpful functions in the Functions/Misc directory of the zsh distribution. Most
are very simple and do not require documentation here, but a few are worthy of special mention.
Descriptions

colors

This function initializes several associative arrays to map color names to (and from) the ANSI
standard eightcolor terminal codes. These are used by the prompt theme system (see above).
You seldom should need to run colors more than once.
The eight base colors are: black, red, green, yellow, blue, magenta, cyan, and white. Each of these
has codes for foreground and background. In addition there are eight intensity attributes: bold,
faint, standout, underline, blink, reverse, and conceal. Finally, there are six codes used to negate
attributes: none (reset all attributes to the defaults), normal (neither bold nor faint), nostandout,

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCONTRIB ( 1 )

nounderline, noblink, and noreverse.


Some terminals do not support all combinations of colors and intensities.
The associative arrays are:
color
colour

Map all the color names to their integer codes, and integer codes to the color names. The
eight base names map to the foreground color codes, as do names prefixed with fg,
such as fgred. Names prefixed with bg, such as bgblue, refer to the background
codes. The reverse mapping from code to color yields base name for foreground codes
and the bg form for backgrounds.
Although it is a misnomer to call them colors, these arrays also map the other fourteen
attributes from names to codes and codes to names.

fg
fg_bold
fg_no_bold
Map the eight basic color names to ANSI terminal escape sequences that set the
corresponding foreground text properties. The fg sequences change the color without
changing the eight intensity attributes.
bg
bg_bold
bg_no_bold
Map the eight basic color names to ANSI terminal escape sequences that set the
corresponding background properties. The bg sequences change the color without changing the eight intensity attributes.
In addition, the scalar parameters reset_color and bold_color are set to the ANSI terminal escapes
that turn off all attributes and turn on bold intensity, respectively.
fned name
Same as zed f. This function does not appear in the zsh distribution, but can be created by linking zed to the name fned in some directory in your fpath.
isatleast needed [ present ]
Perform a greaterthanorequalto comparison of two strings having the format of a zsh version
number; that is, a string of numbers and text with segments separated by dots or dashes. If the
present string is not provided, $ZSH_VERSION is used. Segments are paired lefttoright in the
two strings with leading nonnumber parts ignored. If one string has fewer segments than the
other, the missing segments are considered zero.
This is useful in startup files to set options and other state that are not available in all versions of
zsh.
isatleast 3.1.615 && setopt NO_GLOBAL_RCS
isatleast 3.1.0 && setopt HIST_REDUCE_BLANKS
isatleast 2.617 print " You cant use isatleast here."
nslookup [ arg ... ]
This wrapper function for the nslookup command requires the zsh/zpty module (see zshmodules(1)). It behaves exactly like the standard nslookup except that it provides customizable
prompts (including a rightside prompt) and completion of nslookup commands, host names, etc.
(if you use the functionbased completion system). Completion styles may be set with the context
prefix :completion:nslookup.
See also the pager, prompt and rprompt styles below.
runhelp
See Accessing OnLine Help above.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

User Commands

ZSHCONTRIB ( 1 )

zed [ f ] name
This function uses the ZLE editor to edit a file or function. It rebinds the return key to insert a line
break, and adds bindings for XW in the emacs keymap and ZZ in the vicmd keymap to
accept (and therefore write, in the case of a file) the edited file or function. Keybindings are otherwise the standard ones; completion is available, and styles may be set with the context prefix
:completion:zed.
Only one name argument is recognized (additional arguments are ignored). If the f option is
given, the name is taken to be that of a function; if the function is marked for autoloading, zed
searches for it in the fpath and loads it. Note that functions edited this way are installed into the
current shell, but not written back to the autoload file.
Without f, name is the path name of the file to edit, which need not exist; it is created on write, if
necessary.
zcp [ finqQvw ] srcpat dest
zln [ finqQsvw ] srcpat dest
Same as zmv C and zmv L, respectively. These functions do not appear in the zsh distribution,
but can be created by linking zmv to the names zcp and zln in some directory in your fpath.
zkbd

See Keyboard Definition above.

zmv [ finqQsvw ] [ C L M p program ] [ o optstring ] srcpat dest


Move (usually, rename) files matching the pattern srcpat to corresponding files having names of
the form given by dest, where srcpat contains parentheses surrounding patterns which will be
replaced in turn by $1, $2, ... in dest. For example,
zmv ().lis $1.txt
renames foo.lis to foo.txt, my.old.stuff.lis to my.old.stuff.txt, and so on.
The pattern is always treated as an EXTENDED_GLOB pattern. Any file whose name is not
changed by the substitution is simply ignored. Any error (a substitution resulted in an empty
string, two substitutions gave the same result, the destination was an existing regular file and f
was not given) causes the entire function to abort without doing anything.
Options:
f
i

n
q
Q
s
v
w

Force overwriting of destination files. Not currently passed down to the mv/cp/ln command due to vagaries of implementations (but you can use of to do that).
Interactive: show each line to be executed and ask the user whether to execute it. Y or
y will execute it, anything else will skip it. Note that you just need to type one character.
No execution: print what would happen, but dont do it.
Turn bare glob qualifiers off: now assumed by default, so this has no effect.
Force bare glob qualifiers on. Dont turn this on unless you are actually using glob
qualifiers in a pattern.
Symbolic, passed down to ln; only works with L.
Verbose: print each command as its being executed.
Pick out wildcard parts of the pattern, as described above, and implicitly add parentheses
for referring to them.

C
L
M
Force cp, ln or mv, respectively, regardless of the name of the function.
p program
Call program instead of cp, ln or mv. Whatever it does, it should at least understand the
form program oldname newname where oldname and newname are filenames generated by zmv.
o optstring

zsh 4.0.4

Last change: October 26, 2001

10

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCONTRIB ( 1 )

The optstring is split into words and passed down verbatim to the cp, ln or mv command
called to perform the work. It should probably begin with a .
For more complete examples and other implementation details, see the zmv source file, usually
located in one of the directories named in your fpath, or in Functions/Misc/zmv in the zsh distribution.
zrecompile
See Recompiling Functions above.
zstyle+ context style value [ + subcontext style value ... ]
This makes defining styles a bit simpler by using a single + as a special token that allows you to
append a context name to the previously used context name. Like this:
zstyle+ :foo:bar style1 value1 \
+ :baz style2 value2 \
+ :frob style3 value3
This defines style1 with value1 for the context :foo:bar as usual, but it also defines style2
with value2 for the context :foo:bar:baz and style3 with value3 for :foo:bar:frob. Any subcontext may be the empty string to reuse the first context unchanged.
Styles

inserttab
The zed function sets this style in context :completion:zed: to turn off completion when TAB
is typed at the beginning of a line. You may override this by setting your own value for this context and style.
pager

The nslookup function looks up this style in the context :nslookup to determine the program
used to display output that does not fit on a single screen.

prompt
rprompt
The nslookup function looks up this style in the context :nslookup to set the prompt and the
rightside prompt, respectively. The usual expansions for the PS1 and RPS1 parameters may be
used (see zshmisc(1)).

zsh 4.0.4

Last change: October 26, 2001

11

User Commands

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHALL ( 1 )

FILES

$ZDOTDIR/.zshenv
$ZDOTDIR/.zprofile
$ZDOTDIR/.zshrc
$ZDOTDIR/.zlogin
$ZDOTDIR/.zlogout
${TMPPREFIX} (default is /tmp/zsh)
/etc/zshenv
/etc/zprofile
/etc/zshrc
/etc/zlogin
/etc/zlogout (installationspecific /etc is the default)
SEE ALSO

sh(1), csh(1), tcsh(1), rc(1), bash(1), ksh(1)


IEEE Standard for information Technology Portable Operating System Interface (POSIX) Part
2: Shell and Utilities, IEEE Inc, 1993, ISBN 1559372559.

zsh 4.0.4

Last change: October 26, 2001

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHALL(1)

ZSHALL(1)

NAME
zshall the Z shell metaman page

OVERVIEW
Because zsh contains many features, the zsh manual has been split into a number of sections. This manual
page includes all the separate manual pages in the following order:
zshroadmap Informal introduction to the manual
zshmisc
Anything not fitting into the other sections
zshexpn
Zsh command and parameter expansion
zshparam Zsh parameters
zshoptions Zsh options
zshbuiltins Zsh builtin functions
zshzle
Zsh command line editing
zshcompwid Zsh completion widgets
zshcompsys Zsh completion system
zshcompctl Zsh completion control
zshmodules Zsh loadable modules
zshtcpsys Zsh builtin TCP functions
zshzftpsys Zsh builtin FTP client
zshcontrib Additional zsh functions and utilities

DESCRIPTION
Zsh is a UNIX command interpreter (shell) usable as an interactive login shell and as a shell script command processor. Of the standard shells, zsh most closely resembles ksh but includes many enhancements.
Zsh has command line editing, builtin spelling correction, programmable command completion, shell functions (with autoloading), a history mechanism, and a host of other features.

AUTHOR
Zsh was originally written by Paul Falstad <pf@zsh.org>. Zsh is now maintained by the members of the
zshworkers mailing list <zshworkers@sunsite.dk>. The development is currently coordinated by Peter
Stephenson <pws@zsh.org>. The coordinator can be contacted at <coordinator@zsh.org>, but matters
relating to the code should generally go to the mailing list.

AVAILABILITY
Zsh is available from the following anonymous FTP sites. These mirror sites are kept frequently up to date.
The sites marked with (H) may be mirroring ftp.cs.elte.hu instead of the primary site.
Primary site
ftp://ftp.zsh.org/pub/zsh/
http://www.zsh.org/pub/zsh/
Australia
ftp://ftp.zsh.org/pub/zsh/
http://www.zsh.org/pub/zsh/
Denmark
ftp://sunsite.dk/pub/unix/shells/zsh/
Finland
ftp://ftp.funet.fi/pub/unix/shells/zsh/
Germany
ftp://ftp.fuberlin.de/pub/unix/shells/zsh/ (H)
ftp://ftp.gmd.de/packages/zsh/
ftp://ftp.unitrier.de/pub/unix/shell/zsh/
Hungary
ftp://ftp.cs.elte.hu/pub/zsh/
http://www.cs.elte.hu/pub/zsh/
ftp://ftp.kfki.hu/pub/packages/zsh/

zsh 4.3.4

April 19, 2006

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHALL(1)

ZSHALL(1)

Israel
ftp://ftp.math.technion.ac.il/pub/zsh/
http://www.math.technion.ac.il/pub/zsh/
Japan
ftp://ftp.win.ne.jp/pub/shell/zsh/
Korea
ftp://linux.sarang.net/mirror/system/shell/zsh/
Netherlands
ftp://ftp.demon.nl/pub/mirrors/zsh/
Norway
ftp://ftp.uit.no/pub/unix/shells/zsh/
Poland
ftp://sunsite.icm.edu.pl/pub/unix/shells/zsh/
Romania
ftp://ftp.roedu.net/pub/mirrors/ftp.zsh.org/pub/zsh/
ftp://ftp.kappa.ro/pub/mirrors/ftp.zsh.org/pub/zsh/
Slovenia
ftp://ftp.siol.net/mirrors/zsh/
Sweden
ftp://ftp.lysator.liu.se/pub/unix/zsh/
UK
ftp://ftp.net.lut.ac.uk/zsh/
ftp://sunsite.org.uk/packages/zsh/
USA
http://zsh.openmirror.com/
The uptodate source code is available via anonymous CVS from Sourceforge. See http://sourceforge.net/projects/zsh/ for details.

MAILING LISTS
Zsh has 3 mailing lists:
<zshannounce@sunsite.dk>
Announcements about releases, major changes in the shell and the monthly posting of the Zsh
FAQ. (moderated)
<zshusers@sunsite.dk>
User discussions.
<zshworkers@sunsite.dk>
Hacking, development, bug reports and patches.
To subscribe or unsubscribe, send mail to the associated administrative address for the mailing list.
<zshannouncesubscribe@sunsite.dk>
<zshuserssubscribe@sunsite.dk>
<zshworkerssubscribe@sunsite.dk>
<zshannounceunsubscribe@sunsite.dk>
<zshusersunsubscribe@sunsite.dk>
<zshworkersunsubscribe@sunsite.dk>
YOU ONLY NEED TO JOIN ONE OF THE MAILING LISTS AS THEY ARE NESTED. All submissions to zshannounce are automatically forwarded to zshusers. All submissions to zshusers are automatically forwarded to zshworkers.

zsh 4.3.4

April 19, 2006

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHALL(1)

ZSHALL(1)

If you have problems subscribing/unsubscribing to any of the mailing lists, send mail to <listmaster@zsh.org>. The mailing lists are maintained by Karsten Thygesen <karthy@kom.auc.dk>.
The mailing lists are archived; the archives can be accessed via the administrative addresses listed above.
There is also a hypertext archive, maintained by Geoff Wing <gcw@zsh.org>, available at
http://www.zsh.org/mla/.

THE ZSH FAQ


Zsh has a list of Frequently Asked Questions (FAQ), maintained by Peter Stephenson <pws@zsh.org>. It
is regularly posted to the newsgroup comp.unix.shell and the zshannounce mailing list. The latest version can be found at any of the Zsh FTP sites, or at http://www.zsh.org/FAQ/. The contact address for
FAQrelated matters is <faqmaster@zsh.org>.

THE ZSH WEB PAGE


Zsh has a web page which is located at http://www.zsh.org/. This is maintained by Karsten Thygesen
<karthy@zsh.org>, of SunSITE Denmark. The contact address for webrelated matters is <webmaster@zsh.org>.

THE ZSH USERGUIDE


A userguide is currently in preparation. It is intended to complement the manual, with explanations and
hints on issues where the manual can be cabbalistic, hierographic, or downright mystifying (for example,
the word hierographic does not exist). It can be viewed in its current state at http://zsh.sunsite.dk/Guide/. At the time of writing, chapters dealing with startup files and their contents and the new
completion system were essentially complete.

THE ZSH WIKI


A wiki website for zsh has been created at http://www.zshwiki.org/. This is a site which can be added to
and modified directly by users without any special permission. You can add your own zsh tips and configurations.

INVOCATION OPTIONS
The following flags are interpreted by the shell when invoked to determine where the shell will read commands from:
c

Take the first argument as a command to execute, rather than reading commands from a script or
standard input. If any further arguments are given, the first one is assigned to $0, rather than being
used as a positional parameter.

Force shell to be interactive.

Force shell to read commands from the standard input. If the s flag is not present and an argument is given, the first argument is taken to be the pathname of a script to execute.

After the first one or two arguments have been appropriated as described above, the remaining arguments
are assigned to the positional parameters.
For further options, which are common to invocation and the set builtin, see zshoptions(1).
Options may be specified by name using the o option. o acts like a singleletter option, but takes a following string as the option name. For example,
zsh x o shwordsplit scr
runs the script scr, setting the XTRACE option by the corresponding letter x and the
SH_WORD_SPLIT option by name. Options may be turned off by name by using +o instead of o. o
can be stacked up with preceding singleletter options, so for example xo shwordsplit or xoshwordsplit is equivalent to x o shwordsplit.
Options may also be specified by name in GNU long option style, optionname. When this is done,
characters in the option name are permitted: they are translated into _, and thus ignored. So, for
example, zsh shwordsplit invokes zsh with the SH_WORD_SPLIT option turned on. Like other
option syntaxes, options can be turned off by replacing the initial with a +; thus +shwordsplit is
equivalent to noshwordsplit. Unlike other option syntaxes, GNUstyle long options cannot be

zsh 4.3.4

April 19, 2006

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHALL(1)

ZSHALL(1)

stacked with any other options, so for example xshwordsplit is an error, rather than being treated like
x shwordsplit.
The special GNUstyle option version is handled; it sends to standard output the shells version information, then exits successfully. help is also handled; it sends to standard output a list of options that
can be used when invoking the shell, then exits successfully.
Option processing may be finished, allowing following arguments that start with or + to be treated as
normal arguments, in two ways. Firstly, a lone (or +) as an argument by itself ends option processing.
Secondly, a special option (or +), which may be specified on its own (which is the standard POSIX
usage) or may be stacked with preceding options (so x is equivalent to x ). Options are not permitted to be stacked after (so xf is an error), but note the GNUstyle option form discussed above,
where shwordsplit is permitted and does not end option processing.
Except when the sh/ksh emulation singleletter options are in effect, the option b (or +b) ends option
processing. b is like , except that further singleletter options can be stacked after the b and will
take effect as normal.

COMPATIBILITY
Zsh tries to emulate sh or ksh when it is invoked as sh or ksh respectively; more precisely, it looks at the
first letter of the name by which it was invoked, excluding any initial r (assumed to stand for restricted),
and if that is s or k it will emulate sh or ksh. Furthermore, if invoked as su (which happens on certain
systems when the shell is executed by the su command), the shell will try to find an alternative name from
the SHELL environment variable and perform emulation based on that.
In sh and ksh compatibility modes the following parameters are not special and not initialized by the shell:
ARGC, argv, cdpath, fignore, fpath, HISTCHARS, mailpath, MANPATH, manpath, path, prompt,
PROMPT, PROMPT2, PROMPT3, PROMPT4, psvar, status, watch.
The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by
$HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile
scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic
expansion before being interpreted as a pathname. Note that the PRIVILEGED option also affects the
execution of startup files.
The following options are set if the shell is invoked as sh or ksh: NO_BAD_PATTERN,
NO_BANG_HIST, NO_BG_NICE, NO_EQUALS, NO_FUNCTION_ARGZERO, GLOB_SUBST,
NO_GLOBAL_EXPORT, NO_HUP, INTERACTIVE_COMMENTS, KSH_ARRAYS, NO_MULTIOS,
NO_NOMATCH,
NO_NOTIFY,
POSIX_BUILTINS,
NO_PROMPT_PERCENT,
RM_STAR_SILENT,
SH_FILE_EXPANSION,
SH_GLOB,
SH_OPTION_LETTERS,
SH_WORD_SPLIT. Additionally the BSD_ECHO and IGNORE_BRACES options are set if zsh is
invoked as sh. Also, the KSH_OPTION_PRINT, LOCAL_OPTIONS, PROMPT_BANG,
PROMPT_SUBST and SINGLE_LINE_ZLE options are set if zsh is invoked as ksh.

RESTRICTED SHELL
When the basename of the command used to invoke zsh starts with the letter r or the r command line
option is supplied at invocation, the shell becomes restricted. Emulation mode is determined after stripping
the letter r from the invocation name. The following are disabled in restricted mode:

zsh 4.3.4

changing directories with the cd builtin

changing or unsetting the PATH, path, MODULE_PATH, module_path, SHELL, HISTFILE,


HISTSIZE,
GID,
EGID,
UID,
EUID,
USERNAME,
LD_LIBRARY_PATH,
LD_AOUT_LIBRARY_PATH, LD_PRELOAD and LD_AOUT_PRELOAD parameters

specifying command names containing /

specifying command pathnames using hash

redirecting output to files

April 19, 2006

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHALL(1)

ZSHALL(1)

using the exec builtin command to replace the shell with another command

using jobs Z to overwrite the shell process argument and environment space

using the ARGV0 parameter to override argv[0] for external commands

turning off restricted mode with set +r or unsetopt RESTRICTED

These restrictions are enforced after processing the startup files. The startup files should set up PATH to
point to a directory of commands which can be safely invoked in the restricted environment. They may
also add further restrictions by disabling selected builtins.
Restricted mode can also be activated any time by setting the RESTRICTED option. This immediately
enables all the restrictions described above even if the shell still has not processed all startup files.

STARTUP/SHUTDOWN FILES
Commands are first read from /etc/zshenv; this cannot be overridden. Subsequent behaviour is modified by
the RCS and GLOBAL_RCS options; the former affects all startup files, while the second only affects
those in the /etc directory. If one of the options is unset at any point, any subsequent startup file(s) of the
corresponding type will not be read. It is also possible for a file in $ZDOTDIR to reenable
GLOBAL_RCS. Both RCS and GLOBAL_RCS are set by default.
Commands are then read from $ZDOTDIR/.zshenv. If the shell is a login shell, commands are read from
/etc/zprofile and then $ZDOTDIR/.zprofile. Then, if the shell is interactive, commands are read from
/etc/zshrc and then $ZDOTDIR/.zshrc. Finally, if the shell is a login shell, /etc/zlogin and $ZDOTDIR/.zlogin are read.
When a login shell exits, the files $ZDOTDIR/.zlogout and then /etc/zlogout are read. This happens with
either an explicit exit via the exit or logout commands, or an implicit exit by reading endoffile from the
terminal. However, if the shell terminates due to execing another process, the logout files are not read.
These are also affected by the RCS and GLOBAL_RCS options. Note also that the RCS option affects
the saving of history files, i.e. if RCS is unset when the shell exits, no history file will be saved.
If ZDOTDIR is unset, HOME is used instead. Those files listed above as being in /etc may be in another
directory, depending on the installation.
As /etc/zshenv is run for all instances of zsh, it is important that it be kept as small as possible. In particular, it is a good idea to put code that does not need to be run for every single shell behind a test of the form
if [[ o rcs ]]; then ... so that it will not be executed when zsh is invoked with the f option.
Any of these files may be precompiled with the zcompile builtin command (see zshbuiltins(1)). If a compiled file exists (named for the original file plus the .zwc extension) and it is newer than the original file, the
compiled file will be used instead.

zsh 4.3.4

April 19, 2006

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHROADMAP(1)

ZSHROADMAP(1)

NAME
zshroadmap informal introduction to the zsh manual
The Zsh Manual, like the shell itself, is large and often complicated. This section of the manual provides
some pointers to areas of the shell that are likely to be of particular interest to new users, and indicates
where in the rest of the manual the documentation is to be found.

WHEN THE SHELL STARTS


When it starts, the shell reads commands from various files. These can be created or edited to customize
the shell. See the section Startup/Shutdown Files in zsh(1).
If no personal intialization files exist for the current user, a function is run to help you change some of the
most common settings. It wont appear if your administrator has disabled the zsh/newuser module. The
function is designed to be selfexplanatory. You can run it by hand with autoload Uz
zshnewuserinstall; zshnewuserinstall f.

INTERACTIVE USE
Interaction with the shell uses the builtin Zsh Line Editor, ZLE. This is described in detail in zshzle(1).
The first decision a user must make is whether to use the Emacs or Vi editing mode as the keys for editing
are substantially different. Emacs editing mode is probably more natural for beginners and can be selected
explicitly with the command bindkey e.
A history mechanism for retrieving previously typed lines (most simply with the Up or Down arrow keys)
is available; note that, unlike other shells, zsh will not save these lines when the shell exits unless you set
appropriate variables, and the number of history lines retained by default is quite small (30 lines). See the
description of the shell variables (referred to in the documentation as parameters) HISTFILE, HISTSIZE
and SAVEHIST in zshparam(1).
Completion
Completion is a feature present in many shells. It allows the user to type only a part (usually the prefix) of a
word and have the shell fill in the rest. The completion system in zsh is programmable. For example, the
shell can be set to complete email addresses in arguments to the mail command from your
/.abook/addressbook; usernames, hostnames, and even remote paths in arguments to scp, and so on. Anything that can be written in or glued together with zsh can be the source of what the line editor offers as
possible completions.

zsh 4.3.4

April 19, 2006

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHMISC(1)

ZSHMISC(1)

NAME
zshmisc everything and then some

SIMPLE COMMANDS & PIPELINES


A simple command is a sequence of optional parameter assignments followed by blankseparated words,
with optional redirections interspersed. The first word is the command to be executed, and the remaining
words, if any, are arguments to the command. If a command name is given, the parameter assignments
modify the environment of the command when it is executed. The value of a simple command is its exit
status, or 128 plus the signal number if terminated by a signal. For example,
echo foo
is a simple command with arguments.
A pipeline is either a simple command, or a sequence of two or more simple commands where each command is separated from the next by | or |&. Where commands are separated by |, the standard output
of the first command is connected to the standard input of the next. |& is shorthand for 2>&1 |, which
connects both the standard output and the standard error of the command to the standard input of the next.
The value of a pipeline is the value of the last command, unless the pipeline is preceded by ! in which
case the value is the logical inverse of the value of the last command. For example,
echo foo | sed s/foo/bar/
is a pipeline, where the output (foo plus a newline) of the first command will be passed to the input of the
second.
If a pipeline is preceded by coproc, it is executed as a coprocess; a twoway pipe is established between
it and the parent shell. The shell can read from or write to the coprocess by means of the >&p and <&p
redirection operators or with print p and read p. A pipeline cannot be preceded by both coproc
and !.

zsh 4.3.4

April 19, 2006

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHPARAM(1)

ZSHPARAM(1)

NAME
zshparam zsh parameters

DESCRIPTION
A parameter has a name, a value, and a number of attributes. A name may be any sequence of alphanumeric characters and underscores, or the single characters *, @, #, ?, , $, or !. The value may
be a scalar (a string), an integer, an array (indexed numerically), or an associative array (an unordered set
of namevalue pairs, indexed by name). To declare the type of a parameter, or to assign a scalar or integer
value to a parameter, use the typeset builtin.
The value of a scalar or integer parameter may also be assigned by writing:
name=value
If the integer attribute, i, is set for name, the value is subject to arithmetic evaluation. Furthermore, by
replacing = with +=, a parameter can be added or appended to. See the section Array Parameters for
additional forms of assignment.
To refer to the value of a parameter, write $name or ${name}. See Parameter Expansion in zshexpn(1)
for complete details.
In the parameter lists that follow, the mark <S> indicates that the parameter is special. Special parameters
cannot have their type changed or their readonly attribute turned off, and if a special parameter is unset,
then later recreated, the special properties will be retained. <Z> indicates that the parameter does not
exist when the shell initializes in sh or ksh emulation mode.

ARRAY PARAMETERS
To assign an array value, write one of:
set A name value ...

zsh 4.3.4

April 19, 2006

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHBUILTINS(1)

ZSHBUILTINS(1)

NAME
zshbuiltins zsh builtin commands

SHELL BUILTIN COMMANDS


simple command
See the section Precommand Modifiers.
. file [ arg ... ]
Read commands from file and execute them in the current shell environment.
If file does not contain a slash, or if PATH_DIRS is set, the shell looks in the components of
$path to find the directory containing file. Files in the current directory are not read unless .
appears somewhere in $path. If a file named file.zwc is found, is newer than file, and is the compiled form (created with the zcompile builtin) of file, then commands are read from that file
instead of file.
If any arguments arg are given, they become the positional parameters; the old positional parameters are restored when the file is done executing. The exit status is the exit status of the last command executed.
: [ arg ... ]
This command does nothing, although normal argument expansions is performed which may have
effects on shell parameters. A zero exit status is returned.
alias [ {+|}gmrsL ] [ name[=value] ... ]
For each name with a corresponding value, define an alias with that value. A trailing space in
value causes the next word to be checked for alias expansion. If the g flag is present, define a
global alias; global aliases are expanded even if they do not occur in command position.
If the s flags is present, define a suffix alias: if the command word on a command line is in the
form text.name, where text is any nonempty string, it is replaced by the text value text.name.
Note that name is treated as a literal string, not a pattern. A trailing space in value is not special in
this case. For example,

zsh 4.3.4

April 19, 2006

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHCOMPWID(1)

ZSHCOMPWID(1)

NAME
zshcompwid zsh completion widgets

DESCRIPTION
The shells programmable completion mechanism can be manipulated in two ways; here the lowlevel features supporting the newer, functionbased mechanism are defined. A complete set of shell functions based
on these features is described in zshcompsys(1), and users with no interest in adding to that system (or,
potentially, writing their own see dictionary entry for hubris) should skip the current section. The
older system based on the compctl builtin command is described in zshcompctl(1).
Completion widgets are defined by the C option to the zle builtin command provided by the zsh/zle module (see zshzle(1)). For example,
zle C complete expandorcomplete completer
defines a widget named complete. The second argument is the name of any of the builtin widgets that
handle completions: completeword, expandorcomplete, expandorcompleteprefix, menucomplete, menuexpandorcomplete, reversemenucomplete, listchoices, or deletecharorlist.
Note that this will still work even if the widget in question has been rebound.
When this newly defined widget is bound to a key using the bindkey builtin command defined in the
zsh/zle module (see zshzle(1)), typing that key will call the shell function completer. This function is
responsible for generating the possible matches using the builtins described below. As with other ZLE widgets, the function is called with its standard input closed.
Once the function returns, the completion code takes over control again and treats the matches in the same
manner as the specified builtin widget, in this case expandorcomplete.

SPECIAL PARAMETERS
Inside completion widgets, and any functions called from them, some parameters have special meaning;
outside these functions they are not

zsh 4.3.4

April 19, 2006

Property of BladeLogic, Inc.


Strictly confidential and proprietary

ZSHMODULES(1)

ZSHMODULES(1)

NAME
zshmodules zsh loadable modules

DESCRIPTION
Some optional parts of zsh are in modules, separate from the core of the shell. Each of these modules may
be linked in to the shell at build time, or can be dynamically linked while the shell is running if the installation supports this feature. The modules that are bundled with the zsh distribution are:
zsh/cap
Builtins for manipulating POSIX.1e (POSIX.6) capability (privilege) sets.
zsh/clone
A builtin that can clone a running shell onto another terminal.
zsh/compctl
The compctl builtin for controlling completion.
zsh/complete
The basic completion code.
zsh/complist
Completion listing extensions.
zsh/computil
A module with utility builtins needed for the shell function based completion system.
zsh/datetime
Some date/time commands and parameters.
zsh/deltochar
A ZLE function duplicating EMACS zaptochar.
zsh/example
An example of how to write a module.
zsh/files
Some basic file manipulation commands as builtins.
zsh/mapfile
Access to external files via a special associative array.

zsh 4.3.4

April 19, 2006

*107245*
*107245*
*107245*
*107245*
*107245*

Das könnte Ihnen auch gefallen