command
stringlengths
1
42
description
stringlengths
29
182k
name
stringlengths
7
64.9k
synopsis
stringlengths
4
85.3k
options
stringclasses
593 values
examples
stringclasses
455 values
htmltree
null
htmltree - Parse the given HTML file(s) and dump the parse tree
htmltree -D3 -w file1 file2 file3 Options: -D[number] sets HTML::TreeBuilder::Debug to that figure. -w turns on $tree->warn(1) for the new tree -h Help message perl v5.34.0 2024-04-13 HTMLTREE(1)
null
null
git
Git is a fast, scalable, distributed revision control system with an unusually rich command set that provides both high-level operations and full access to internals. See gittutorial(7) to get started, then see giteveryday(7) for a useful minimum set of commands. The Git User’s Manual[1] has a more in-depth introduction. After you mastered the basic concepts, you can come back to this page to learn what commands Git offers. You can learn more about individual Git commands with "git help command". gitcli(7) manual page gives you an overview of the command-line command syntax. A formatted and hyperlinked copy of the latest Git documentation can be viewed at https://git.github.io/htmldocs/git.html or https://git-scm.com/docs.
git - the stupid content tracker
git [-v | --version] [-h | --help] [-C <path>] [-c <name>=<value>] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] [-p|--paginate|-P|--no-pager] [--no-replace-objects] [--bare] [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] [--config-env=<name>=<envvar>] <command> [<args>]
-v, --version Prints the Git suite version that the git program came from. This option is internally converted to git version ... and accepts the same options as the git-version(1) command. If --help is also given, it takes precedence over --version. -h, --help Prints the synopsis and a list of the most commonly used commands. If the option --all or -a is given then all available commands are printed. If a Git command is named this option will bring up the manual page for that command. Other options are available to control how the manual page is displayed. See git-help(1) for more information, because git --help ... is converted internally into git help .... -C <path> Run as if git was started in <path> instead of the current working directory. When multiple -C options are given, each subsequent non-absolute -C <path> is interpreted relative to the preceding -C <path>. If <path> is present but empty, e.g. -C "", then the current working directory is left unchanged. This option affects options that expect path name like --git-dir and --work-tree in that their interpretations of the path names would be made relative to the working directory caused by the -C option. For example the following invocations are equivalent: git --git-dir=a.git --work-tree=b -C c status git --git-dir=c/a.git --work-tree=c/b status -c <name>=<value> Pass a configuration parameter to the command. The value given will override values from configuration files. The <name> is expected in the same format as listed by git config (subkeys separated by dots). Note that omitting the = in git -c foo.bar ... is allowed and sets foo.bar to the boolean true value (just like [foo]bar would in a config file). Including the equals but with an empty value (like git -c foo.bar= ...) sets foo.bar to the empty string which git config --type=bool will convert to false. --config-env=<name>=<envvar> Like -c <name>=<value>, give configuration variable <name> a value, where <envvar> is the name of an environment variable from which to retrieve the value. Unlike -c there is no shortcut for directly setting the value to an empty string, instead the environment variable itself must be set to the empty string. It is an error if the <envvar> does not exist in the environment. <envvar> may not contain an equals sign to avoid ambiguity with <name> containing one. This is useful for cases where you want to pass transitory configuration options to git, but are doing so on OS’s where other processes might be able to read your cmdline (e.g. /proc/self/cmdline), but not your environ (e.g. /proc/self/environ). That behavior is the default on Linux, but may not be on your system. Note that this might add security for variables such as http.extraHeader where the sensitive information is part of the value, but not e.g. url.<base>.insteadOf where the sensitive information can be part of the key. --exec-path[=<path>] Path to wherever your core Git programs are installed. This can also be controlled by setting the GIT_EXEC_PATH environment variable. If no path is given, git will print the current setting and then exit. --html-path Print the path, without trailing slash, where Git’s HTML documentation is installed and exit. --man-path Print the manpath (see man(1)) for the man pages for this version of Git and exit. --info-path Print the path where the Info files documenting this version of Git are installed and exit. -p, --paginate Pipe all output into less (or if set, $PAGER) if standard output is a terminal. This overrides the pager.<cmd> configuration options (see the "Configuration Mechanism" section below). -P, --no-pager Do not pipe Git output into a pager. --git-dir=<path> Set the path to the repository (".git" directory). This can also be controlled by setting the GIT_DIR environment variable. It can be an absolute path or relative path to current working directory. Specifying the location of the ".git" directory using this option (or GIT_DIR environment variable) turns off the repository discovery that tries to find a directory with ".git" subdirectory (which is how the repository and the top-level of the working tree are discovered), and tells Git that you are at the top level of the working tree. If you are not at the top-level directory of the working tree, you should tell Git where the top-level of the working tree is, with the --work-tree=<path> option (or GIT_WORK_TREE environment variable) If you just want to run git as if it was started in <path> then use git -C <path>. --work-tree=<path> Set the path to the working tree. It can be an absolute path or a path relative to the current working directory. This can also be controlled by setting the GIT_WORK_TREE environment variable and the core.worktree configuration variable (see core.worktree in git- config(1) for a more detailed discussion). --namespace=<path> Set the Git namespace. See gitnamespaces(7) for more details. Equivalent to setting the GIT_NAMESPACE environment variable. --bare Treat the repository as a bare repository. If GIT_DIR environment is not set, it is set to the current working directory. --no-replace-objects Do not use replacement refs to replace Git objects. See git- replace(1) for more information. --literal-pathspecs Treat pathspecs literally (i.e. no globbing, no pathspec magic). This is equivalent to setting the GIT_LITERAL_PATHSPECS environment variable to 1. --glob-pathspecs Add "glob" magic to all pathspec. This is equivalent to setting the GIT_GLOB_PATHSPECS environment variable to 1. Disabling globbing on individual pathspecs can be done using pathspec magic ":(literal)" --noglob-pathspecs Add "literal" magic to all pathspec. This is equivalent to setting the GIT_NOGLOB_PATHSPECS environment variable to 1. Enabling globbing on individual pathspecs can be done using pathspec magic ":(glob)" --icase-pathspecs Add "icase" magic to all pathspec. This is equivalent to setting the GIT_ICASE_PATHSPECS environment variable to 1. --no-optional-locks Do not perform optional operations that require locks. This is equivalent to setting the GIT_OPTIONAL_LOCKS to 0. --list-cmds=group[,group...] List commands by group. This is an internal/experimental option and may change or be removed in the future. Supported groups are: builtins, parseopt (builtin commands that use parse-options), main (all commands in libexec directory), others (all other commands in $PATH that have git- prefix), list-<category> (see categories in command-list.txt), nohelpers (exclude helper commands), alias and config (retrieve command list from config variable completion.commands) --attr-source=<tree-ish> Read gitattributes from <tree-ish> instead of the worktree. See gitattributes(5). This is equivalent to setting the GIT_ATTR_SOURCE environment variable. GIT COMMANDS We divide Git into high level ("porcelain") commands and low level ("plumbing") commands. HIGH-LEVEL COMMANDS (PORCELAIN) We separate the porcelain commands into the main commands and some ancillary user utilities. Main porcelain commands git-add(1) Add file contents to the index. git-am(1) Apply a series of patches from a mailbox. git-archive(1) Create an archive of files from a named tree. git-bisect(1) Use binary search to find the commit that introduced a bug. git-branch(1) List, create, or delete branches. git-bundle(1) Move objects and refs by archive. git-checkout(1) Switch branches or restore working tree files. git-cherry-pick(1) Apply the changes introduced by some existing commits. git-citool(1) Graphical alternative to git-commit. git-clean(1) Remove untracked files from the working tree. git-clone(1) Clone a repository into a new directory. git-commit(1) Record changes to the repository. git-describe(1) Give an object a human readable name based on an available ref. git-diff(1) Show changes between commits, commit and working tree, etc. git-fetch(1) Download objects and refs from another repository. git-format-patch(1) Prepare patches for e-mail submission. git-gc(1) Cleanup unnecessary files and optimize the local repository. git-grep(1) Print lines matching a pattern. git-gui(1) A portable graphical interface to Git. git-init(1) Create an empty Git repository or reinitialize an existing one. git-log(1) Show commit logs. git-maintenance(1) Run tasks to optimize Git repository data. git-merge(1) Join two or more development histories together. git-mv(1) Move or rename a file, a directory, or a symlink. git-notes(1) Add or inspect object notes. git-pull(1) Fetch from and integrate with another repository or a local branch. git-push(1) Update remote refs along with associated objects. git-range-diff(1) Compare two commit ranges (e.g. two versions of a branch). git-rebase(1) Reapply commits on top of another base tip. git-reset(1) Reset current HEAD to the specified state. git-restore(1) Restore working tree files. git-revert(1) Revert some existing commits. git-rm(1) Remove files from the working tree and from the index. git-shortlog(1) Summarize git log output. git-show(1) Show various types of objects. git-sparse-checkout(1) Reduce your working tree to a subset of tracked files. git-stash(1) Stash the changes in a dirty working directory away. git-status(1) Show the working tree status. git-submodule(1) Initialize, update or inspect submodules. git-switch(1) Switch branches. git-tag(1) Create, list, delete or verify a tag object signed with GPG. git-worktree(1) Manage multiple working trees. gitk(1) The Git repository browser. scalar(1) A tool for managing large Git repositories. Ancillary Commands Manipulators: git-config(1) Get and set repository or global options. git-fast-export(1) Git data exporter. git-fast-import(1) Backend for fast Git data importers. git-filter-branch(1) Rewrite branches. git-mergetool(1) Run merge conflict resolution tools to resolve merge conflicts. git-pack-refs(1) Pack heads and tags for efficient repository access. git-prune(1) Prune all unreachable objects from the object database. git-reflog(1) Manage reflog information. git-remote(1) Manage set of tracked repositories. git-repack(1) Pack unpacked objects in a repository. git-replace(1) Create, list, delete refs to replace objects. Interrogators: git-annotate(1) Annotate file lines with commit information. git-blame(1) Show what revision and author last modified each line of a file. git-bugreport(1) Collect information for user to file a bug report. git-count-objects(1) Count unpacked number of objects and their disk consumption. git-diagnose(1) Generate a zip archive of diagnostic information. git-difftool(1) Show changes using common diff tools. git-fsck(1) Verifies the connectivity and validity of the objects in the database. git-help(1) Display help information about Git. git-instaweb(1) Instantly browse your working repository in gitweb. git-merge-tree(1) Perform merge without touching index or working tree. git-rerere(1) Reuse recorded resolution of conflicted merges. git-show-branch(1) Show branches and their commits. git-verify-commit(1) Check the GPG signature of commits. git-verify-tag(1) Check the GPG signature of tags. git-version(1) Display version information about Git. git-whatchanged(1) Show logs with difference each commit introduces. gitweb(1) Git web interface (web frontend to Git repositories). Interacting with Others These commands are to interact with foreign SCM and with other people via patch over e-mail. git-archimport(1) Import a GNU Arch repository into Git. git-cvsexportcommit(1) Export a single commit to a CVS checkout. git-cvsimport(1) Salvage your data out of another SCM people love to hate. git-cvsserver(1) A CVS server emulator for Git. git-imap-send(1) Send a collection of patches from stdin to an IMAP folder. git-p4(1) Import from and submit to Perforce repositories. git-quiltimport(1) Applies a quilt patchset onto the current branch. git-request-pull(1) Generates a summary of pending changes. git-send-email(1) Send a collection of patches as emails. git-svn(1) Bidirectional operation between a Subversion repository and Git. Reset, restore and revert There are three commands with similar names: git reset, git restore and git revert. • git-revert(1) is about making a new commit that reverts the changes made by other commits. • git-restore(1) is about restoring files in the working tree from either the index or another commit. This command does not update your branch. The command can also be used to restore files in the index from another commit. • git-reset(1) is about updating your branch, moving the tip in order to add or remove commits from the branch. This operation changes the commit history. git reset can also be used to restore the index, overlapping with git restore. LOW-LEVEL COMMANDS (PLUMBING) Although Git includes its own porcelain layer, its low-level commands are sufficient to support development of alternative porcelains. Developers of such porcelains might start by reading about git-update- index(1) and git-read-tree(1). The interface (input, output, set of options and the semantics) to these low-level commands are meant to be a lot more stable than Porcelain level commands, because these commands are primarily for scripted use. The interface to Porcelain commands on the other hand are subject to change in order to improve the end user experience. The following description divides the low-level commands into commands that manipulate objects (in the repository, index, and working tree), commands that interrogate and compare objects, and commands that move objects and references between repositories. Manipulation commands git-apply(1) Apply a patch to files and/or to the index. git-checkout-index(1) Copy files from the index to the working tree. git-commit-graph(1) Write and verify Git commit-graph files. git-commit-tree(1) Create a new commit object. git-hash-object(1) Compute object ID and optionally creates a blob from a file. git-index-pack(1) Build pack index file for an existing packed archive. git-merge-file(1) Run a three-way file merge. git-merge-index(1) Run a merge for files needing merging. git-mktag(1) Creates a tag object with extra validation. git-mktree(1) Build a tree-object from ls-tree formatted text. git-multi-pack-index(1) Write and verify multi-pack-indexes. git-pack-objects(1) Create a packed archive of objects. git-prune-packed(1) Remove extra objects that are already in pack files. git-read-tree(1) Reads tree information into the index. git-symbolic-ref(1) Read, modify and delete symbolic refs. git-unpack-objects(1) Unpack objects from a packed archive. git-update-index(1) Register file contents in the working tree to the index. git-update-ref(1) Update the object name stored in a ref safely. git-write-tree(1) Create a tree object from the current index. Interrogation commands git-cat-file(1) Provide content or type and size information for repository objects. git-cherry(1) Find commits yet to be applied to upstream. git-diff-files(1) Compares files in the working tree and the index. git-diff-index(1) Compare a tree to the working tree or index. git-diff-tree(1) Compares the content and mode of blobs found via two tree objects. git-for-each-ref(1) Output information on each ref. git-for-each-repo(1) Run a Git command on a list of repositories. git-get-tar-commit-id(1) Extract commit ID from an archive created using git-archive. git-ls-files(1) Show information about files in the index and the working tree. git-ls-remote(1) List references in a remote repository. git-ls-tree(1) List the contents of a tree object. git-merge-base(1) Find as good common ancestors as possible for a merge. git-name-rev(1) Find symbolic names for given revs. git-pack-redundant(1) Find redundant pack files. git-rev-list(1) Lists commit objects in reverse chronological order. git-rev-parse(1) Pick out and massage parameters. git-show-index(1) Show packed archive index. git-show-ref(1) List references in a local repository. git-unpack-file(1) Creates a temporary file with a blob’s contents. git-var(1) Show a Git logical variable. git-verify-pack(1) Validate packed Git archive files. In general, the interrogate commands do not touch the files in the working tree. Syncing repositories git-daemon(1) A really simple server for Git repositories. git-fetch-pack(1) Receive missing objects from another repository. git-http-backend(1) Server side implementation of Git over HTTP. git-send-pack(1) Push objects over Git protocol to another repository. git-update-server-info(1) Update auxiliary info file to help dumb servers. The following are helper commands used by the above; end users typically do not use them directly. git-http-fetch(1) Download from a remote Git repository via HTTP. git-http-push(1) Push objects over HTTP/DAV to another repository. git-receive-pack(1) Receive what is pushed into the repository. git-shell(1) Restricted login shell for Git-only SSH access. git-upload-archive(1) Send archive back to git-archive. git-upload-pack(1) Send objects packed back to git-fetch-pack. Internal helper commands These are internal helper commands used by other commands; end users typically do not use them directly. git-check-attr(1) Display gitattributes information. git-check-ignore(1) Debug gitignore / exclude files. git-check-mailmap(1) Show canonical names and email addresses of contacts. git-check-ref-format(1) Ensures that a reference name is well formed. git-column(1) Display data in columns. git-credential(1) Retrieve and store user credentials. git-credential-cache(1) Helper to temporarily store passwords in memory. git-credential-store(1) Helper to store credentials on disk. git-fmt-merge-msg(1) Produce a merge commit message. git-hook(1) Run git hooks. git-interpret-trailers(1) Add or parse structured information in commit messages. git-mailinfo(1) Extracts patch and authorship from a single e-mail message. git-mailsplit(1) Simple UNIX mbox splitter program. git-merge-one-file(1) The standard helper program to use with git-merge-index. git-patch-id(1) Compute unique ID for a patch. git-sh-i18n(1) Git’s i18n setup code for shell scripts. git-sh-setup(1) Common Git shell script setup code. git-stripspace(1) Remove unnecessary whitespace. GUIDES The following documentation pages are guides about Git concepts. gitcore-tutorial(7) A Git core tutorial for developers. gitcredentials(7) Providing usernames and passwords to Git. gitcvs-migration(7) Git for CVS users. gitdiffcore(7) Tweaking diff output. giteveryday(7) A useful minimum set of commands for Everyday Git. gitfaq(7) Frequently asked questions about using Git. gitglossary(7) A Git Glossary. gitnamespaces(7) Git namespaces. gitremote-helpers(7) Helper programs to interact with remote repositories. gitsubmodules(7) Mounting one repository inside another. gittutorial(7) A tutorial introduction to Git. gittutorial-2(7) A tutorial introduction to Git: part two. gitworkflows(7) An overview of recommended workflows with Git. REPOSITORY, COMMAND AND FILE INTERFACES This documentation discusses repository and command interfaces which users are expected to interact with directly. See --user-formats in git-help(1) for more details on the criteria. gitattributes(5) Defining attributes per path. gitcli(7) Git command-line interface and conventions. githooks(5) Hooks used by Git. gitignore(5) Specifies intentionally untracked files to ignore. gitmailmap(5) Map author/committer names and/or E-Mail addresses. gitmodules(5) Defining submodule properties. gitrepository-layout(5) Git Repository Layout. gitrevisions(7) Specifying revisions and ranges for Git. FILE FORMATS, PROTOCOLS AND OTHER DEVELOPER INTERFACES This documentation discusses file formats, over-the-wire protocols and other git developer interfaces. See --developer-interfaces in git- help(1). gitformat-bundle(5) The bundle file format. gitformat-chunk(5) Chunk-based file formats. gitformat-commit-graph(5) Git commit-graph format. gitformat-index(5) Git index format. gitformat-pack(5) Git pack format. gitformat-signature(5) Git cryptographic signature formats. gitprotocol-capabilities(5) Protocol v0 and v1 capabilities. gitprotocol-common(5) Things common to various protocols. gitprotocol-http(5) Git HTTP-based protocols. gitprotocol-pack(5) How packs are transferred over-the-wire. gitprotocol-v2(5) Git Wire Protocol, Version 2. CONFIGURATION MECHANISM Git uses a simple text format to store customizations that are per repository and are per user. Such a configuration file may look like this: # # A '#' or ';' character indicates a comment. # ; core variables [core] ; Don't trust file modes filemode = false ; user identity [user] name = "Junio C Hamano" email = "gitster@pobox.com" Various commands read from the configuration file and adjust their operation accordingly. See git-config(1) for a list and more details about the configuration mechanism. IDENTIFIER TERMINOLOGY <object> Indicates the object name for any type of object. <blob> Indicates a blob object name. <tree> Indicates a tree object name. <commit> Indicates a commit object name. <tree-ish> Indicates a tree, commit or tag object name. A command that takes a <tree-ish> argument ultimately wants to operate on a <tree> object but automatically dereferences <commit> and <tag> objects that point at a <tree>. <commit-ish> Indicates a commit or tag object name. A command that takes a <commit-ish> argument ultimately wants to operate on a <commit> object but automatically dereferences <tag> objects that point at a <commit>. <type> Indicates that an object type is required. Currently one of: blob, tree, commit, or tag. <file> Indicates a filename - almost always relative to the root of the tree structure GIT_INDEX_FILE describes. SYMBOLIC IDENTIFIERS Any Git command accepting any <object> can also use the following symbolic notation: HEAD indicates the head of the current branch. <tag> a valid tag name (i.e. a refs/tags/<tag> reference). <head> a valid head name (i.e. a refs/heads/<head> reference). For a more complete list of ways to spell object names, see "SPECIFYING REVISIONS" section in gitrevisions(7). FILE/DIRECTORY STRUCTURE Please see the gitrepository-layout(5) document. Read githooks(5) for more details about each hook. Higher level SCMs may provide and manage additional information in the $GIT_DIR. TERMINOLOGY Please see gitglossary(7). ENVIRONMENT VARIABLES Various Git commands pay attention to environment variables and change their behavior. The environment variables marked as "Boolean" take their values the same way as Boolean valued configuration variables, e.g. "true", "yes", "on" and positive numbers are taken as "yes". Here are the variables: The Git Repository These environment variables apply to all core Git commands. Nb: it is worth noting that they may be used/overridden by SCMS sitting above Git so take care if using a foreign front-end. GIT_INDEX_FILE This environment variable specifies an alternate index file. If not specified, the default of $GIT_DIR/index is used. GIT_INDEX_VERSION This environment variable specifies what index version is used when writing the index file out. It won’t affect existing index files. By default index file version 2 or 3 is used. See git-update- index(1) for more information. GIT_OBJECT_DIRECTORY If the object storage directory is specified via this environment variable then the sha1 directories are created underneath - otherwise the default $GIT_DIR/objects directory is used. GIT_ALTERNATE_OBJECT_DIRECTORIES Due to the immutable nature of Git objects, old objects can be archived into shared, read-only directories. This variable specifies a ":" separated (on Windows ";" separated) list of Git object directories which can be used to search for Git objects. New objects will not be written to these directories. Entries that begin with " (double-quote) will be interpreted as C-style quoted paths, removing leading and trailing double-quotes and respecting backslash escapes. E.g., the value "path-with-\"-and-:-in-it":vanilla-path has two paths: path-with-"-and-:-in-it and vanilla-path. GIT_DIR If the GIT_DIR environment variable is set then it specifies a path to use instead of the default .git for the base of the repository. The --git-dir command-line option also sets this value. GIT_WORK_TREE Set the path to the root of the working tree. This can also be controlled by the --work-tree command-line option and the core.worktree configuration variable. GIT_NAMESPACE Set the Git namespace; see gitnamespaces(7) for details. The --namespace command-line option also sets this value. GIT_CEILING_DIRECTORIES This should be a colon-separated list of absolute paths. If set, it is a list of directories that Git should not chdir up into while looking for a repository directory (useful for excluding slow-loading network directories). It will not exclude the current working directory or a GIT_DIR set on the command line or in the environment. Normally, Git has to read the entries in this list and resolve any symlink that might be present in order to compare them with the current directory. However, if even this access is slow, you can add an empty entry to the list to tell Git that the subsequent entries are not symlinks and needn’t be resolved; e.g., GIT_CEILING_DIRECTORIES=/maybe/symlink::/very/slow/non/symlink. GIT_DISCOVERY_ACROSS_FILESYSTEM When run in a directory that does not have ".git" repository directory, Git tries to find such a directory in the parent directories to find the top of the working tree, but by default it does not cross filesystem boundaries. This Boolean environment variable can be set to true to tell Git not to stop at filesystem boundaries. Like GIT_CEILING_DIRECTORIES, this will not affect an explicit repository directory set via GIT_DIR or on the command line. GIT_COMMON_DIR If this variable is set to a path, non-worktree files that are normally in $GIT_DIR will be taken from this path instead. Worktree-specific files such as HEAD or index are taken from $GIT_DIR. See gitrepository-layout(5) and git-worktree(1) for details. This variable has lower precedence than other path variables such as GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY... GIT_DEFAULT_HASH If this variable is set, the default hash algorithm for new repositories will be set to this value. This value is ignored when cloning and the setting of the remote repository is always used. The default is "sha1". THIS VARIABLE IS EXPERIMENTAL! See --object-format in git-init(1). Git Commits GIT_AUTHOR_NAME The human-readable name used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides the user.name and author.name configuration settings. GIT_AUTHOR_EMAIL The email address used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides the user.email and author.email configuration settings. GIT_AUTHOR_DATE The date used for the author identity when creating commit or tag objects, or when writing reflogs. See git-commit(1) for valid formats. GIT_COMMITTER_NAME The human-readable name used in the committer identity when creating commit or tag objects, or when writing reflogs. Overrides the user.name and committer.name configuration settings. GIT_COMMITTER_EMAIL The email address used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides the user.email and committer.email configuration settings. GIT_COMMITTER_DATE The date used for the committer identity when creating commit or tag objects, or when writing reflogs. See git-commit(1) for valid formats. EMAIL The email address used in the author and committer identities if no other relevant environment variable or configuration setting has been set. Git Diffs GIT_DIFF_OPTS Only valid setting is "--unified=??" or "-u??" to set the number of context lines shown when a unified diff is created. This takes precedence over any "-U" or "--unified" option value passed on the Git diff command line. GIT_EXTERNAL_DIFF When the environment variable GIT_EXTERNAL_DIFF is set, the program named by it is called to generate diffs, and Git does not use its builtin diff machinery. For a path that is added, removed, or modified, GIT_EXTERNAL_DIFF is called with 7 parameters: path old-file old-hex old-mode new-file new-hex new-mode where: <old|new>-file are files GIT_EXTERNAL_DIFF can use to read the contents of <old|new>, <old|new>-hex are the 40-hexdigit SHA-1 hashes, <old|new>-mode are the octal representation of the file modes. The file parameters can point at the user’s working file (e.g. new-file in "git-diff-files"), /dev/null (e.g. old-file when a new file is added), or a temporary file (e.g. old-file in the index). GIT_EXTERNAL_DIFF should not worry about unlinking the temporary file — it is removed when GIT_EXTERNAL_DIFF exits. For a path that is unmerged, GIT_EXTERNAL_DIFF is called with 1 parameter, <path>. For each path GIT_EXTERNAL_DIFF is called, two environment variables, GIT_DIFF_PATH_COUNTER and GIT_DIFF_PATH_TOTAL are set. GIT_DIFF_PATH_COUNTER A 1-based counter incremented by one for every path. GIT_DIFF_PATH_TOTAL The total number of paths. other GIT_MERGE_VERBOSITY A number controlling the amount of output shown by the recursive merge strategy. Overrides merge.verbosity. See git-merge(1) GIT_PAGER This environment variable overrides $PAGER. If it is set to an empty string or to the value "cat", Git will not launch a pager. See also the core.pager option in git-config(1). GIT_PROGRESS_DELAY A number controlling how many seconds to delay before showing optional progress indicators. Defaults to 2. GIT_EDITOR This environment variable overrides $EDITOR and $VISUAL. It is used by several Git commands when, on interactive mode, an editor is to be launched. See also git-var(1) and the core.editor option in git- config(1). GIT_SEQUENCE_EDITOR This environment variable overrides the configured Git editor when editing the todo list of an interactive rebase. See also git- rebase(1) and the sequence.editor option in git-config(1). GIT_SSH, GIT_SSH_COMMAND If either of these environment variables is set then git fetch and git push will use the specified command instead of ssh when they need to connect to a remote system. The command-line parameters passed to the configured command are determined by the ssh variant. See ssh.variant option in git-config(1) for details. $GIT_SSH_COMMAND takes precedence over $GIT_SSH, and is interpreted by the shell, which allows additional arguments to be included. $GIT_SSH on the other hand must be just the path to a program (which can be a wrapper shell script, if additional arguments are needed). Usually it is easier to configure any desired options through your personal .ssh/config file. Please consult your ssh documentation for further details. GIT_SSH_VARIANT If this environment variable is set, it overrides Git’s autodetection whether GIT_SSH/GIT_SSH_COMMAND/core.sshCommand refer to OpenSSH, plink or tortoiseplink. This variable overrides the config setting ssh.variant that serves the same purpose. GIT_SSL_NO_VERIFY Setting and exporting this environment variable to any value tells Git not to verify the SSL certificate when fetching or pushing over HTTPS. GIT_ATTR_SOURCE Sets the treeish that gitattributes will be read from. GIT_ASKPASS If this environment variable is set, then Git commands which need to acquire passwords or passphrases (e.g. for HTTP or IMAP authentication) will call this program with a suitable prompt as command-line argument and read the password from its STDOUT. See also the core.askPass option in git-config(1). GIT_TERMINAL_PROMPT If this Boolean environment variable is set to false, git will not prompt on the terminal (e.g., when asking for HTTP authentication). GIT_CONFIG_GLOBAL, GIT_CONFIG_SYSTEM Take the configuration from the given files instead from global or system-level configuration files. If GIT_CONFIG_SYSTEM is set, the system config file defined at build time (usually /etc/gitconfig) will not be read. Likewise, if GIT_CONFIG_GLOBAL is set, neither $HOME/.gitconfig nor $XDG_CONFIG_HOME/git/config will be read. Can be set to /dev/null to skip reading configuration files of the respective level. GIT_CONFIG_NOSYSTEM Whether to skip reading settings from the system-wide $(prefix)/etc/gitconfig file. This Boolean environment variable can be used along with $HOME and $XDG_CONFIG_HOME to create a predictable environment for a picky script, or you can set it to true to temporarily avoid using a buggy /etc/gitconfig file while waiting for someone with sufficient permissions to fix it. GIT_FLUSH If this environment variable is set to "1", then commands such as git blame (in incremental mode), git rev-list, git log, git check-attr and git check-ignore will force a flush of the output stream after each record have been flushed. If this variable is set to "0", the output of these commands will be done using completely buffered I/O. If this environment variable is not set, Git will choose buffered or record-oriented flushing based on whether stdout appears to be redirected to a file or not. GIT_TRACE Enables general trace messages, e.g. alias expansion, built-in command execution and external command execution. If this variable is set to "1", "2" or "true" (comparison is case insensitive), trace messages will be printed to stderr. If the variable is set to an integer value greater than 2 and lower than 10 (strictly) then Git will interpret this value as an open file descriptor and will try to write the trace messages into this file descriptor. Alternatively, if the variable is set to an absolute path (starting with a / character), Git will interpret this as a file path and will try to append the trace messages to it. Unsetting the variable, or setting it to empty, "0" or "false" (case insensitive) disables trace messages. GIT_TRACE_FSMONITOR Enables trace messages for the filesystem monitor extension. See GIT_TRACE for available trace output options. GIT_TRACE_PACK_ACCESS Enables trace messages for all accesses to any packs. For each access, the pack file name and an offset in the pack is recorded. This may be helpful for troubleshooting some pack-related performance problems. See GIT_TRACE for available trace output options. GIT_TRACE_PACKET Enables trace messages for all packets coming in or out of a given program. This can help with debugging object negotiation or other protocol issues. Tracing is turned off at a packet starting with "PACK" (but see GIT_TRACE_PACKFILE below). See GIT_TRACE for available trace output options. GIT_TRACE_PACKFILE Enables tracing of packfiles sent or received by a given program. Unlike other trace output, this trace is verbatim: no headers, and no quoting of binary data. You almost certainly want to direct into a file (e.g., GIT_TRACE_PACKFILE=/tmp/my.pack) rather than displaying it on the terminal or mixing it with other trace output. Note that this is currently only implemented for the client side of clones and fetches. GIT_TRACE_PERFORMANCE Enables performance related trace messages, e.g. total execution time of each Git command. See GIT_TRACE for available trace output options. GIT_TRACE_REFS Enables trace messages for operations on the ref database. See GIT_TRACE for available trace output options. GIT_TRACE_SETUP Enables trace messages printing the .git, working tree and current working directory after Git has completed its setup phase. See GIT_TRACE for available trace output options. GIT_TRACE_SHALLOW Enables trace messages that can help debugging fetching / cloning of shallow repositories. See GIT_TRACE for available trace output options. GIT_TRACE_CURL Enables a curl full trace dump of all incoming and outgoing data, including descriptive information, of the git transport protocol. This is similar to doing curl --trace-ascii on the command line. See GIT_TRACE for available trace output options. GIT_TRACE_CURL_NO_DATA When a curl trace is enabled (see GIT_TRACE_CURL above), do not dump data (that is, only dump info lines and headers). GIT_TRACE2 Enables more detailed trace messages from the "trace2" library. Output from GIT_TRACE2 is a simple text-based format for human readability. If this variable is set to "1", "2" or "true" (comparison is case insensitive), trace messages will be printed to stderr. If the variable is set to an integer value greater than 2 and lower than 10 (strictly) then Git will interpret this value as an open file descriptor and will try to write the trace messages into this file descriptor. Alternatively, if the variable is set to an absolute path (starting with a / character), Git will interpret this as a file path and will try to append the trace messages to it. If the path already exists and is a directory, the trace messages will be written to files (one per process) in that directory, named according to the last component of the SID and an optional counter (to avoid filename collisions). In addition, if the variable is set to af_unix:[<socket_type>:]<absolute-pathname>, Git will try to open the path as a Unix Domain Socket. The socket type can be either stream or dgram. Unsetting the variable, or setting it to empty, "0" or "false" (case insensitive) disables trace messages. See Trace2 documentation[2] for full details. GIT_TRACE2_EVENT This setting writes a JSON-based format that is suited for machine interpretation. See GIT_TRACE2 for available trace output options and Trace2 documentation[2] for full details. GIT_TRACE2_PERF In addition to the text-based messages available in GIT_TRACE2, this setting writes a column-based format for understanding nesting regions. See GIT_TRACE2 for available trace output options and Trace2 documentation[2] for full details. GIT_TRACE_REDACT By default, when tracing is activated, Git redacts the values of cookies, the "Authorization:" header, the "Proxy-Authorization:" header and packfile URIs. Set this Boolean environment variable to false to prevent this redaction. GIT_LITERAL_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs literally, rather than as glob patterns. For example, running GIT_LITERAL_PATHSPECS=1 git log -- '*.c' will search for commits that touch the path *.c, not any paths that the glob *.c matches. You might want this if you are feeding literal paths to Git (e.g., paths previously given to you by git ls-tree, --raw diff output, etc). GIT_GLOB_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs as glob patterns (aka "glob" magic). GIT_NOGLOB_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs as literal (aka "literal" magic). GIT_ICASE_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs as case-insensitive. GIT_REFLOG_ACTION When a ref is updated, reflog entries are created to keep track of the reason why the ref was updated (which is typically the name of the high-level command that updated the ref), in addition to the old and new values of the ref. A scripted Porcelain command can use set_reflog_action helper function in git-sh-setup to set its name to this variable when it is invoked as the top level command by the end user, to be recorded in the body of the reflog. GIT_REF_PARANOIA If this Boolean environment variable is set to false, ignore broken or badly named refs when iterating over lists of refs. Normally Git will try to include any such refs, which may cause some operations to fail. This is usually preferable, as potentially destructive operations (e.g., git-prune(1)) are better off aborting rather than ignoring broken refs (and thus considering the history they point to as not worth saving). The default value is 1 (i.e., be paranoid about detecting and aborting all operations). You should not normally need to set this to 0, but it may be useful when trying to salvage data from a corrupted repository. GIT_ALLOW_PROTOCOL If set to a colon-separated list of protocols, behave as if protocol.allow is set to never, and each of the listed protocols has protocol.<name>.allow set to always (overriding any existing configuration). See the description of protocol.allow in git- config(1) for more details. GIT_PROTOCOL_FROM_USER Set this Boolean environment variable to false to prevent protocols used by fetch/push/clone which are configured to the user state. This is useful to restrict recursive submodule initialization from an untrusted repository or for programs which feed potentially-untrusted URLS to git commands. See git-config(1) for more details. GIT_PROTOCOL For internal use only. Used in handshaking the wire protocol. Contains a colon : separated list of keys with optional values key[=value]. Presence of unknown keys and values must be ignored. Note that servers may need to be configured to allow this variable to pass over some transports. It will be propagated automatically when accessing local repositories (i.e., file:// or a filesystem path), as well as over the git:// protocol. For git-over-http, it should work automatically in most configurations, but see the discussion in git-http-backend(1). For git-over-ssh, the ssh server may need to be configured to allow clients to pass this variable (e.g., by using AcceptEnv GIT_PROTOCOL with OpenSSH). This configuration is optional. If the variable is not propagated, then clients will fall back to the original "v0" protocol (but may miss out on some performance improvements or features). This variable currently only affects clones and fetches; it is not yet used for pushes (but may be in the future). GIT_OPTIONAL_LOCKS If this Boolean environment variable is set to false, Git will complete any requested operation without performing any optional sub-operations that require taking a lock. For example, this will prevent git status from refreshing the index as a side effect. This is useful for processes running in the background which do not want to cause lock contention with other operations on the repository. Defaults to 1. GIT_REDIRECT_STDIN, GIT_REDIRECT_STDOUT, GIT_REDIRECT_STDERR Windows-only: allow redirecting the standard input/output/error handles to paths specified by the environment variables. This is particularly useful in multi-threaded applications where the canonical way to pass standard handles via CreateProcess() is not an option because it would require the handles to be marked inheritable (and consequently every spawned process would inherit them, possibly blocking regular Git operations). The primary intended use case is to use named pipes for communication (e.g. \\.\pipe\my-git-stdin-123). Two special values are supported: off will simply close the corresponding standard handle, and if GIT_REDIRECT_STDERR is 2>&1, standard error will be redirected to the same handle as standard output. GIT_PRINT_SHA1_ELLIPSIS (deprecated) If set to yes, print an ellipsis following an (abbreviated) SHA-1 value. This affects indications of detached HEADs (git-checkout(1)) and the raw diff output (git-diff(1)). Printing an ellipsis in the cases mentioned is no longer considered adequate and support for it is likely to be removed in the foreseeable future (along with the variable). DISCUSSION More detail on the following is available from the Git concepts chapter of the user-manual[3] and gitcore-tutorial(7). A Git project normally consists of a working directory with a ".git" subdirectory at the top level. The .git directory contains, among other things, a compressed object database representing the complete history of the project, an "index" file which links that history to the current contents of the working tree, and named pointers into that history such as tags and branch heads. The object database contains objects of three main types: blobs, which hold file data; trees, which point to blobs and other trees to build up directory hierarchies; and commits, which each reference a single tree and some number of parent commits. The commit, equivalent to what other systems call a "changeset" or "version", represents a step in the project’s history, and each parent represents an immediately preceding step. Commits with more than one parent represent merges of independent lines of development. All objects are named by the SHA-1 hash of their contents, normally written as a string of 40 hex digits. Such names are globally unique. The entire history leading up to a commit can be vouched for by signing just that commit. A fourth object type, the tag, is provided for this purpose. When first created, objects are stored in individual files, but for efficiency may later be compressed together into "pack files". Named pointers called refs mark interesting points in history. A ref may contain the SHA-1 name of an object or the name of another ref. Refs with names beginning ref/head/ contain the SHA-1 name of the most recent commit (or "head") of a branch under development. SHA-1 names of tags of interest are stored under ref/tags/. A special ref named HEAD contains the name of the currently checked-out branch. The index file is initialized with a list of all paths and, for each path, a blob object and a set of attributes. The blob object represents the contents of the file as of the head of the current branch. The attributes (last modified time, size, etc.) are taken from the corresponding file in the working tree. Subsequent changes to the working tree can be found by comparing these attributes. The index may be updated with new content, and new commits may be created from the content stored in the index. The index is also capable of storing multiple entries (called "stages") for a given pathname. These stages are used to hold the various unmerged version of a file when a merge is in progress. FURTHER DOCUMENTATION See the references in the "description" section to get started using Git. The following is probably more detail than necessary for a first-time user. The Git concepts chapter of the user-manual[3] and gitcore-tutorial(7) both provide introductions to the underlying Git architecture. See gitworkflows(7) for an overview of recommended workflows. See also the howto[4] documents for some useful examples. The internals are documented in the Git API documentation[5]. Users migrating from CVS may also want to read gitcvs-migration(7). AUTHORS Git was started by Linus Torvalds, and is currently maintained by Junio C Hamano. Numerous contributions have come from the Git mailing list <git@vger.kernel.org[6]>. http://www.openhub.net/p/git/contributors/summary gives you a more complete list of contributors. If you have a clone of git.git itself, the output of git-shortlog(1) and git-blame(1) can show you the authors for specific parts of the project. REPORTING BUGS Report bugs to the Git mailing list <git@vger.kernel.org[6]> where the development and maintenance is primarily done. You do not have to be subscribed to the list to send a message there. See the list archive at https://lore.kernel.org/git for previous bug reports and other discussions. Issues which are security relevant should be disclosed privately to the Git Security mailing list <git-security@googlegroups.com[7]>. SEE ALSO gittutorial(7), gittutorial-2(7), giteveryday(7), gitcvs-migration(7), gitglossary(7), gitcore-tutorial(7), gitcli(7), The Git User’s Manual[1], gitworkflows(7) GIT Part of the git(1) suite NOTES 1. Git User’s Manual git-htmldocs/user-manual.html 2. Trace2 documentation git-htmldocs/technical/api-trace2.html 3. Git concepts chapter of the user-manual git-htmldocs/user-manual.html#git-concepts 4. howto git-htmldocs/howto-index.html 5. Git API documentation git-htmldocs/technical/api-index.html 6. git@vger.kernel.org mailto:git@vger.kernel.org 7. git-security@googlegroups.com mailto:git-security@googlegroups.com Git 2.41.0 2023-06-01 GIT(1)
null
tr
The tr utility copies the standard input to the standard output with substitution or deletion of selected characters. The following options are available: -C Complement the set of characters in string1, that is “-C ab” includes every character except for ‘a’ and ‘b’. -c Same as -C but complement the set of values in string1. -d Delete characters in string1 from the input. -s Squeeze 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. -u Guarantee that any output is unbuffered. 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 <alert character> \b <backspace> \f <form-feed> \n <newline> \r <carriage return> \t <tab> \v <vertical tab> A backslash followed by any other character maps to that character. c-c For non-octal range endpoints represents the range of characters between the range endpoints, inclusive, in ascending order, as defined by the collation sequence. If either or both of the range endpoints are octal sequences, it represents the range of specific coded values between the range endpoints, inclusive. See the COMPATIBILITY section below for an important note regarding differences in the way the current implementation interprets range expressions differently from previous implementations. [:class:] Represents all characters belonging to the defined character class. Class names are: alnum <alphanumeric characters> alpha <alphabetic characters> blank <whitespace characters> cntrl <control characters> digit <numeric characters> graph <graphic characters> ideogram <ideographic characters> lower <lower-case alphabetic characters> phonogram <phonographic characters> print <printable characters> punct <punctuation characters> rune <valid characters> space <space characters> special <special characters> upper <upper-case characters> xdigit <hexadecimal characters> When “[:lower:]” appears in string1 and “[:upper:]” appears in the same relative position in string2, it represents the characters pairs from the toupper mapping in the LC_CTYPE category of the current locale. When “[:upper:]” appears in string1 and “[:lower:]” appears in the same relative position in string2, it represents the characters pairs from the tolower mapping in the LC_CTYPE category of the current locale. With the exception of case conversion, characters in the classes are in unspecified 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 belonging to the same equivalence class as equiv, ordered by their encoded values. [#*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, it is interpreted as a decimal value. ENVIRONMENT The LANG, LC_ALL, LC_CTYPE and LC_COLLATE environment variables affect the execution of tr as described in environ(7). EXIT STATUS The tr utility exits 0 on success, and >0 if an error occurs.
tr – translate characters
tr [-Ccsu] string1 string2 tr [-Ccu] -d string1 tr [-Ccu] -s string1 tr [-Ccu] -ds string1 string2
null
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 (This should be preferred over the traditional UNIX idiom of “tr a-z A-Z”, since it works correctly in all locales.) Strip out non-printable characters from file1. tr -cd "[:print:]" < file1 Remove diacritical marks from all accented variants of the letter ‘e’: tr "[=e=]" "e" COMPATIBILITY Previous FreeBSD implementations of tr did not order characters in range expressions according to the current locale's collation order, making it possible to convert unaccented Latin characters (esp. as found in English text) from upper to lower case using the traditional UNIX idiom of “tr A-Z a-z”. Since tr now obeys the locale's collation order, this idiom may not produce correct results when there is not a 1:1 mapping between lower and upper case, or when the order of characters within the two cases differs. As noted in the EXAMPLES section above, the character class expressions “[:lower:]” and “[:upper:]” should be used instead of explicit character ranges like “a-z” and “A-Z”. “[=equiv=]” expression and collation for ranges are implemented for single byte locales only. 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-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 a 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 NUL's 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 conforms to IEEE Std 1003.1-2001 (“POSIX.1”). The “ideogram”, “phonogram”, “rune”, and “special” character classes are extensions. 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. The -u option is an extension to the IEEE Std 1003.1-2001 (“POSIX.1”) standard. macOS 14.5 October 13, 2006 macOS 14.5
banner
Banner prints a large, high quality banner on the standard output. If the message is omitted, it prompts for and reads one line of its standard input. The output should be printed on paper of the appropriate width, with no breaks between the pages. The following options are available: -d Enable debug. -t Enable trace. -w width Change the output from a width of 132 to width, suitable for a narrow terminal. HISTORY The banner utility first appeared in AT&T UNIX 6. AUTHORS Mark Horton BUGS Several ASCII characters are not defined, notably <, >, [, ], \, ^, _, {, }, |, and ~. Also, the characters ", ', and & are funny looking (but in a useful way.) The -w option is implemented by skipping some rows and columns. The smaller it gets, the grainier the output. Sometimes it runs letters together. Messages are limited to 1024 characters in length. macOS 14.5 June 21, 2021 macOS 14.5
banner – print large banner on printer
banner [-d] [-t] [-w width] message ...
null
null
leave
The leave utility waits until the specified time, then reminds you that you have to leave. You are reminded 5 minutes and 1 minute before the actual time, at the time, and every minute thereafter. When you log off, leave exits just before it would have printed the next message. The following options are available: hhmm The time of day is in the form hhmm where hh is a time in hours (on a 12 or 24 hour clock), and mm are minutes. All times are converted to a 12 hour clock, and assumed to be in the next 12 hours. + If the time is preceded by ‘+’, the alarm will go off in hours and minutes from the current time. If no argument is given, leave prompts with "When do you have to leave?". A reply of newline causes leave to exit, otherwise the reply is assumed to be a time. This form is suitable for inclusion in a .login or .profile. To get rid of leave you should either log off or use ‘kill -s KILL’ giving its process id. SEE ALSO calendar(1) HISTORY The leave command appeared in 3.0BSD. macOS 14.5 April 28, 1995 macOS 14.5
leave – remind you when you have to leave
leave [[+]hhmm]
null
null
jconsole
The jconsole command starts a graphical console tool that lets you monitor and manage Java applications and virtual machines on a local or remote machine. On Windows, the jconsole command doesn't associate with a console window. It does, however, display a dialog box with error information when the jconsole command fails. JDK 22 2024 JCONSOLE(1)
jconsole - start a graphical console to monitor and manage Java applications
jconsole [-interval=n] [-notile] [-plugin path] [-version] [connection ... ] [-Jinput_arguments] jconsole -help
-interval Sets the update interval to n seconds (default is 4 seconds). -notile Doesn't tile the windows for two or more connections. -pluginpath path Specifies the path that jconsole uses to look up plug-ins. The plug-in path should contain a provider-configuration file named META-INF/services/com.sun.tools.jconsole.JConsolePlugin that contains one line for each plug-in. The line specifies the fully qualified class name of the class implementing the com.sun.tools.jconsole.JConsolePlugin class. -version Prints the program version. connection = pid | host:port | jmxURL A connection is described by either pid, host:port or jmxURL. • The pid value is the process ID of a target process. The JVM must be running with the same user ID as the user ID running the jconsole command. • The host:port values are the name of the host system on which the JVM is running, and the port number specified by the system property com.sun.management.jmxremote.port when the JVM was started. • The jmxUrl value is the address of the JMX agent to be connected to as described in JMXServiceURL. -Jinput_arguments Passes input_arguments to the JVM on which the jconsole command is run. -help or --help Displays the help message for the command.
null
paste
The paste utility concatenates the corresponding lines of the given input files, replacing all but the last file's newline characters with a single tab character, and writes the resulting lines to standard output. If end-of-file 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 newline character \t tab character \\ backslash character \0 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 ‘-’. EXIT STATUS The paste utility exits 0 on success, and >0 if an error occurs.
paste – merge corresponding or subsequent lines of files
paste [-s] [-d list] file ...
null
List the files in the current directory in three columns: ls | paste - - - Combine pairs of lines from a file into single lines: paste -s -d '\t\n' myfile Number the lines in a file, similar to nl(1): sed = myfile | paste - - Create a colon-separated list of directories named bin, suitable for use in the PATH environment variable: find / -name bin -type d | paste -s -d : - SEE ALSO cut(1), lam(1) STANDARDS The paste utility is expected to be IEEE Std 1003.2 (“POSIX.2”) compatible. HISTORY A paste command appeared in Version 7 AT&T UNIX/32V. macOS 14.5 June 25, 2004 macOS 14.5
bzip2
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. 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 can't 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.
bzip2, bunzip2 - a block-sorting file compressor, v1.0.8 bzcat - decompresses files to stdout bzip2recover - recovers data from damaged bzip2 files
bzip2 [ -cdfkqstvzVL123456789 ] [ filenames ... ] bunzip2 [ -fkvsVL ] [ filenames ... ] bzcat [ -s ] [ filenames ... ] bzip2recover filename
-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 invocation name. -t --test Check integrity of the specified file(s), but don't 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 wouldn't do. bzip2 normally declines to decompress files which don't have the correct magic header bytes. If forced (-f), however, it will pass such files through unmodified. This is how GNU gzip behaves. -k --keep Keep (don't 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. -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 -v's 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 (or --fast) to -9 (or --best) Set the block size to 100 k, 200 k .. 900 k when compressing. Has no effect when decompressing. See MEMORY MANAGEMENT below. The --fast and --best aliases are primarily for GNU gzip compatibility. In particular, --fast doesn't make things significantly faster. And --best merely selects the default behaviour. -- 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 you'd 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. 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 1200k 500k 350k 914704 -2 2000k 900k 600k 877703 -3 2800k 1300k 850k 860338 -4 3600k 1700k 1100k 846899 -5 4400k 2100k 1350k 845160 -6 5200k 2500k 1600k 838626 -7 6100k 2900k 1850k 834096 -8 6800k 3300k 2100k 828642 -9 7600k 3700k 2350k 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 "rec00001file.bz2", "rec00002file.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" -- processes 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 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.8 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, 0.9.5, 1.0.0, 1.0.1, 1.0.2 and above, 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 versions prior to 1.0.2 used 32-bit integers to represent bit positions in compressed files, so they could not handle compressed files more than 512 megabytes long. Versions 1.0.2 and above use 64-bit ints on some platforms which support them (GNU supported targets, and Windows). To establish whether or not bzip2recover was built with such a limitation, run it without arguments. In any event you can build yourself an unlimited version if you can recompile it with MaybeUInt64 set to be an unsigned 64-bit integer. AUTHOR Julian Seward, jseward@acm.org. https://sourceware.org/bzip2/ 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. Donna Robinson XMLised the documentation. The bz* scripts are derived from those of GNU gzip. Many people sent patches, helped with portability problems, lent machines, gave advice and were generally helpful. bzip2(1)
null
uucp
The uucp command copies files between systems. Each file argument is either a pathname on the local machine or is of the form system!path which is interpreted as being on a remote system. In the first form, the contents of the first file are copied to the second. In the second form, each source file is copied into the destination directory. A file be transferred to or from system2 via system1 by using system1!system2!path. Any pathname that does not begin with / or ~ will be appended to the current directory (unless the -W or --noexpand option is used); this resulting path will not necessarily exist on a remote system. A pathname beginning with a simple ~ starts at the UUCP public directory; a pathname beginning with ~name starts at the home directory of the named user. The ~ is interpreted on the appropriate system. Note that some shells will interpret a simple ~ to the local home directory before uucp sees it; to avoid this the ~ must be quoted. Shell metacharacters ? * [ ] are interpreted on the appropriate system, assuming they are quoted to prevent the shell from interpreting them first. The copy does not take place immediately, but is queued up for the uucico (8) daemon; the daemon is started immediately unless the -r or --nouucico switch is given. In any case, the next time the remote system is called the file(s) will be copied.
uucp - Unix to Unix copy
uucp [ options ] source-file destination-file uucp [ options ] source-file... destination-directory
The following options may be given to uucp. -c, --nocopy Do not copy local source files to the spool directory. If they are removed before being processed by the uucico (8) daemon, the copy will fail. The files must be readable by the uucico (8) daemon, and by the invoking user. -C, --copy Copy local source files to the spool directory. This is the default. -d, --directories Create all necessary directories when doing the copy. This is the default. -f, --nodirectories If any necessary directories do not exist for the destination path, abort the copy. -R, --recursive If any of the source file names are directories, copy their contents recursively to the destination (which must itself be a directory). -g grade, --grade grade Set the grade of the file transfer command. Jobs of a higher grade are executed first. Grades run 0 ... 9 A ... Z a ... z from high to low. -m, --mail Report completion or failure of the file transfer by mail (1). -n user, --notify user Report completion or failure of the file transfer by mail (1) to the named user on the remote system. -r, --nouucico Do not start uucico (8) daemon immediately; merely queue up the file transfer for later execution. -j, --jobid Print jobid on standard output. The job may be later cancelled by passing the jobid to the -k switch of uustat (1). It is possible for some complex operations to produce more than one jobid, in which case each will be printed on a separate line. For example uucp sys1!~user1/file1 sys2!~user2/file2 ~user3 will generate two separate jobs, one for the system sys1 and one for the system sys2. -W, --noexpand Do not prepend remote relative path names with the current directory. -t, --uuto This option is used by the uuto shell script. It causes uucp to interpret the final argument as system!user. The file(s) are sent to ~/receive/USER/LOCAL on the remote system, where USER is from the final argument and LOCAL is the local UUCP system name. Also, uucp will act as though --notify user were specified. -x type, --debug type Turn on particular debugging types. The following types are recognized: abnormal, chat, handshake, uucp-proto, proto, port, config, spooldir, execute, incoming, outgoing. Only abnormal, config, spooldir and execute are meaningful for uucp. Multiple types may be given, separated by commas, and the --debug option may appear multiple times. A number may also be given, which will turn on that many types from the foregoing list; for example, --debug 2 is equivalent to --debug abnormal,chat. -I file, --config file Set configuration file to use. This option may not be available, depending upon how uucp was compiled. -v, --version Report version information and exit. --help Print a help message and exit. SEE ALSO mail(1), uux(1), uustat(1), uucico(8) BUGS Some of the options are dependent on the capabilities of the uucico (8) daemon on the remote system. The -n and -m switches do not work when transferring a file from one remote system to another. File modes are not preserved, except for the execute bit. The resulting file is owned by the uucp user. AUTHOR Ian Lance Taylor <ian@airs.com> Taylor UUCP 1.07 uucp(1)
null
passwd
Every cmd listed above is a (sub-)command of the openssl(1) application. It has its own detailed manual page at openssl-cmd(1). For example, to view the manual page for the openssl dgst command, type "man openssl-dgst".
asn1parse, ca, ciphers, cmp, cms, crl, crl2pkcs7, dgst, dhparam, dsa, dsaparam, ec, ecparam, enc, engine, errstr, gendsa, genpkey, genrsa, info, kdf, mac, nseq, ocsp, passwd, pkcs12, pkcs7, pkcs8, pkey, pkeyparam, pkeyutl, prime, rand, rehash, req, rsa, rsautl, s_client, s_server, s_time, sess_id, smime, speed, spkac, srp, storeutl, ts, verify, version, x509 - OpenSSL application commands
openssl cmd -help | [-option | -option arg] ... [arg] ...
Among others, every subcommand has a help option. -help Print out a usage message for the subcommand. SEE ALSO openssl(1), openssl-asn1parse(1), openssl-ca(1), openssl-ciphers(1), openssl-cmp(1), openssl-cms(1), openssl-crl(1), openssl-crl2pkcs7(1), openssl-dgst(1), openssl-dhparam(1), openssl-dsa(1), openssl-dsaparam(1), openssl-ec(1), openssl-ecparam(1), openssl-enc(1), openssl-engine(1), openssl-errstr(1), openssl-gendsa(1), openssl-genpkey(1), openssl-genrsa(1), openssl-info(1), openssl-kdf(1), openssl-mac(1), openssl-nseq(1), openssl-ocsp(1), openssl-passwd(1), openssl-pkcs12(1), openssl-pkcs7(1), openssl-pkcs8(1), openssl-pkey(1), openssl-pkeyparam(1), openssl-pkeyutl(1), openssl-prime(1), openssl-rand(1), openssl-rehash(1), openssl-req(1), openssl-rsa(1), openssl-rsautl(1), openssl-s_client(1), openssl-s_server(1), openssl-s_time(1), openssl-sess_id(1), openssl-smime(1), openssl-speed(1), openssl-spkac(1), openssl-srp(1), openssl-storeutl(1), openssl-ts(1), openssl-verify(1), openssl-version(1), openssl-x509(1), HISTORY Initially, the manual page entry for the "openssl cmd" command used to be available at cmd(1). Later, the alias openssl-cmd(1) was introduced, which made it easier to group the openssl commands using the apropos(1) command or the shell's tab completion. In order to reduce cluttering of the global manual page namespace, the manual page entries without the 'openssl-' prefix have been deprecated in OpenSSL 3.0 and will be removed in OpenSSL 4.0. COPYRIGHT Copyright 2019-2020 The OpenSSL Project Authors. All Rights Reserved. Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at <https://www.openssl.org/source/license.html>. 3.3.1 2024-06-04 OPENSSL-CMDS(1ssl)
null
moose-outdated5.34
null
null
null
null
null
macerror5.30
The macerror script translates Mac error numbers into their symbolic name and description. SEE ALSO Mac::Errors AUTHOR Chris Nandor, pudge@pobox.com COPYRIGHT Copryright 2002, Chris Nandor, All rights reserved You may use this under the same terms as Perl itself. perl v5.30.3 2018-06-20 MACERROR(1)
macerror
% macerror -23
null
null
uuidgen
The uuidgen command generates a Universally Unique IDentifier (UUID), a 128-bit value guaranteed to be unique over both space and time. The following options are available: -hdr Emit CoreFoundation CFUUID-based source code for using the uuid in a header. RETURN VALUE The UUID is printed to standard output as a hyphen-punctuated ASCII string of the form: EEF45689-BBE5-4FB6-9E80-41B78F6578E2 (in printf(3) format "%08X-%04X-%04X-%04X-%012X"), unless the -hdr option is given, in which case a fragment of source code is output. Mac OS X July 1, 2005 Mac OS X
uuidgen – generates new UUID strings
uuidgen [-hdr]
null
null
install_name_tool
Install_name_tool changes the dynamic shared library install names and or adds, changes or deletes the rpaths recorded in a Mach-O binary. For this tool to work when the install names or rpaths are larger the binary should be built with the ld(1) -headerpad_max_install_names option. -change old new Changes the dependent shared library install name old to new in the specified Mach-O binary. More than one of these options can be specified. If the Mach-O binary does not contain the old install name in a specified -change option the option is ignored. -id name Changes the shared library identification name of a dynamic shared library to name. If the Mach-O binary is not a dynamic shared library and the -id option is specified it is ignored. -rpath old new Changes the rpath path name old to new in the specified Mach-O binary. More than one of these options can be specified. If the Mach-O binary does not contain the old rpath path name in a specified -rpath it is an error. -add_rpath new Adds the rpath path name new in the specified Mach-O binary. More than one of these options can be specified. If the Mach-O binary already contains the new rpath path name specified in -add_rpath it is an error. -delete_rpath old deletes the rpath path name old in the specified Mach-O binary. More than one of these options can be specified. If the Mach-O binary does not contains the old rpath path name specified in -delete_rpath it is an error. SEE ALSO ld(1) Apple, Inc. March 4, 2009 INSTALL_NAME_TOOL(1)
install_name_tool - change dynamic shared library install names
install_name_tool [-change old new ] ... [-rpath old new ] ... [-add_rpath new ] ... [-delete_rpath new ] ... [-id name] file
null
null
cmpdylib
cmpdylib compares two versions of a dynamic shared library to see if they are compatible with each other. If the two versions are incompatible, the reason is printed to stdout, and the exit status is nonzero. If they are compatible, nothing is printed, and the exit status is zero. To see if the two versions are compatible, cmpdylib first verifies that newLibrary was built for all of the architectures that oldLibrary was built for. If so, for each architecture, it checks to see if the global symbols defined in oldLibrary are still defined in newLibrary. It then looks for new symbols, symbols defined in newLibrary that are not defined in oldLibrary. If it finds new symbols, it compares the compatibility version numbers of the two libraries. If the compatibility version number of newLibrary is greater than oldLibrary, the libraries are still compatible. If the compatibility version number is the same or less, the libraries are incompatible.
cmpdylib - compare two dynamic shared libraries for compatibility
cmpdylib oldLibrary newLibrary
oldLibrary The older version of the library. newLibrary The newer version of the library.
This example shows the result of performing cmpdylib on two incompatible versions of the Foundation library. As stated, the versions are incompatible because the newer version was not built for the ppc architecture. cmpdylib /System/Library/Frameworks/Foundation.framework/Foundation Foundation_proj/Foundation cmpdylib: file: Foundation_proj/Foundation does not contain architecture: ppc cmpdylib: new dynamic shared library: Foundation_proj/Foundation does not contain architecture ppc DIAGNOSTICS The exit status is zero if the library versions are compatible and nonzero if they are incompatible. BUGS There are lots of other things that could be checked for that are not (such as the Objective C API). Apple Computer, Inc. November 3, 1997 CMPDYLIB(1)
pod2text5.34
pod2text is a front-end for Pod::Text and its subclasses. It uses them to generate formatted ASCII text from POD source. It can optionally use either termcap sequences or ANSI color escape sequences to format the text. input is the file to read for POD source (the POD can be embedded in code). If input isn't given, it defaults to "STDIN". output, if given, is the file to which to write the formatted output. If output isn't given, the formatted output is written to "STDOUT". Several POD files can be processed in the same pod2text invocation (saving module load and compile times) by providing multiple pairs of input and output files on the command line.
pod2text - Convert POD data to formatted ASCII text
pod2text [-aclostu] [--code] [--errors=style] [-i indent] [-q quotes] [--nourls] [--stderr] [-w width] [input [output ...]] pod2text -h
-a, --alt Use an alternate output format that, among other things, uses a different heading style and marks "=item" entries with a colon in the left margin. --code Include any non-POD text from the input file in the output as well. Useful for viewing code documented with POD blocks with the POD rendered and the code left intact. -c, --color Format the output with ANSI color escape sequences. Using this option requires that Term::ANSIColor be installed on your system. --errors=style Set the error handling style. "die" says to throw an exception on any POD formatting error. "stderr" says to report errors on standard error, but not to throw an exception. "pod" says to include a POD ERRORS section in the resulting documentation summarizing the errors. "none" ignores POD errors entirely, as much as possible. The default is "die". -i indent, --indent=indent Set the number of spaces to indent regular text, and the default indentation for "=over" blocks. Defaults to 4 spaces if this option isn't given. -h, --help Print out usage information and exit. -l, --loose Print a blank line after a "=head1" heading. Normally, no blank line is printed after "=head1", although one is still printed after "=head2", because this is the expected formatting for manual pages; if you're formatting arbitrary text documents, using this option is recommended. -m width, --left-margin=width, --margin=width The width of the left margin in spaces. Defaults to 0. This is the margin for all text, including headings, not the amount by which regular text is indented; for the latter, see -i option. --nourls Normally, L<> formatting codes with a URL but anchor text are formatted to show both the anchor text and the URL. In other words: L<foo|http://example.com/> is formatted as: foo <http://example.com/> This flag, if given, suppresses the URL when anchor text is given, so this example would be formatted as just "foo". This can produce less cluttered output in cases where the URLs are not particularly important. -o, --overstrike Format the output with overstrike printing. Bold text is rendered as character, backspace, character. Italics and file names are rendered as underscore, backspace, character. Many pagers, such as less, know how to convert this to bold or underlined text. -q quotes, --quotes=quotes Sets the quote marks used to surround C<> text to quotes. If quotes is a single character, it is used as both the left and right quote. Otherwise, it is split in half, and the first half of the string is used as the left quote and the second is used as the right quote. quotes may also be set to the special value "none", in which case no quote marks are added around C<> text. -s, --sentence Assume each sentence ends with two spaces and try to preserve that spacing. Without this option, all consecutive whitespace in non- verbatim paragraphs is compressed into a single space. --stderr By default, pod2text dies if any errors are detected in the POD input. If --stderr is given and no --errors flag is present, errors are sent to standard error, but pod2text does not abort. This is equivalent to "--errors=stderr" and is supported for backward compatibility. -t, --termcap Try to determine the width of the screen and the bold and underline sequences for the terminal from termcap, and use that information in formatting the output. Output will be wrapped at two columns less than the width of your terminal device. Using this option requires that your system have a termcap file somewhere where Term::Cap can find it and requires that your system support termios. With this option, the output of pod2text will contain terminal control sequences for your current terminal type. -u, --utf8 By default, pod2text tries to use the same output encoding as its input encoding (to be backward-compatible with older versions). This option says to instead force the output encoding to UTF-8. Be aware that, when using this option, the input encoding of your POD source should be properly declared unless it's US-ASCII. Pod::Simple will attempt to guess the encoding and may be successful if it's Latin-1 or UTF-8, but it will warn, which by default results in a pod2text failure. Use the "=encoding" command to declare the encoding. See perlpod(1) for more information. -w, --width=width, -width The column at which to wrap text on the right-hand side. Defaults to 76, unless -t is given, in which case it's two columns less than the width of your terminal device. EXIT STATUS As long as all documents processed result in some output, even if that output includes errata (a "POD ERRORS" section generated with "--errors=pod"), pod2text will exit with status 0. If any of the documents being processed do not result in an output document, pod2text will exit with status 1. If there are syntax errors in a POD document being processed and the error handling style is set to the default of "die", pod2text will abort immediately with exit status 255. DIAGNOSTICS If pod2text fails with errors, see Pod::Text and Pod::Simple for information about what those errors might mean. Internally, it can also produce the following diagnostics: -c (--color) requires Term::ANSIColor be installed (F) -c or --color were given, but Term::ANSIColor could not be loaded. Unknown option: %s (F) An unknown command line option was given. In addition, other Getopt::Long error messages may result from invalid command-line options. ENVIRONMENT COLUMNS If -t is given, pod2text will take the current width of your screen from this environment variable, if available. It overrides terminal width information in TERMCAP. TERMCAP If -t is given, pod2text will use the contents of this environment variable if available to determine the correct formatting sequences for your current terminal device. AUTHOR Russ Allbery <rra@cpan.org>. COPYRIGHT AND LICENSE Copyright 1999-2001, 2004, 2006, 2008, 2010, 2012-2019 Russ Allbery <rra@cpan.org> This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. SEE ALSO Pod::Text, Pod::Text::Color, Pod::Text::Overstrike, Pod::Text::Termcap, Pod::Simple, perlpod(1) The current version of this script is always available from its web site at <https://www.eyrie.org/~eagle/software/podlators/>. It is also part of the Perl core distribution as of 5.6.0. perl v5.34.1 2024-04-13 POD2TEXT(1)
null
zfgrep
The grep utility searches any given input files, selecting lines that match one or more patterns. By default, a pattern matches an input line if the 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. grep is used for simple patterns and basic regular expressions (BREs); egrep can handle extended regular expressions (EREs). See re_format(7) for more information on regular expressions. fgrep is quicker than both grep and egrep, but can only handle fixed patterns (i.e., it does not interpret regular expressions). Patterns may consist of one or more lines, allowing any of the pattern lines to match a portion of the input. zgrep, zegrep, and zfgrep act like grep, egrep, and fgrep, respectively, but accept input files compressed with the compress(1) or gzip(1) compression utilities. bzgrep, bzegrep, and bzfgrep act like grep, egrep, and fgrep, respectively, but accept input files compressed with the bzip2(1) compression utility. The following options are available: -A num, --after-context=num Print num lines of trailing context after each match. See also the -B and -C options. -a, --text Treat all files as ASCII text. Normally grep will simply print “Binary file ... matches” if files contain binary characters. Use of this option forces grep to output lines matching the specified pattern. -B num, --before-context=num Print num lines of leading context before each match. See also the -A and -C options. -b, --byte-offset The offset in bytes of a matched pattern is displayed in front of the respective matched line. -C num, --context=num Print num lines of leading and trailing context surrounding each match. See also the -A and -B options. -c, --count Only a count of selected lines is written to standard output. --colour=[when], --color=[when] Mark up the matching text with the expression stored in the GREP_COLOR environment variable. The possible values of when are “never”, “always” and “auto”. -D action, --devices=action Specify the demanded action for devices, FIFOs and sockets. The default action is “read”, which means, that they are read as if they were normal files. If the action is set to “skip”, devices are silently skipped. -d action, --directories=action Specify the demanded action for directories. It is “read” by default, which means that the directories are read in the same manner as normal files. Other possible values are “skip” to silently ignore the directories, and “recurse” to read them recursively, which has the same effect as the -R and -r option. -E, --extended-regexp Interpret pattern as an extended regular expression (i.e., force grep to behave as egrep). -e pattern, --regexp=pattern Specify a pattern used during the search of the input: an input line is selected if it matches any of the specified patterns. This option is most useful when multiple -e options are used to specify multiple patterns, or when a pattern begins with a dash (‘-’). --exclude pattern If specified, it excludes files matching the given filename pattern from the search. Note that --exclude and --include patterns are processed in the order given. If a name matches multiple patterns, the latest matching rule wins. If no --include pattern is specified, all files are searched that are not excluded. Patterns are matched to the full path specified, not only to the filename component. --exclude-dir pattern If -R is specified, it excludes directories matching the given filename pattern from the search. Note that --exclude-dir and --include-dir patterns are processed in the order given. If a name matches multiple patterns, the latest matching rule wins. If no --include-dir pattern is specified, all directories are searched that are not excluded. -F, --fixed-strings Interpret pattern as a set of fixed strings (i.e., force grep to behave as fgrep). -f file, --file=file Read one or more newline separated patterns from file. Empty pattern lines match every input line. Newlines are not considered part of a pattern. If file is empty, nothing is matched. -G, --basic-regexp Interpret pattern as a basic regular expression (i.e., force grep to behave as traditional grep). -H Always print filename headers with output lines. -h, --no-filename Never print filename headers (i.e., filenames) with output lines. --help Print a brief help message. -I Ignore binary files. This option is equivalent to the “--binary-files=without-match” option. -i, --ignore-case Perform case insensitive matching. By default, grep is case sensitive. --include pattern If specified, only files matching the given filename pattern are searched. Note that --include and --exclude patterns are processed in the order given. If a name matches multiple patterns, the latest matching rule wins. Patterns are matched to the full path specified, not only to the filename component. --include-dir pattern If -R is specified, only directories matching the given filename pattern are searched. Note that --include-dir and --exclude-dir patterns are processed in the order given. If a name matches multiple patterns, the latest matching rule wins. -J, --bz2decompress Decompress the bzip2(1) compressed file before looking for the text. -L, --files-without-match Only the names of files not containing selected lines are written to standard output. Pathnames are listed once per file searched. If the standard input is searched, the string “(standard input)” is written unless a --label is specified. -l, --files-with-matches Only the names of files containing selected lines are written to standard output. grep will only search a file until a match has been found, making searches potentially less expensive. Pathnames are listed once per file searched. If the standard input is searched, the string “(standard input)” is written unless a --label is specified. --label Label to use in place of “(standard input)” for a file name where a file name would normally be printed. This option applies to -H, -L, and -l. --mmap Use mmap(2) instead of read(2) to read input, which can result in better performance under some circumstances but can cause undefined behaviour. -M, --lzma Decompress the LZMA compressed file before looking for the text. -m num, --max-count=num Stop reading the file after num matches. -n, --line-number Each output line is preceded by its relative line number in the file, starting at line 1. The line number counter is reset for each file processed. This option is ignored if -c, -L, -l, or -q is specified. --null Prints a zero-byte after the file name. -O If -R is specified, follow symbolic links only if they were explicitly listed on the command line. The default is not to follow symbolic links. -o, --only-matching Prints only the matching part of the lines. -p If -R is specified, no symbolic links are followed. This is the default. -q, --quiet, --silent Quiet mode: suppress normal output. grep will only search a file until a match has been found, making searches potentially less expensive. -R, -r, --recursive Recursively search subdirectories listed. (i.e., force grep to behave as rgrep). -S If -R is specified, all symbolic links are followed. The default is not to follow symbolic links. -s, --no-messages Silent mode. Nonexistent and unreadable files are ignored (i.e., their error messages are suppressed). -U, --binary Search binary files, but do not attempt to print them. -u This option has no effect and is provided only for compatibility with GNU grep. -V, --version Display version information and exit. -v, --invert-match Selected lines are those not matching any of the specified patterns. -w, --word-regexp The expression is searched for as a word (as if surrounded by ‘[[:<:]]’ and ‘[[:>:]]’; see re_format(7)). This option has no effect if -x is also specified. -x, --line-regexp Only input lines selected against an entire fixed string or regular expression are considered to be matching lines. -y Equivalent to -i. Obsoleted. -z, --null-data Treat input and output data as sequences of lines terminated by a zero-byte instead of a newline. -X, --xz Decompress the xz(1) compressed file before looking for the text. -Z, --decompress Force grep to behave as zgrep. --binary-files=value Controls searching and printing of binary files. Options are: binary (default) Search binary files but do not print them. without-match Do not search binary files. text Treat all files as text. --line-buffered Force output to be line buffered. By default, output is line buffered when standard output is a terminal and block buffered otherwise. If no file arguments are specified, the standard input is used. Additionally, “-” may be used in place of a file name, anywhere that a file name is accepted, to read from standard input. This includes both -f and file arguments. ENVIRONMENT GREP_OPTIONS May be used to specify default options that will be placed at the beginning of the argument list. Backslash-escaping is not supported, unlike the behavior in GNU grep. EXIT STATUS The grep utility exits with one of the following values: 0 One or more lines were selected. 1 No lines were selected. >1 An error occurred.
grep, egrep, fgrep, rgrep, bzgrep, bzegrep, bzfgrep, zgrep, zegrep, zfgrep – file pattern searcher
grep [-abcdDEFGHhIiJLlMmnOopqRSsUVvwXxZz] [-A num] [-B num] [-C num] [-e pattern] [-f file] [--binary-files=value] [--color[=when]] [--colour[=when]] [--context=num] [--label] [--line-buffered] [--null] [pattern] [file ...]
null
- Find all occurrences of the pattern ‘patricia’ in a file: $ grep 'patricia' myfile - Same as above but looking only for complete words: $ grep -w 'patricia' myfile - Count occurrences of the exact pattern ‘FOO’ : $ grep -c FOO myfile - Same as above but ignoring case: $ grep -c -i FOO myfile - Find all occurrences of the pattern ‘.Pp’ at the beginning of a line: $ grep '^\.Pp' myfile The apostrophes ensure the entire expression is evaluated by grep instead of by the user's shell. The caret ‘^’ matches the null string at the beginning of a line, and the ‘\’ escapes the ‘.’, which would otherwise match any character. - Find all lines in a file which do not contain the words ‘foo’ or ‘bar’: $ grep -v -e 'foo' -e 'bar' myfile - Peruse the file ‘calendar’ looking for either 19, 20, or 25 using extended regular expressions: $ egrep '19|20|25' calendar - Show matching lines and the name of the ‘*.h’ files which contain the pattern ‘FIXME’. Do the search recursively from the /usr/src/sys/arm directory $ grep -H -R FIXME --include="*.h" /usr/src/sys/arm/ - Same as above but show only the name of the matching file: $ grep -l -R FIXME --include="*.h" /usr/src/sys/arm/ - Show lines containing the text ‘foo’. The matching part of the output is colored and every line is prefixed with the line number and the offset in the file for those lines that matched. $ grep -b --colour -n foo myfile - Show lines that match the extended regular expression patterns read from the standard input: $ echo -e 'Free\nBSD\nAll.*reserved' | grep -E -f - myfile - Show lines from the output of the pciconf(8) command matching the specified extended regular expression along with three lines of leading context and one line of trailing context: $ pciconf -lv | grep -B3 -A1 -E 'class.*=.*storage' - Suppress any output and use the exit status to show an appropriate message: $ grep -q foo myfile && echo File matches SEE ALSO bzip2(1), compress(1), ed(1), ex(1), gzip(1), sed(1), xz(1), zgrep(1), re_format(7) STANDARDS The grep utility is compliant with the IEEE Std 1003.1-2008 (“POSIX.1”) specification. The flags [-AaBbCDdGHhILmopRSUVw] are extensions to that specification, and the behaviour of the -f flag when used with an empty pattern file is left undefined. All long options are provided for compatibility with GNU versions of this utility. Historic versions of the grep utility also supported the flags [-ruy]. This implementation supports those options; however, their use is strongly discouraged. HISTORY The grep command first appeared in Version 6 AT&T UNIX. BUGS The grep utility does not normalize Unicode input, so a pattern containing composed characters will not match decomposed input, and vice versa. macOS 14.5 November 10, 2021 macOS 14.5
aea
aea creates and manipulates Apple Encrypted Archives (AEA) VERBS encrypt Create a new AEA archive decrypt Decrypt an AEA archive sign Sign an AEA archive append Append data to an existing AEA archive id Identify an AEA archive
aea – Manipulate Apple Encrypted Archives
aea command [options]
-v Increase verbosity. Default is silent operation. -h Print usage and exit. -i -input_file Input file. Default is stdin. -o -output_file Output file. Default is stdout. -profile -profile Archive profile, one of the following (both index and id are allowed): - 0: hkdf_sha256_hmac__none__ecdsa_p256 - no encryption, signed - 1: hkdf_sha256_aesctr_hmac__symmetric__none - symmetric key encryption - 2: hkdf_sha256_aesctr_hmac__symmetric__ecdsa_p256 - symmetric key encryption, signed - 3: hkdf_sha256_aesctr_hmac__ecdhe_p256__none - ECDHE encryption - 4: hkdf_sha256_aesctr_hmac__ecdhe_p256__ecdsa_p256 - ECDHE encryption, signed - 5: hkdf_sha256_aesctr_hmac__scrypt__none - scrypt encryption (password based) -a -algorithm Compression algorithm used when creating archives. One of lzfse, lzma, lz4, zlib, copy. Default is lzfse. -b -block_size Block size used for compression+encryption, a number with optional b, k, m, g suffix (bytes are assumed if no suffix is specified). Default is 1m. -t -worker_threads Number of worker threads. Default is the number of physical CPU on the running machine. -checksum -checksum_mode Block checksum mode, one of none, murmur64, sha256. -key -key_file File containing or receiving the symmetric encryption key. -key-value -<key> Symmetric encryption key, encoded either as hex:..., or base64:.... -key-gen When creating a new archive, generate a new random high entropy symmetric key, and store it in the file specified by -key. The new key is stored as hex:... in the file. -password password_file File containing or receiving the encryption password. --password-value -<password> Encryption password. -password-gen When creating a new archive, generate a new random high entropy password, and store it in the file specified by -password. --auth-data-key -<string> Define the key for the next -auth-data or -auth-data-value option. If this option is specified at least once, the auth data blob in the archive will be stored using the key->value format, and all occurrences of fI-auth-data or -auth-data-value must be preceded by a -auth-data-key. --auth-data -data_file Insert the contents of data_file in the container as authentication data. This option can be specified multiple times. Authentication data is stored in plain text in the container, and can be used to store public key certificates for example. --auth-data-value -<data> Insert the contents of data (encoded either as hex:..., or base64:...) in the container as authentication data. This option can be specified multiple times. Authentication data is stored in plain text in the container, and can be used to store public key certificates for example. --sign-pub -key_file File containing the signature public key. Used to decrypt a signed container, or encrypt a container without signing it. --sign-priv -key_file File containing the signature private key. Used to sign a container. --recipient-pub -key_file File containing the recipient public key. Used to encrypt a container in the ECDHE modes. --recipient-priv -key_file File containing the recipient private key. Used to decrypt a container in the ECDHE modes. --master-key -key_file When creating a new container, if this option is given, the file will receive the container main key, needed for future append operations. The main key is only intended to unlock an existing container to append new data, and should be kept by the container creator. --signature-key -key_file When creating an new signed container, if this option is given, the file will receive the signature encryption key. if only the signature public key is passed with -sign-pub when creating a new signed container, the container needs to be signed offline using the sign command. This requires both the signature private key -sign-priv, and this signature encryption key.
Encrypt foo into foo.aea using a new random symmetric key stored in foo.key aea encrypt -profile hkdf_sha256_aesctr_hmac__symmetric__none -i foo -o foo.aea -key foo.key Decrypt foo.aea into bar aea decrypt -i foo.aea -o bar -key foo.key Alice encrypts and signs foo into foo.aea, so only Bob can decrypt it. aea encrypt -profile hkdf_sha256_aesctr_hmac__ecdhe_p256__ecdsa_p256 -i foo -o foo.aea -sign-priv alice.priv -recipient-pub bob.pub Bob decrypts foo.aea into bar using his private key, and at the same time verifying Alice signed it. aea decrypt -i foo.aea -o bar -sign-pub alice.pub -recipient-priv bob.priv macOS April 5, 2020 macOS
snfsdefrag
snfsdefrag is a utility for defragmenting files on a Xsan volume by relocating the data in a file to a smaller set of extents. Reducing the number of extents in a file improves performance by minimizing disk head movement when performing I/O. In addition, with fewer extents, Xsan File System Manager (FSM) overhead is reduced. snfsdefrag can be used to migrate files off of an existing stripe group and on to other storage pools by using the -G option and setting the -m option to 0. If affinities are associated with a file that is being defragmented, new extents are created using the existing file affinity, unless being overridden by the -k option. If the -k option is specified, the files are moved to a stripe group with the specified affinity. Without -k, files are moved to any available stripe group. This migration capability can be especially useful when a storage pool is going out of service. See the use of the -G option in the EXAMPLES section below. In addition to defragmenting and migrating files, snfsdefrag can be used to list the extents in a file (see the -e option) or to prune away unused space that has been preallocated for the file (see the -p option). Note: Free space in a storage pool can also become fragmented. To address this issue, see the sgdefrag command. Note: The snfsdefrag utility is no longer the preferred tool to prepare a storage pool for retirement. Use the sgoffload utility instead.
snfsdefrag - Xsan File System File Defrag Utility
snfsdefrag [-ADdFPqsv] [-G group] [-K key] [-k key] [-g group] [-m count] [-r] [-S file] Target [Target...] snfsdefrag -e [-v] [-b] [-F] [-G group] [-K key] [-r] [-t] [-L] [-S file] Target [Target...] snfsdefrag -E [-v] [-b] [-F] [-G group] [-K key] [-r] [-t] [-L] [-S file] Target [Target...] snfsdefrag -c [-v] [-F] [-G group] [-K key] [-r] [-t] [-T] [-S file] [-A] Target [Target...] snfsdefrag -p [-DPqv] [-F] [-G group] [-K key] [-r] [-S file] [-A] Target [Target...] snfsdefrag -l [-Dv] [-F] [-G group] [-K key] [-m count] [-r] [-S file] [-A] Target [Target...]
-A Do not attempt to temporarily stop I/O on an open file by setting the administrative lock on the file. -b Show extent size in blocks instead of kilobytes. Only useful with the -e and -E (list extents) options. -c This option causes snfsdefrag to just display an extent count instead of defragmenting files. See also the -t and -T options. -D Turns on debug messages. -d Causes snfsdefrag to operate on files containing extents that have depths that are different than the current depth for the extent's storage pool. This option is useful for reclaiming disk space that has become "shadowed" after cvupdatefs has been run for stripe group expansion. Note that when -d is used, a file may be defragmented due to the stripe depth in one or more of its extents OR due to the file's extent count. -e This option causes snfsdefrag to not actually attempt the defragmentation, but instead report the list of extents contained in the file. The extent information includes the starting file relative offset, starting and ending storage pool block addresses, the size of the extent, the depth of the extent, and the storage pool number. See also the -t option. -E This option has the same effect as the -e option except that file relative offsets and starting and ending stripe group block addresses that are stripe-aligned are highlighted with an asterisk (*). Also, starting storage pool addresses that are equally misaligned with the file relative offset are highlighted with a plus sign (+). See also the -t option. -F This option causes snfsdefrag to skip resource forks for file systems on which the namedStreams option is enabled. -G storagepool This option causes snfsdefrag to only operate on files having at least one extent in storagepool, which is the stripe group index. Use "sgmanage --list" to see the stripe group index. Note that multiple -G options can be specified to match files with an extent in at least one of the specified storage pools. -K key This option causes snfsdefrag to only operate on source files that have the supplied affinity key. If key is preceded by '!' then snfsdefrag will only operate on source files that do not have the affinity key. See EXAMPLES below. -k key Forces the new extent for the file to be created on the storage pool specified by key. This option has the side effect of changing or creating the affinity on the affected files. If this is not desired, the cvaffinity command can be used to change or delete the affinity or the -g option can used instead. -g storagepool Places the new extent on the storage pool corresponding to the specified index storagepool. Unlike the key option, the file's affinity is not affected. Use "sgmanage --list" to see the stripe group index. -l This option causes snfsdefrag to just list candidate files. -L When used with the -e or -E option, this option causes snfsdefrag to also print out the physical location of each extent on disk. -m count This option tells snfsdefrag to only operate on files containing more than count extents. By default, the value of count is 1. A value of zero can be specified to operate on all files with at least one extent. This is useful for moving files off a stripe group. -p Causes snfsdefrag to perform a prune operation instead of defragmenting the file. During a prune operation, blocks beyond EOF that have been preallocated either explicitly or as part of inode expansion are freed, thereby reducing disk usage. Files are otherwise unmodified. Note: While prune operations reclaim unused disk space, performing them regularly can lead to free space fragmentation. -P Lists skipped files. -q Causes snfsdefrag to be quiet. -r This option instructs snfsdefrag to recurse through the Target and attempt to defragment each fragmented file that it finds. If Target is not specified, the current directory is assumed. -s Causes snfsdefrag to perform allocations that are block-aligned. This can help performance in situations where the I/O size perfectly spans the width of the storage pool's disks. -S file Writes status monitoring information in the supplied file. This is used internally by Xsan and the format of this file may change. -t This option adds totals to the output of the -c, -e, or -E options. Output at the end indicates how many regular files were visited, how many total extents were found from all files, and the average # of extents per file. Also shown are the number of files with one extent, the number of files with more than one extent, and the largest number of extents in a single file. -T This option acts like -t, except that with -c, only the summary output is presented. No information is provided for individual files. -v Causes snfsdefrag to be verbose.
Count the extents in the file foo. rock% snfsdefrag -c foo Starting in directory, dir1, recursively count all the files and their extents and then print the grand total and average number of extents per file. rock% snfsdefrag -r -c -t dir1 List the extents in the file foo. rock% snfsdefrag -e foo Defragment the file foo. rock% snfsdefrag foo Defragment the file foo if it contains more than 2 extents. Otherwise, do nothing. rock% snfsdefrag -m 2 foo Traverse the directory abc and its sub-directories and defragment every file found containing more than one extent. rock% snfsdefrag -r abc Traverse the directory abc and its sub-directories and defragment every file found having one or more extents whose depth differs from the current depth of extent's storage pool OR having more than one extent. rock% snfsdefrag -rd abc Traverse the directory abc and its sub-directories and only defragment files having one or more extents whose depth differs from the current depth of extent's storage pool. This situation would arise after cvupdatefs has been used to expand the depth of a stripe group. The high value for -m ensures that only extents with different depth values are defragmented. rock% snfsdefrag -m 9999999999 -rd abc Traverse the directory abc and recover unused preallocated disk space in every file visited. rock% snfsdefrag -rp abc Force the file foo to be relocated to the storage pool with the affinity key "fast" rock% snfsdefrag -k fast -m 0 foo If the file foo has the affinity fast, then move its data to a storage pool with the affinity slow. rock% snfsdefrag -K fast -k slow -m 0 foo If the file foo does NOT have the affinity slow, then move its data to a storage pool with the affinity slow. rock% snfsdefrag -K '!slow' -k slow -m 0 foo Traverse the directory abc and migrate any files containing at least one extent in storage pool 2 to any non-exclusive storage pool. rock% snfsdefrag -r -G 2 -m 0 abc Traverse the directory abc and migrate any files containing at least one extent in storage pool 2 to storage pools with the affinity slow. It is advised that allocations to the source stripe group be disabled before running the following command, if you wish to retire the source stripe group. On systems with Linux MDCs, use sgmanage to disable allocations. On Windows MDCs, edit the config file, insert "Alloc Disabled" in the stripe group section, and restart the FSM. rock% snfsdefrag -r -G 2 -k slow -m 0 abc Traverse the directory abc list any files that have the affinity fast and having at least one extent in storage pool 2. It is advised that allocations to the source stripe group be disabled before running the following command, if you wish to retire the source stripe group. On systems with Linux MDCs, use sgmanage to disable allocations. On Windows MDCs, edit the config file, insert "Alloc Disabled" in the stripe group section, and restart the FSM. rock% snfsdefrag -r -G 2 -k fast -l -m 0 abc NOTES Only the owner of a file or superuser is allowed to defragment a file. (To act as superuser on a Xsan volume, in addition to becoming the user root, the configuration option GlobalSuperUser must be enabled. See snfs_config(5) for more information.) snfsdefrag attempts to set an administrative lock on a file before attempting the defrag operation, unless overridden by the -A option. This will stop I/O related operations on an open file and allow the defrag operation to proceed. When the defrag is complete, the client will refresh its view of the file such that an application will not be aware that the file's physical location on disk may have changed. If the administrative lock cannot be obtained and the file is open, snfsdefrag will skip the file. snfsdefrag will not operate on files that have been modified in the past 10 seconds and files with modification times in the future. If a file is modified while defragmentation is in progress, snfsdefrag will abort and the file will be skipped. snfsdefrag skips special files and files containing holes. snfsdefrag does not follow symbolic links. When operating on a file marked for PerfectFit allocations, snfsdefrag will "do the right thing" and preserve the PerfectFit attribute. While performing defragmentation, snfsdefrag creates a temporary file named TargetFile__defragtmp. If the command is interrupted, snfsdefrag will attempt to remove this file. However, if snfsdefrag is killed or a power failure occurs, the temporary file may be left behind. If snfsdefrag is subsequently re-run and attempts defragmentation, it will clean up any stale temporary files encountered. But if snfsdefrag is not run again, it will be necessary to find and remove the temporary file as it will continue to consume space. Note that user files having the __defragtmp extension should not be created if snfsdefrag is to be run. snfsdefrag will fail if it cannot locate a set of extents that would reduce the current extent count on a file. When files being defragmented reside in a managed file system with stub files enabled and CLASS_STUB_READ_AHEAD is set in the fs_sysparams file, the operation could cause file retrieval. By default, when using the -r option, snfsdefrag will sort directory entries before operating on them unless the size of the directory exceeds 1GiB. This threshold can be adjusted using the environment variable DEFRAG_MAX_DIR_SORT_SIZE. When a file contains a resource fork and resides on a file system where the namedStreams feature is enabled, by default, snfsdefrag will attempt to operate on the resource fork as well as the main file. When this occurs, the resource fork will be displayed having the same name as the original file with the "/..namedfork/rsrc" suffix. For example, if the original file has the name "/stornext/snfs1/myfile", snfsdefrag will show "/stornext/snfs1/myfile/..namedfork/rsrc" to represent the resource fork "named stream." The -F option can be used to prevent snfsdefrag from operating on these named streams. ADVANCED FRAGMENTATION ANALYSIS There are two major types of fragmentation to note: file fragmentation and free space fragmentation. File fragmentation is measured by the number of file extents used to store a file. A file extent is a contiguous allocation unit within a file. When a large enough contiguous space cannot be found to allocate to a file, multiple smaller file extents are created. Each extent represents a different physical spot in a storage pool. Requiring multiple extents to address file data impacts performance in a number of ways. First, the file system must do more work looking up locations for a file's data. Also, having file data spread across many different locations in the file system requires the storage hardware to do more work while reading a file. On a disk there will be increased head movements, as the drive seeks around to read in each data extent. Many disks also attempt to optimize I/O performance, for example, by attempting to predict upcoming read locations. When a file's data is contiguous these optimizations work well. However, with a fragmented file the drive optimizations are not nearly as efficient. A file's fragmentation should be viewed more as a percentage than as a hard number. While it's true that a file of nearly any size with 50000 fragments is extremely fragmented and should be defragmented, a file that has 500 fragments that are mostly one or two file system blocks (4096 bytes) in length is also very fragmented. Keeping files to under 10% fragmentation is the ideal, and how close you come to that ideal is a compromise based on real-world factors (file system use, file sizes and their life span, opportunities to run snfsdefrag, etc.). In an attempt to reduce fragmentation (file and free space), Administrators can try using the Allocation Session Reservation feature. This feature is managed using the GUI or by modifying the allocSessionReservationSize parameter, see snfs_config(5). See also the Xsan Tuning Guide. Some common causes of fragmentation are having very full stripe groups (possibly because of affinities), a file system that has a lot of fragmented free space (deleting a fragmented file produces fragmented free space), heavy use of CIFS or NFS which typically use out-of-order allocations resulting in unoptimized (uncoalesced) allocations, or an application that writes files in a random order. snfsdefrag is designed to detect files which contain file fragmentation and coalesce that data onto a minimal number of file extents. The efficiency of snfsdefrag is dependent on the state of the file system's free data blocks, or free space. The second type of fragmentation is free space fragmentation. The file system's free space is the pool of unallocated data blocks. Space allocation for new files, as well as allocations for extending existing files, comes from the file system's free space. Free space fragmentation is measured by the number of fragments of contiguous free blocks. Fragmentation in the file system's free space affects the file system's ability to allocate large extents. A file can only have an extent as large as the largest contiguous block of free space. Thus free space fragmentation can lead to file fragmentation in larger files. As snfsdefrag processes fragmented files it attempts to use large enough free space fragments to create a new defragmented file space. If free space is too fragmented snfsdefrag may not be able to allocate a large enough extent for the file's data. In the case that snfsdefrag must use multiple extents in the defragmented file, it will only proceed if the processed file will have fewer extents than the original. Otherwise snfsdefrag will abort that file's defrag process and move on to remaining defrag requests. FRAGMENTATION ANALYSIS EXAMPLES The following examples include reporting from snfsdefrag as well as cvfsck. Some examples require additional tools such as awk and sort. Reporting a specific file's fragmentation (extent count). # snfsdefrag -c <filename> Report all files, their extents, the total # of files and extents, and the average number of extents per files. Beware that this command walks the entire file system so it can take a while and cause the performance of applications to degrade while running. # snfsdefrag -r -c -t <mount point> The following command will create a report showing each file's path, followed by extent count, with the report sorted by extent count. Files with the greatest number of extents will show up at the top of the list. Replace <fsname> in the following example with the name of your Xsan file system. The report is written to stdout and should be redirected to a file. # cvfsck -x <fsname> | awk -F, '{if (NF == 14) \ print($6", "$7)}' | sort -uk1 -t, | sort -nrk2 -t, This next command will display all files with at least 10 extents and with a size of at least 1MB. Replace <fsname> in the following example with the name of your Xsan file system. The report is written to stdout and can be redirected to a file. # echo "#extents file size av. extent size filename"; \ cvfsck -r <fsname> | awk '{if (NF == 8 && $03 > 1048576 && \ $05 > 10) printf("%8d %10d %16d %10s\n", $5, $3, $03/$05, $8)}' \ | sort -nr The next command displays a report of free space fragmentation. This allows an administrator to see if free space fragmentation may affect future allocation fragmentation. See cvfsck(8) man page for description of report output. # cvfsck -a -t -f <fsname> The fragmentation detected RAS warning message may sometimes refer to an inode number instead of a file name. To find the file name associated with the inode number on non-Windows clients, fill the file system mount point and the decimal inum from the RAS message into the following find command. The file name can then be used to defragment the file. There may be more than one file that matches the 32-bit inode number. # find <mount_point> -inum <decimal_inum> # snfsdefrag <filename> For Windows clients: Using a DOS shell, CD to the directory containing the StorNext binaries and run the cvstat command as follows: The <fname> parameter is the drive letter:/mount point and the <inum> parameter has either the decimal or hexadecimal 64-bit inode number from the RAS message. For example: c:\> cd c:\Program Files\StorNext\bin c:\> cvstat fname=j:\ inum=0x1c0000004183da FILES /Library/Preferences/Xsan/*.cfg SEE ALSO cvfsck(8), cvcp(1), cvmkfile(1), snfs_config(5), snfs.cfgx(5), snfs.cfg(5), cvaffinity(1), sgdefrag(8), sgoffload(8), sgmanage(8) Xsan File System February 2020 SNFSDEFRAG(1)
zipdetails
This program creates a detailed report on the internal structure of zip files. For each item of metadata within a zip file the program will output the offset into the zip file where the item is located. a textual representation for the item. an optional hex dump of the item. The program assumes a prior understanding of the internal structure of Zip files. You should have a copy of the Zip APPNOTE.TXT <http://www.pkware.com/documents/casestudies/APPNOTE.TXT> file at hand to help understand the output from this program. Default Behaviour By default the program expects to be given a well-formed zip file. It will navigate the Zip file by first parsing the zip central directory at the end of the file. If that is found, it will then walk through the zip records starting at the beginning of the file. Any badly formed zip data structures encountered are likely to terminate the program. If the program finds any structural problems with the zip file it will print a summary at the end of the output report. The set of error cases reported is very much a work in progress, so don't rely on this feature to find all the possible errors in a zip file. If you have suggestions for use-cases where this could be enhanced please consider creating an enhancement request (see "SUPPORT"). Date/time fields are found in zip files are displayed in local time. Use the "--utc" option to display these fields in Coordinated Universal Time (UTC). Scan-Mode If you do have a potentially corrupt zip file, particulatly where the central directory at the end of the file is absent/incomplete, you can try usng the "--scan" option to search for zip records that are still present. When Scan-mode is enabled, the program will walk the zip file from the start, blindly looking for the 4-byte signatures that preceed each of the zip data structures. If it finds any of the recognised signatures it will attempt to dump the associated zip record. For very large zip files, this operation can take a long time to run. Note that the 4-byte signatures used in zip files can sometimes match with random data stored in the zip file, so care is needed interpreting the results.
zipdetails - display the internal structure of zip files
zipdetails [-v][--scan][--redact][--utc] zipfile.zip zipdetails -h zipdetails --version
-h Display help --redact Obscure filenames in the output. Handy for the use case where the zip files contains sensitive data that cannot be shared. --scan Walk the zip file loking for possible zip records. Can be error- prone. See "Scan-Mode" --utc By default, date/time fields are displayed in local time. Use this option to display them in in Coordinated Universal Time (UTC). -v Enable Verbose mode. See "Verbose Output". --version Display version number of the program and exit. Default Output By default zipdetails will output the details of the zip file in three columns. Column 1 This contains the offset from the start of the file in hex. Column 2 This contains a textual description of the field. Column 3 If the field contains a numeric value it will be displayed in hex. Zip stores most numbers in little-endian format - the value displayed will have the little-endian encoding removed. Next, is an optional description of what the value means. For example, assuming you have a zip file with two entries, like this $ unzip -l test.zip Archive: setup/test.zip Length Date Time Name --------- ---------- ----- ---- 6 2021-03-23 18:52 latters.txt 6 2021-03-23 18:52 numbers.txt --------- ------- 12 2 files Running "zipdetails" will gives this output $ zipdetails test.zip 0000 LOCAL HEADER #1 04034B50 0004 Extract Zip Spec 0A '1.0' 0005 Extract OS 00 'MS-DOS' 0006 General Purpose Flag 0000 0008 Compression Method 0000 'Stored' 000A Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021' 000E CRC 0F8A149C 0012 Compressed Length 00000006 0016 Uncompressed Length 00000006 001A Filename Length 000B 001C Extra Length 0000 001E Filename 'letters.txt' 0029 PAYLOAD abcde. 002F LOCAL HEADER #2 04034B50 0033 Extract Zip Spec 0A '1.0' 0034 Extract OS 00 'MS-DOS' 0035 General Purpose Flag 0000 0037 Compression Method 0000 'Stored' 0039 Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021' 003D CRC 261DAFE6 0041 Compressed Length 00000006 0045 Uncompressed Length 00000006 0049 Filename Length 000B 004B Extra Length 0000 004D Filename 'numbers.txt' 0058 PAYLOAD 12345. 005E CENTRAL HEADER #1 02014B50 0062 Created Zip Spec 1E '3.0' 0063 Created OS 03 'Unix' 0064 Extract Zip Spec 0A '1.0' 0065 Extract OS 00 'MS-DOS' 0066 General Purpose Flag 0000 0068 Compression Method 0000 'Stored' 006A Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021' 006E CRC 0F8A149C 0072 Compressed Length 00000006 0076 Uncompressed Length 00000006 007A Filename Length 000B 007C Extra Length 0000 007E Comment Length 0000 0080 Disk Start 0000 0082 Int File Attributes 0001 [Bit 0] 1 Text Data 0084 Ext File Attributes 81B40000 0088 Local Header Offset 00000000 008C Filename 'letters.txt' 0097 CENTRAL HEADER #2 02014B50 009B Created Zip Spec 1E '3.0' 009C Created OS 03 'Unix' 009D Extract Zip Spec 0A '1.0' 009E Extract OS 00 'MS-DOS' 009F General Purpose Flag 0000 00A1 Compression Method 0000 'Stored' 00A3 Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021' 00A7 CRC 261DAFE6 00AB Compressed Length 00000006 00AF Uncompressed Length 00000006 00B3 Filename Length 000B 00B5 Extra Length 0000 00B7 Comment Length 0000 00B9 Disk Start 0000 00BB Int File Attributes 0001 [Bit 0] 1 Text Data 00BD Ext File Attributes 81B40000 00C1 Local Header Offset 0000002F 00C5 Filename 'numbers.txt' 00D0 END CENTRAL HEADER 06054B50 00D4 Number of this disk 0000 00D6 Central Dir Disk no 0000 00D8 Entries in this disk 0002 00DA Total Entries 0002 00DC Size of Central Dir 00000072 00E0 Offset to Central Dir 0000005E 00E4 Comment Length 0000 Done Verbose Output If the "-v" option is present, column 1 is expanded to include • The offset from the start of the file in hex. • The length of the field in hex. • A hex dump of the bytes in field in the order they are stored in the zip file. Here is the same zip file dumped using the "zipdetails" "-v" option: $ zipdetails -v test.zip 0000 0004 50 4B 03 04 LOCAL HEADER #1 04034B50 0004 0001 0A Extract Zip Spec 0A '1.0' 0005 0001 00 Extract OS 00 'MS-DOS' 0006 0002 00 00 General Purpose Flag 0000 0008 0002 00 00 Compression Method 0000 'Stored' 000A 0004 3D 98 77 52 Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021' 000E 0004 9C 14 8A 0F CRC 0F8A149C 0012 0004 06 00 00 00 Compressed Length 00000006 0016 0004 06 00 00 00 Uncompressed Length 00000006 001A 0002 0B 00 Filename Length 000B 001C 0002 00 00 Extra Length 0000 001E 000B 6C 65 74 74 Filename 'letters.txt' 65 72 73 2E 74 78 74 0029 0006 61 62 63 64 PAYLOAD abcde. 65 0A 002F 0004 50 4B 03 04 LOCAL HEADER #2 04034B50 0033 0001 0A Extract Zip Spec 0A '1.0' 0034 0001 00 Extract OS 00 'MS-DOS' 0035 0002 00 00 General Purpose Flag 0000 0037 0002 00 00 Compression Method 0000 'Stored' 0039 0004 3D 98 77 52 Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021' 003D 0004 E6 AF 1D 26 CRC 261DAFE6 0041 0004 06 00 00 00 Compressed Length 00000006 0045 0004 06 00 00 00 Uncompressed Length 00000006 0049 0002 0B 00 Filename Length 000B 004B 0002 00 00 Extra Length 0000 004D 000B 6E 75 6D 62 Filename 'numbers.txt' 65 72 73 2E 74 78 74 0058 0006 31 32 33 34 PAYLOAD 12345. 35 0A 005E 0004 50 4B 01 02 CENTRAL HEADER #1 02014B50 0062 0001 1E Created Zip Spec 1E '3.0' 0063 0001 03 Created OS 03 'Unix' 0064 0001 0A Extract Zip Spec 0A '1.0' 0065 0001 00 Extract OS 00 'MS-DOS' 0066 0002 00 00 General Purpose Flag 0000 0068 0002 00 00 Compression Method 0000 'Stored' 006A 0004 3D 98 77 52 Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021' 006E 0004 9C 14 8A 0F CRC 0F8A149C 0072 0004 06 00 00 00 Compressed Length 00000006 0076 0004 06 00 00 00 Uncompressed Length 00000006 007A 0002 0B 00 Filename Length 000B 007C 0002 00 00 Extra Length 0000 007E 0002 00 00 Comment Length 0000 0080 0002 00 00 Disk Start 0000 0082 0002 01 00 Int File Attributes 0001 [Bit 0] 1 Text Data 0084 0004 00 00 B4 81 Ext File Attributes 81B40000 0088 0004 00 00 00 00 Local Header Offset 00000000 008C 000B 6C 65 74 74 Filename 'letters.txt' 65 72 73 2E 74 78 74 0097 0004 50 4B 01 02 CENTRAL HEADER #2 02014B50 009B 0001 1E Created Zip Spec 1E '3.0' 009C 0001 03 Created OS 03 'Unix' 009D 0001 0A Extract Zip Spec 0A '1.0' 009E 0001 00 Extract OS 00 'MS-DOS' 009F 0002 00 00 General Purpose Flag 0000 00A1 0002 00 00 Compression Method 0000 'Stored' 00A3 0004 3D 98 77 52 Last Mod Time 5277983D 'Tue Mar 23 19:01:58 2021' 00A7 0004 E6 AF 1D 26 CRC 261DAFE6 00AB 0004 06 00 00 00 Compressed Length 00000006 00AF 0004 06 00 00 00 Uncompressed Length 00000006 00B3 0002 0B 00 Filename Length 000B 00B5 0002 00 00 Extra Length 0000 00B7 0002 00 00 Comment Length 0000 00B9 0002 00 00 Disk Start 0000 00BB 0002 01 00 Int File Attributes 0001 [Bit 0] 1 Text Data 00BD 0004 00 00 B4 81 Ext File Attributes 81B40000 00C1 0004 2F 00 00 00 Local Header Offset 0000002F 00C5 000B 6E 75 6D 62 Filename 'numbers.txt' 65 72 73 2E 74 78 74 00D0 0004 50 4B 05 06 END CENTRAL HEADER 06054B50 00D4 0002 00 00 Number of this disk 0000 00D6 0002 00 00 Central Dir Disk no 0000 00D8 0002 02 00 Entries in this disk 0002 00DA 0002 02 00 Total Entries 0002 00DC 0004 72 00 00 00 Size of Central Dir 00000072 00E0 0004 5E 00 00 00 Offset to Central Dir 0000005E 00E4 0002 00 00 Comment Length 0000 Done LIMITATIONS The following zip file features are not supported by this program: • Multi-part archives. • The strong encryption features defined in the APPNOTE.TXT <http://www.pkware.com/documents/casestudies/APPNOTE.TXT> document. TODO Error handling is a work in progress. If the program encounters a problem reading a zip file it is likely to terminate with an unhelpful error message. SUPPORT General feedback/questions/bug reports should be sent to <https://github.com/pmqs/zipdetails/issues>. SEE ALSO The primary reference for Zip files is APPNOTE.TXT <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>. An alternative reference is the Info-Zip appnote. This is available from <ftp://ftp.info-zip.org/pub/infozip/doc/> For details of WinZip AES encryption see AES Encryption Information: Encryption Specification AE-1 and AE-2 <https://www.winzip.com/win/es/aes_info.html>. The "zipinfo" program that comes with the info-zip distribution (<http://www.info-zip.org/>) can also display details of the structure of a zip file. AUTHOR Paul Marquess pmqs@cpan.org. COPYRIGHT Copyright (c) 2011-2022 Paul Marquess. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. perl v5.38.2 2023-11-28 ZIPDETAILS(1)
null
look
The look utility displays any lines in file which contain string as a prefix. As look performs a binary search, the lines in file must be sorted. If file is not specified, the file /usr/share/dict/words is used, only alphanumeric characters are compared and the case of alphabetic characters is ignored. The following options are available: -d, --alphanum Dictionary character set and order, i.e., only alphanumeric characters are compared. -f, --ignore-case Ignore the case of alphabetic characters. -t, --terminate termchar Specify a string termination character, i.e., only the characters in string up to and including the first occurrence of termchar are compared. ENVIRONMENT The LANG, LC_ALL and LC_CTYPE environment variables affect the execution of the look utility. Their effect is described in environ(7). FILES /usr/share/dict/words the dictionary EXIT STATUS The look utility exits 0 if one or more lines were found and displayed, 1 if no lines were found, and >1 if an error occurred.
look – display lines beginning with a given string
look [-df] [-t termchar] string [file ...]
null
Look for lines starting with ‘xylene’ in the file /usr/share/dict/words: $ look xylen xylene xylenol xylenyl Same as above, but do not consider any characters in string beyond the first ‘e’. Note that -f is implicit since we are searching the default file /usr/share/dict/words: $ look -t e xylen Xyleborus xylem xylene xylenol xylenyl xyletic COMPATIBILITY The original manual page stated that tabs and blank characters participated in comparisons when the -d option was specified. This was incorrect and the current man page matches the historic implementation. The -a and --alternative flags are ignored for compatibility. SEE ALSO grep(1), sort(1) HISTORY A look utility appeared in Version 7 AT&T UNIX. BUGS Lines are not compared according to the current locale's collating order. Input files must be sorted with LC_COLLATE set to ‘C’. macOS 14.5 December 29, 2020 macOS 14.5
col
The col utility filters out reverse (and half reverse) line feeds so that the output is in the correct order with only forward and half forward line feeds, and replaces white-space characters with tabs where possible. The col utility reads from the standard input and writes to the standard output. The options are as follows: -b Do not output any backspaces, printing only the last character written to each column position. -f Forward half line feeds are permitted (``fine'' mode). Normally characters printed on a half line boundary are printed on the following line. -h Do not output multiple spaces instead of tabs (default). -l num Buffer at least num lines in memory. By default, 128 lines are buffered. -p Force unknown control sequences to be passed through unchanged. Normally, col will filter out any control sequences from the input other than those recognized and interpreted by itself, which are listed below. -x Output multiple spaces instead of tabs. In the input stream, col understands both the escape sequences of the form escape-digit mandated by Version 2 of the Single UNIX Specification (“SUSv2”) and the traditional BSD format escape-control-character. The control sequences for carriage motion and their ASCII values are as follows: ESC-BELL reverse line feed (escape then bell). ESC-7 reverse line feed (escape then 7). ESC-BACKSPACE half reverse line feed (escape then backspace). ESC-8 half reverse line feed (escape then 8). ESC-TAB half forward line feed (escape than tab). ESC-9 half forward line feed (escape then 9). In -f mode, this sequence may also occur in the output stream. backspace moves back one column (8); ignored in the first column carriage return (13) newline forward line feed (10); also does carriage return shift in shift to normal character set (15) shift out shift to alternate character set (14) space moves forward one column (32) tab moves forward to next tab stop (9) vertical tab reverse line feed (11) All unrecognized control characters and escape sequences are discarded. The col utility keeps track of the character set as characters are read and makes sure the character set is correct when they are output. If the input attempts to back up to the last flushed line, col will display a warning message. ENVIRONMENT The LANG, LC_ALL and LC_CTYPE environment variables affect the execution of col as described in environ(7). EXIT STATUS The col utility exits 0 on success, and >0 if an error occurs.
col – filter reverse line feeds from input
col [-bfhpx] [-l num]
null
We can use col to filter the output of man(1) and remove the backspace characters ( ^H ) before searching for some text: man ls | col -b | grep HISTORY SEE ALSO expand(1) STANDARDS The col utility conforms to Version 2 of the Single UNIX Specification (“SUSv2”). HISTORY A col command appeared in Version 6 AT&T UNIX. macOS 14.5 October 21, 2020 macOS 14.5
dscacheutil
dscacheutil does various operations against the Directory Service cache including gathering statistics, initiating lookups, inspection, cache flush, etc. This tool replaces most of the functionality of the lookupd tool previously available in the OS. FLAGS A list of flags and their descriptions: -h Lists the options for calling dscacheutil -q category Initiate a query using standard calls. These calls will either return results from the cache or go fetch live data and place them in the cache. By default if no specific query is requested via -a then all results within that category will be returned. -a key value Optional flag to -q for a specific key with a value. -cachedump Dumps an overview of the cache by default. Additional flags will provide more detailed information. -buckets Used in conjunction with -cachedump to also print hash bucket usage of the current cache. -entries [category] Used in conjunction with -cachedump to dump detailed information about cache entries. An optional category can be supplied to only see types of interest. Dumping 'host' entries can only be done by administrative users. -configuration Prints current configuration information, such as the search policy from Directory Service and cache parameters. -flushcache Flushes the entire cache. This should only be used in extreme cases. Validation information is used within the cache along with other techniques to ensure the OS has valid information available to it. -statistics Prints statistics from the cache including an overview and detailed call statistics. Some calls are not cached but are derived from other calls internally. Cache hits and cache misses may not always be equal to external calls. For example getaddrinfo is actually a combination of gethostbyname with other calls internally to the cache to maximize cache hit rate. Available categories and associated keys: group name or gid host name or ip_address (used for both IPv6 and IPv4) mount name protocol name or number rpc name or number service name or port user name or uid
dscacheutil – gather information, statistics and initiate queries to the Directory Service cache.
dscacheutil -h dscacheutil -q category [-a key value] dscacheutil -cachedump [-buckets] [-entries [category]] dscacheutil -configuration dscacheutil -flushcache dscacheutil -statistics
null
Lookup a user: % dscacheutil -q user -a name jdoe name: jdoe password: ******** uid: 501 gid: 501 dir: /Users/jdoe shell: /bin/csh gecos: John Doe Lookup all users: % dscacheutil -q user Dump cache overview: % dscacheutil -cachedump Dump cache details with user entries: % dscacheutil -cachedump -entries user SEE ALSO DirectoryService(8), dsmemberutil(1) Darwin January 14, 2007 Darwin
syscapturediags
null
null
null
null
null
lwp-request5.30
This program can be used to send requests to WWW servers and your local file system. The request content for POST and PUT methods is read from stdin. The content of the response is printed on stdout. Error messages are printed on stderr. The program returns a status value indicating the number of URLs that failed. The options are: -m <method> Set which method to use for the request. If this option is not used, then the method is derived from the name of the program. -f Force request through, even if the program believes that the method is illegal. The server might reject the request eventually. -b <uri> This URI will be used as the base URI for resolving all relative URIs given as argument. -t <timeout> Set the timeout value for the requests. The timeout is the amount of time that the program will wait for a response from the remote server before it fails. The default unit for the timeout value is seconds. You might append "m" or "h" to the timeout value to make it minutes or hours, respectively. The default timeout is '3m', i.e. 3 minutes. -i <time> Set the If-Modified-Since header in the request. If time is the name of a file, use the modification timestamp for this file. If time is not a file, it is parsed as a literal date. Take a look at HTTP::Date for recognized formats. -c <content-type> Set the Content-Type for the request. This option is only allowed for requests that take a content, i.e. POST and PUT. You can force methods to take content by using the "-f" option together with "-c". The default Content-Type for POST is "application/x-www-form-urlencoded". The default Content-type for the others is "text/plain". -p <proxy-url> Set the proxy to be used for the requests. The program also loads proxy settings from the environment. You can disable this with the "-P" option. -P Don't load proxy settings from environment. -H <header> Send this HTTP header with each request. You can specify several, e.g.: lwp-request \ -H 'Referer: http://other.url/' \ -H 'Host: somehost' \ http://this.url/ -C <username>:<password> Provide credentials for documents that are protected by Basic Authentication. If the document is protected and you did not specify the username and password with this option, then you will be prompted to provide these values. The following options controls what is displayed by the program: -u Print request method and absolute URL as requests are made. -U Print request headers in addition to request method and absolute URL. -s Print response status code. This option is always on for HEAD requests. -S Print response status chain. This shows redirect and authorization requests that are handled by the library. -e Print response headers. This option is always on for HEAD requests. -E Print response status chain with full response headers. -d Do not print the content of the response. -o <format> Process HTML content in various ways before printing it. If the content type of the response is not HTML, then this option has no effect. The legal format values are; "text", "ps", "links", "html" and "dump". If you specify the "text" format then the HTML will be formatted as plain "latin1" text. If you specify the "ps" format then it will be formatted as Postscript. The "links" format will output all links found in the HTML document. Relative links will be expanded to absolute ones. The "html" format will reformat the HTML code and the "dump" format will just dump the HTML syntax tree. Note that the "HTML-Tree" distribution needs to be installed for this option to work. In addition the "HTML-Format" distribution needs to be installed for "-o text" or "-o ps" to work. -v Print the version number of the program and quit. -h Print usage message and quit. -a Set text(ascii) mode for content input and output. If this option is not used, content input and output is done in binary mode. Because this program is implemented using the LWP library, it will only support the protocols that LWP supports. SEE ALSO lwp-mirror, LWP COPYRIGHT Copyright 1995-1999 Gisle Aas. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. AUTHOR Gisle Aas <gisle@aas.no> perl v5.30.3 2020-04-14 LWP-REQUEST(1)
lwp-request - Simple command line user agent
lwp-request [-afPuUsSedvhx] [-m method] [-b base URL] [-t timeout] [-i if-modified-since] [-c content-type] [-C credentials] [-p proxy-url] [-o format] url...
null
null
zforce
The zforce utility renames gzip(1) files to have a ‘.gz’ suffix, so that gzip(1) will not compress them twice. This can be useful if file names were truncated during a file transfer. Files that have an existing ‘.gz’, ‘-gz’, ‘_gz’, ‘.tgz’ or ‘.taz’ suffix, or that have not been compressed by gzip(1), are ignored. SEE ALSO gzip(1) CAVEATS zforce overwrites existing files without warning. macOS 14.5 January 26, 2007 macOS 14.5
zforce – force gzip files to have a .gz suffix
zforce file ...
null
null
lwp-mirror
This program can be used to mirror a document from a WWW server. The document is only transferred if the remote copy is newer than the local copy. If the local copy is newer nothing happens. Use the "-v" option to print the version number of this program. The timeout value specified with the "-t" option. The timeout value is the time that the program will wait for response from the remote server before it fails. The default unit for the timeout value is seconds. You might append "m" or "h" to the timeout value to make it minutes or hours, respectively. Because this program is implemented using the LWP library, it only supports the protocols that LWP supports. SEE ALSO lwp-request, LWP AUTHOR Gisle Aas <gisle@aas.no> perl v5.34.0 2020-04-14 LWP-MIRROR(1)
lwp-mirror - Simple mirror utility
lwp-mirror [-v] [-t timeout] <url> <local file>
null
null
malloc_history
malloc_history inspects a given process and lists the malloc and anonymous VM allocations performed by it. Anonymous VM allocations are from calls such as mach_vm_allocate that allocate raw Virtual Memory that is not backed by a file. Allocations of the VM regions underlying the malloc heaps are ignored. malloc_history relies on information provided by the standard malloc library when malloc stack logging has been enabled for the target process. See below for further information. The target process may be specified by pid or by full or partial name, or it can be the path of a memory graph file generated by leaks or the Xcode Memory Graph Debugger. If the -highWaterMark option is passed, malloc_history first scans through the all malloc stack log records to calculate the "high water mark" of allocated memory -- i.e., the highest amount of allocated memory used at any one time by the target process. It then shows information about the malloc allocations and anonymous VM regions that were live at that time, rather than currently alive in the target program. The -highWaterMark option does not work with memory graph files since they only contain stack logs for active allocations, not full history. By specifying one or more addresses, malloc_history lists all allocations and deallocations of any malloc blocks or VM regions that started at or contained those addresses. For each allocation, a stack trace describing who called malloc or free, or mach_vm_allocate, mmap, or mach_vm_deallocate is listed. If you do only wish to see events for malloc blocks and VM regions that started at the specified address, you can grep the output for that address. If -highWaterMark is passed, it only shows allocations and deallocations up to the high water mark. Alternatively, the -allBySize and -allByCount options list all allocations that are currently live in the target process, or were live at the high water mark. Frequent allocations from the same point in the program (that is, the same call stack) are grouped together, and output presented either from largest allocations to smallest, or most allocations to least. If you also specify one or more addresses, this output is filtered to only show information for malloc blocks containing those addresses. The -allEvents option lists all allocation and free events, for all addresses, up to the current time or to the high water mark. This output can be voluminous. If the -showContent option is passed, live allocations will have additional details as described for that option below. The -callTree option generates a call tree of the backtraces of malloc calls and anonymous VM regions for live allocations in the target process, or for allocations that were live at the high water mark. The call tree can be filtered to backtraces of specific allocations or classes, by passing one or more addresses or a <classes-pattern>. The <classes-pattern> regular expression is interpreted as an extended (modern) regular expression as described by the re_format(7) manual page. "malloc" or "non-object" can be used to refer to blocks that are not of any specific type. Examples of valid classes-patterns include: CFString 'NS.*' '__NSCFString|__NSCFArray' '.*(String|Array)' 'VM:.*' malloc non-object malloc|.*String The <classes-pattern> pattern can be followed by an optional allocation size specifier, which can be one of the following forms. The square brackets are required. The size can include a 'k' suffix for kilobytes, or an 'm' suffix for megabytes: [size] [lowerBound-upperBound] [lowerBound+] [-upperBound] Examples of <classes-pattern> with size specifications include: malloc[2048] all malloc blocks of size 2048 malloc[1k-8k] all malloc blocks between 1k and 8k '(NS|CF).*[10k+]' all NS or CF objects 10k or larger [-1024] all allocations 1024 bytes or less VM.*[1m+] all Virtual Memory regions of size 1m or larger; by default this is dirty+swapped-volative size, unless the -virtual flag is passed The call tree format is similar to the output from sample(1). The resulting call tree can be filtered or pruned with the filtercalltree(1) tool for further analysis. Additional options for the -callTree mode include: -showContent Show the content of malloc blocks of various types, including C strings, Pascal strings (with a length byte at the start), and various objects including NSString, NSDate, and NSNumber. -invert Invert the call tree, so that malloc (and the allocated content, if the -showContent option was given) show at the top of the call trees. -ignoreThreads Combine the call trees for all threads into a single call tree. -collapseRecursion Collapse recursion within the call trees. -chargeSystemLibraries Remove stack frames from all libraries in /System and /usr, while still charging their cost (number of calls, allocation size, and content) to the callers. -virtual Display the size of VM regions as the virtual size, rather than the default dirty + swapped/compressed - purgableVolatile. All modes require the standard malloc library's debugging facility to be turned on. To do this, set either the MallocStackLogging or MallocStackLoggingNoCompact environment variable to 1 in the shell that will run the program. If MallocStackLogging is used, then when recording events, if an allocation event for an address is immediately followed by a free event for the same address, both events are removed from the event log. If MallocStackLoggingNoCompact is used, then all such immediate allocation/free pairs are kept in the event log, which can be useful when examining all events for a specific address, or when using the -allEvents option. If both MallocStackLogging and MallocStackLoggingNoCompact are set, then MallocStackLogging takes precedence and MallocStackLoggingNoCompact is ignored. malloc_history is particularly useful for tracking down memory smashers. Run the program to be inspected with MallocStackLogging or MallocStackLoggingNoCompact defined. Also set the environment variable MallocScribble; this causes the malloc library to overwrite freed memory with a well-known value (0x55), and occasionally checks freed malloc blocks to make sure the memory has not been overwritten since it was cleared. When malloc detects the memory has been written, it will print out a warning that the buffer was modified after being freed. You can then use malloc_history to find who allocated and freed memory at that address, and thus deduce what parts of the code might still have a pointer to the freed structure. EXAMPLE To see backtraces of allocations by class type or malloc size, run this command: % malloc_history <process> -callTree -invert -showContent SEE ALSO malloc(3), heap(1), leaks(1), stringdups(1), vmmap(1), filtercalltree(1), DevToolsSecurity(1) The Xcode developer tools also include Instruments, a graphical application that can give information similar to that provided by malloc_history. The Allocations instrument graphically displays dynamic, real-time information about the object and memory use in an application, including backtraces of where the allocations occured. macOS 14.5 Oct. 7, 2019 macOS 14.5
malloc_history – Show the malloc and anonymous VM allocations that the process has performed
malloc_history process [-highWaterMark] address [address ...] malloc_history process -allBySize [-highWaterMark] [address ...] malloc_history process -allByCount [-highWaterMark] [address ...] malloc_history process -allEvents [-highWaterMark] [-showContent] malloc_history process -callTree [-highWaterMark] [-showContent] [-invert] [-ignoreThreads] [-collapseRecursion] [-chargeSystemLibraries] [-virtual] [address ... | <classes-pattern>] process is a pid, executable-name, or memory-graph-file
null
null
cpio
cpio copies files between archives and directories. This implementation can extract from tar, pax, cpio, zip, jar, ar, and ISO 9660 cdrom images and can create tar, pax, cpio, ar, and shar archives. The first option to cpio is a mode indicator from the following list: -i Input. Read an archive from standard input (unless overridden) and extract the contents to disk or (if the -t option is specified) list the contents to standard output. If one or more file patterns are specified, only files matching one of the patterns will be extracted. -o Output. Read a list of filenames from standard input and produce a new archive on standard output (unless overridden) containing the specified items. -p Pass-through. Read a list of filenames from standard input and copy the files to the specified directory.
cpio – copy files to and from archives
cpio -i [options] [pattern ...] [< archive] cpio -o [options] < name-list [> archive] cpio -p [options] dest-dir < name-list
Unless specifically stated otherwise, options are applicable in all operating modes. -0, --null Read filenames separated by NUL characters instead of newlines. This is necessary if any of the filenames being read might contain newlines. -6, --pwb When reading a binary format archive, assume it's the earlier one, from the PWB variant of 6th Edition UNIX. When writing a cpio archive, use the PWB format. -7, --binary (o mode only) When writing a cpio archive, use the (newer, non- PWB) binary format. -A (o mode only) Append to the specified archive. (Not yet implemented.) -a (o and p modes) Reset access times on files after they are read. -B (o mode only) Block output to records of 5120 bytes. -C size (o mode only) Block output to records of size bytes. -c (o mode only) Use the old POSIX portable character format. Equivalent to --format odc. -d, --make-directories (i and p modes) Create directories as necessary. -E file (i mode only) Read list of file name patterns from file to list and extract. -F file, --file file Read archive from or write archive to file. -f pattern (i mode only) Ignore files that match pattern. -H format, --format format (o mode only) Produce the output archive in the specified format. Supported formats include: cpio Synonym for odc. newc The SVR4 portable cpio format. odc The old POSIX.1 portable octet-oriented cpio format. pax The POSIX.1 pax format, an extension of the ustar format. ustar The POSIX.1 tar format. The default format is odc. See libarchive-formats(5) for more complete information about the formats currently supported by the underlying libarchive(3) library. -h, --help Print usage information. -I file Read archive from file. -i, --extract Input mode. See above for description. --insecure (i and p mode only) Disable security checks during extraction or copying. This allows extraction via symbolic links, absolute paths, and path names containing ‘..’ in the name. -J, --xz (o mode only) Compress the file with xz-compatible compression before writing it. In input mode, this option is ignored; xz compression is recognized automatically on input. -j Synonym for -y. -L (o and p modes) All symbolic links will be followed. Normally, symbolic links are archived and copied as symbolic links. With this option, the target of the link will be archived or copied instead. -l, --link (p mode only) Create links from the target directory to the original files, instead of copying. --lrzip (o mode only) Compress the resulting archive with lrzip(1). In input mode, this option is ignored. --lz4 (o mode only) Compress the archive with lz4-compatible compression before writing it. In input mode, this option is ignored; lz4 compression is recognized automatically on input. --zstd (o mode only) Compress the archive with zstd-compatible compression before writing it. In input mode, this option is ignored; zstd compression is recognized automatically on input. --lzma (o mode only) Compress the file with lzma-compatible compression before writing it. In input mode, this option is ignored; lzma compression is recognized automatically on input. --lzop (o mode only) Compress the resulting archive with lzop(1). In input mode, this option is ignored. --passphrase passphrase The passphrase is used to extract or create an encrypted archive. Currently, zip is only a format that cpio can handle encrypted archives. You shouldn't use this option unless you realize how insecure use of this option is. -m, --preserve-modification-time (i and p modes) Set file modification time on created files to match those in the source. -n, --numeric-uid-gid (i mode, only with -t) Display numeric uid and gid. By default, cpio displays the user and group names when they are provided in the archive, or looks up the user and group names in the system password database. --no-preserve-owner (i mode only) Do not attempt to restore file ownership. This is the default when run by non-root users. -O file Write archive to file. -o, --create Output mode. See above for description. -p, --pass-through Pass-through mode. See above for description. --preserve-owner (i mode only) Restore file ownership. This is the default when run by the root user. --quiet Suppress unnecessary messages. -R [user][:][group], --owner [user][:][group] Set the owner and/or group on files in the output. If group is specified with no user (for example, -R :wheel) then the group will be set but not the user. If the user is specified with a trailing colon and no group (for example, -R root:) then the group will be set to the user's default group. If the user is specified with no trailing colon, then the user will be set but not the group. In -i and -p modes, this option can only be used by the super-user. (For compatibility, a period can be used in place of the colon.) -r (All modes.) Rename files interactively. For each file, a prompt is written to /dev/tty containing the name of the file and a line is read from /dev/tty. If the line read is blank, the file is skipped. If the line contains a single period, the file is processed normally. Otherwise, the line is taken to be the new name of the file. -t, --list (i mode only) List the contents of the archive to stdout; do not restore the contents to disk. -u, --unconditional (i and p modes) Unconditionally overwrite existing files. Ordinarily, an older file will not overwrite a newer file on disk. -V, --dot Print a dot to stderr for each file as it is processed. Superseded by -v. -v, --verbose Print the name of each file to stderr as it is processed. With -t, provide a detailed listing of each file. --version Print the program version information and exit. -y (o mode only) Compress the archive with bzip2-compatible compression before writing it. In input mode, this option is ignored; bzip2 compression is recognized automatically on input. -Z (o mode only) Compress the archive with compress-compatible compression before writing it. In input mode, this option is ignored; compression is recognized automatically on input. -z (o mode only) Compress the archive with gzip-compatible compression before writing it. In input mode, this option is ignored; gzip compression is recognized automatically on input. EXIT STATUS The cpio utility exits 0 on success, and >0 if an error occurs. ENVIRONMENT The following environment variables affect the execution of cpio: LANG The locale to use. See environ(7) for more information. TZ The timezone to use when displaying dates. See environ(7) for more information.
The cpio command is traditionally used to copy file hierarchies in conjunction with the find(1) command. The first example here simply copies all files from src to dest: find src | cpio -pmud dest By carefully selecting options to the find(1) command and combining it with other standard utilities, it is possible to exercise very fine control over which files are copied. This next example copies files from src to dest that are more than 2 days old and whose names match a particular pattern: find src -mtime +2 | grep foo[bar] | cpio -pdmu dest This example copies files from src to dest that are more than 2 days old and which contain the word “foobar”: find src -mtime +2 | xargs grep -l foobar | cpio -pdmu dest COMPATIBILITY The mode options i, o, and p and the options a, B, c, d, f, l, m, r, t, u, and v comply with SUSv2. The old POSIX.1 standard specified that only -i, -o, and -p were interpreted as command-line options. Each took a single argument of a list of modifier characters. For example, the standard syntax allows -imu but does not support -miu or -i -m -u, since m and u are only modifiers to -i, they are not command-line options in their own right. The syntax supported by this implementation is backwards-compatible with the standard. For best compatibility, scripts should limit themselves to the standard syntax. SEE ALSO bzip2(1), gzip(1), mt(1), pax(1), tar(1), libarchive(3), cpio(5), libarchive-formats(5), tar(5) STANDARDS There is no current POSIX standard for the cpio command; it appeared in ISO/IEC 9945-1:1996 (“POSIX.1”) but was dropped from IEEE Std 1003.1-2001 (“POSIX.1”). The cpio, ustar, and pax interchange file formats are defined by IEEE Std 1003.1-2001 (“POSIX.1”) for the pax command. HISTORY The original cpio and find utilities were written by Dick Haight while working in AT&T's Unix Support Group. They first appeared in 1977 in PWB/UNIX 1.0, the “Programmer's Work Bench” system developed for use within AT&T. They were first released outside of AT&T as part of System III Unix in 1981. As a result, cpio actually predates tar, even though it was not well-known outside of AT&T until some time later. This is a complete re-implementation based on the libarchive(3) library. BUGS The cpio archive format has several basic limitations: It does not store user and group names, only numbers. As a result, it cannot be reliably used to transfer files between systems with dissimilar user and group numbering. Older cpio formats limit the user and group numbers to 16 or 18 bits, which is insufficient for modern systems. The cpio archive formats cannot support files over 4 gigabytes, except for the “odc” variant, which can support files up to 8 gigabytes. macOS 14.5 September 16, 2014 macOS 14.5
h2ph5.34
h2ph converts any C header files specified to the corresponding Perl header file format. It is most easily run while in /usr/include: cd /usr/include; h2ph * sys/* or cd /usr/include; h2ph * sys/* arpa/* netinet/* or cd /usr/include; h2ph -r -l . The output files are placed in the hierarchy rooted at Perl's architecture dependent library directory. You can specify a different hierarchy with a -d switch. If run with no arguments, filters standard input to standard output.
h2ph - convert .h C header files to .ph Perl header files
h2ph [-d destination directory] [-r | -a] [-l] [-h] [-e] [-D] [-Q] [headerfiles]
-d destination_dir Put the resulting .ph files beneath destination_dir, instead of beneath the default Perl library location ($Config{'installsitearch'}). -r Run recursively; if any of headerfiles are directories, then run h2ph on all files in those directories (and their subdirectories, etc.). -r and -a are mutually exclusive. -a Run automagically; convert headerfiles, as well as any .h files which they include. This option will search for .h files in all directories which your C compiler ordinarily uses. -a and -r are mutually exclusive. -l Symbolic links will be replicated in the destination directory. If -l is not specified, then links are skipped over. -h Put 'hints' in the .ph files which will help in locating problems with h2ph. In those cases when you require a .ph file containing syntax errors, instead of the cryptic [ some error condition ] at (eval mmm) line nnn you will see the slightly more helpful [ some error condition ] at filename.ph line nnn However, the .ph files almost double in size when built using -h. -e If an error is encountered during conversion, output file will be removed and a warning emitted instead of terminating the conversion immediately. -D Include the code from the .h file as a comment in the .ph file. This is primarily used for debugging h2ph. -Q 'Quiet' mode; don't print out the names of the files being converted. ENVIRONMENT No environment variables are used. FILES /usr/include/*.h /usr/include/sys/*.h etc. AUTHOR Larry Wall SEE ALSO perl(1) DIAGNOSTICS The usual warnings if it can't read or write the files involved. BUGS Doesn't construct the %sizeof array for you. It doesn't handle all C constructs, but it does attempt to isolate definitions inside evals so that you can get at the definitions that it can translate. It's only intended as a rough tool. You may need to dicker with the files produced. You have to run this program by hand; it's not run as part of the Perl installation. Doesn't handle complicated expressions built piecemeal, a la: enum { FIRST_VALUE, SECOND_VALUE, #ifdef ABC THIRD_VALUE #endif }; Doesn't necessarily locate all of your C compiler's internally-defined symbols. perl v5.34.1 2024-04-13 H2PH(1)
null
nohup
The nohup utility invokes utility 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. Some shells may provide a builtin nohup command which is similar or identical to this utility. Consult the builtin(1) manual page. ENVIRONMENT The following variables are utilized by nohup: 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. PATH Used to locate the requested utility if the name contains no ‘/’ characters. EXIT STATUS The nohup utility exits with one of the following values: 126 The utility was found, but could not be invoked. 127 The utility could not be found or an error occurred in nohup. Otherwise, the exit status of nohup will be that of utility. SEE ALSO builtin(1), csh(1), signal(3) STANDARDS The nohup utility is expected to be IEEE Std 1003.2 (“POSIX.2”) compatible. BUGS Two or more instances of nohup can append to the same file, which makes for a confusing output. macOS 14.5 November 9, 2018 macOS 14.5
nohup – invoke a utility immune to hangups
nohup [--] utility [arguments]
null
null
kcc
kcc Options supported: --version version information --help help SEE ALSO kdestroy(1), kinit(1) HEIMDAL September 30, 2011 HEIMDAL
kcc – Kerberos credential cache tools
kcc [--version] [--help] [command [arguments ...]]
null
null
ulimit
Shell builtin commands are commands that can be executed within the running shell's process. Note that, in the case of csh(1) builtin commands, the command is executed in a subshell if it occurs as any component of a pipeline except the last. If a command specified to the shell contains a slash ‘/’, the shell will not execute a builtin command, even if the last component of the specified command matches the name of a builtin command. Thus, while specifying “echo” causes a builtin command to be executed under shells that support the echo builtin command, specifying “/bin/echo” or “./echo” does not. While some builtin commands may exist in more than one shell, their operation may be different under each shell which supports them. Below is a table which lists shell builtin commands, the standard shells that support them and whether they exist as standalone utilities. Only builtin commands for the csh(1) and sh(1) shells are listed here. Consult a shell's manual page for details on the operation of its builtin commands. Beware that the sh(1) manual page, at least, calls some of these commands “built-in commands” and some of them “reserved words”. Users of other shells may need to consult an info(1) page or other sources of documentation. Commands marked “No**” under External do exist externally, but are implemented as scripts using a builtin command of the same name. Command External csh(1) sh(1) ! No No Yes % No Yes No . No No Yes : No Yes Yes @ No Yes Yes [ Yes No Yes { No No Yes } No No Yes alias No** Yes Yes alloc No Yes No bg No** Yes Yes bind No No Yes bindkey No Yes No break No Yes Yes breaksw No Yes No builtin No No Yes builtins No Yes No case No Yes Yes cd No** Yes Yes chdir No Yes Yes command No** No Yes complete No Yes No continue No Yes Yes default No Yes No dirs No Yes No do No No Yes done No No Yes echo Yes Yes Yes echotc No Yes No elif No No Yes else No Yes Yes end No Yes No endif No Yes No endsw No Yes No esac No No Yes eval No Yes Yes exec No Yes Yes exit No Yes Yes export No No Yes false Yes No Yes fc No** No Yes fg No** Yes Yes filetest No Yes No fi No No Yes for No No Yes foreach No Yes No getopts No** No Yes glob No Yes No goto No Yes No hash No** No Yes hashstat No Yes No history No Yes No hup No Yes No if No Yes Yes jobid No No Yes jobs No** Yes Yes kill Yes Yes Yes limit No Yes No local No No Yes log No Yes No login Yes Yes No logout No Yes No ls-F No Yes No nice Yes Yes No nohup Yes Yes No notify No Yes No onintr No Yes No popd No Yes No printenv Yes Yes No printf Yes No Yes pushd No Yes No pwd Yes No Yes read No** No Yes readonly No No Yes rehash No Yes No repeat No Yes No return No No Yes sched No Yes No set No Yes Yes setenv No Yes No settc No Yes No setty No Yes No setvar No No Yes shift No Yes Yes source No Yes No stop No Yes No suspend No Yes No switch No Yes No telltc No Yes No test Yes No Yes then No No Yes time Yes Yes No times No No Yes trap No No Yes true Yes No Yes type No** No Yes ulimit No** No Yes umask No** Yes Yes unalias No** Yes Yes uncomplete No Yes No unhash No Yes No unlimit No Yes No unset No Yes Yes unsetenv No Yes No until No No Yes wait No** Yes Yes where No Yes No which Yes Yes No while No Yes Yes SEE ALSO csh(1), dash(1), echo(1), false(1), info(1), kill(1), login(1), nice(1), nohup(1), printenv(1), printf(1), pwd(1), sh(1), test(1), time(1), true(1), which(1), zsh(1) HISTORY The builtin manual page first appeared in FreeBSD 3.4. AUTHORS This manual page was written by Sheldon Hearn <sheldonh@FreeBSD.org>. macOS 14.5 December 21, 2010 macOS 14.5
builtin, !, %, ., :, @, [, {, }, alias, alloc, bg, bind, bindkey, break, breaksw, builtins, case, cd, chdir, command, complete, continue, default, dirs, do, done, echo, echotc, elif, else, end, endif, endsw, esac, eval, exec, exit, export, false, fc, fg, filetest, fi, for, foreach, getopts, glob, goto, hash, hashstat, history, hup, if, jobid, jobs, kill, limit, local, log, login, logout, ls-F, nice, nohup, notify, onintr, popd, printenv, printf, pushd, pwd, read, readonly, rehash, repeat, return, sched, set, setenv, settc, setty, setvar, shift, source, stop, suspend, switch, telltc, test, then, time, times, trap, true, type, ulimit, umask, unalias, uncomplete, unhash, unlimit, unset, unsetenv, until, wait, where, which, while – shell built-in commands
See the built-in command description in the appropriate shell manual page.
null
null
rails
null
null
null
null
null
bspatch
The bspatch utility generates newfile from oldfile and patchfile where patchfile is a binary patch built by bsdiff(1). The bspatch utility uses memory equal to the size of oldfile plus the size of newfile, but can tolerate a very small working set without a dramatic loss of performance. SEE ALSO bsdiff(1) AUTHORS Colin Percival <cperciva@FreeBSD.org> BUGS The bspatch utility does not verify that oldfile is the correct source file for patchfile. Attempting to apply a patch to the wrong file will usually produce garbage; consequently it is strongly recommended that users of bspatch verify that oldfile matches the source file from which patchfile was built, by comparing cryptographic hashes, for example. Users may also wish to verify after running bspatch that newfile matches the target file from which was built. macOS 14.5 May 18, 2003 macOS 14.5
bspatch – apply a patch built with bsdiff(1)
bspatch oldfile newfile patchfile
null
null
hotspot.d
hotspot.d is a simple DTrace script to determine if disk activity is occuring in the one place - a "hotspot". This helps us understand the system's usage of a disk, it does not imply that the existance or not of a hotspot is good or bad (often may be good, less seeking). Since this uses DTrace, only users with root privileges can run this command.
hotspot.d - print disk event by location. Uses DTrace.
hotspot.d
null
Sample until Ctrl-C is hit then print report, # hotspot.d FIELDS Disk disk instance name Major driver major number Minor driver minor number value location of disk event, megabytes count number of events DOCUMENTATION See the DTraceToolkit for further documentation under the Docs directory. The DTraceToolkit docs may include full worked examples with verbose descriptions explaining the output. EXIT hotspot.d will sample until Ctrl-C is hit. AUTHOR Brendan Gregg [Sydney, Australia] SEE ALSO dtrace(1M) version 0.95 May 14, 2005 hotspot.d(1m)
cvaffinity
cvaffinity can be used to set an affinity for a specific storage pool on a file or directory, or list the current affinity. An affinity is created in a storage pool through the volume configuration, see snfs_config(5). It is a name, up to eight (8) characters, describing a special media type. Use cvadmin(8) to see what affinity sets are assigned to the configured storage pools. If the affinity does not exist on any of the storage pools, a set will fail. When allocating space for a file with an affinity, if the affinity does not exist for any of the storage pools, or if the storage pools with the affinity cannot be used to satisfy an allocation request, then the allocation will occur on the non-exclusive storage pools. If there is no non-exclusive storage pools, an ENOSPC is returned. See also AffinityPreference in snfs_config(5). If a file does not have an affinity, it cannot have space allocated to it on storage pools that have any affinities and are configured to be exclusive. A common way to use the affinity capability, is to create a directory with cvmkdir(1) and have all files and directories below that directory inherit the affinity. Also, files can be created and have space pre- allocated with an affinity using cvmkfile(1). For automatic affinity mapping for certain files, see autoAffinity and autoAffinities in snfs_config(5) and snfs.cfgx(5).
cvaffinity - set, get, or delete the affinity of a file or directory
cvaffinity -s_key filename cvaffinity -l filename cvaffinity -d filename
-s key Set the given key to be the Affinity Key of the given file or directory. This key must be configured as an Affinity in the storage pool section of the file system configuration. Use cvadmin(8) to see the affinities in this file system. For files with an Affinity, new blocks allocated to that file are placed on a storage pool with the specified Affinity. For directories with an Affinity new files created in that directory inherit the Affinity from the directory. -l This option says to just list the affinity for the specified file and exit. -d This option says to delete the affinity from the specified file or directory, if one exists. filename Specifies the file or directory operated on.
List the affinity on the file /usr/clips/foo. rock # cvaffinity -l /usr/clips/foo Set this file or directory to use the storage pool that has the jmfn8 affinity type. rock # cvaffinity -s jmfn8 /usr/clips/filename Remove the affinity from the /usr/clips/mydir, if one is currently assigned. rock # cvaffinity -d /usr/clips/mydir SEE ALSO snfs_config(5), cvadmin(8) Xsan File System January 2020 CVAFFINITY(1)
xsubpp5.34
This compiler is typically run by the makefiles created by ExtUtils::MakeMaker or by Module::Build or other Perl module build tools. xsubpp will compile XS code into C code by embedding the constructs necessary to let C functions manipulate Perl values and creates the glue necessary to let Perl access those functions. The compiler uses typemaps to determine how to map C function parameters and variables to Perl values. The compiler will search for typemap files called typemap. It will use the following search path to find default typemaps, with the rightmost typemap taking precedence. ../../../typemap:../../typemap:../typemap:typemap It will also use a default typemap installed as "ExtUtils::typemap".
xsubpp - compiler to convert Perl XS code into C code
xsubpp [-v] [-except] [-s pattern] [-prototypes] [-noversioncheck] [-nolinenumbers] [-nooptimize] [-typemap typemap] [-output filename]... file.xs
Note that the "XSOPT" MakeMaker option may be used to add these options to any makefiles generated by MakeMaker. -hiertype Retains '::' in type names so that C++ hierarchical types can be mapped. -except Adds exception handling stubs to the C code. -typemap typemap Indicates that a user-supplied typemap should take precedence over the default typemaps. This option may be used multiple times, with the last typemap having the highest precedence. -output filename Specifies the name of the output file to generate. If no file is specified, output will be written to standard output. -v Prints the xsubpp version number to standard output, then exits. -prototypes By default xsubpp will not automatically generate prototype code for all xsubs. This flag will enable prototypes. -noversioncheck Disables the run time test that determines if the object file (derived from the ".xs" file) and the ".pm" files have the same version number. -nolinenumbers Prevents the inclusion of '#line' directives in the output. -nooptimize Disables certain optimizations. The only optimization that is currently affected is the use of targets by the output C code (see perlguts). This may significantly slow down the generated code, but this is the way xsubpp of 5.005 and earlier operated. -noinout Disable recognition of "IN", "OUT_LIST" and "INOUT_LIST" declarations. -noargtypes Disable recognition of ANSI-like descriptions of function signature. -C++ Currently doesn't do anything at all. This flag has been a no-op for many versions of perl, at least as far back as perl5.003_07. It's allowed here for backwards compatibility. -s=... or -strip=... This option is obscure and discouraged. If specified, the given string will be stripped off from the beginning of the C function name in the generated XS functions (if it starts with that prefix). This only applies to XSUBs without "CODE" or "PPCODE" blocks. For example, the XS: void foo_bar(int i); when "xsubpp" is invoked with "-s foo_" will install a "foo_bar" function in Perl, but really call bar(i) in C. Most of the time, this is the opposite of what you want and failure modes are somewhat obscure, so please avoid this option where possible. ENVIRONMENT No environment variables are used. AUTHOR Originally by Larry Wall. Turned into the "ExtUtils::ParseXS" module by Ken Williams. MODIFICATION HISTORY See the file Changes. SEE ALSO perl(1), perlxs(1), perlxstut(1), ExtUtils::ParseXS perl v5.34.1 2024-04-13 XSUBPP(1)
null
gatherheaderdoc
Gatherheaderdoc processes the headerdoc output in directory and creates an index page that links to each header's documentation. FILES /$HOME/Library/Preferences/com.apple.headerDoc2HTML.config SEE ALSO headerdoc2html(1) For more information, see the HeaderDoc User Guide. It can be found in /Developer/Documentation/ if you have the Xcode Tools package installed, or at <http://developer.apple.com/documentation/DeveloperTools/Conceptual/HeaderDoc> in the reference library. Darwin June 13, 2003 Darwin
gatherheaderdoc – header documentation processor
gatherheaderdoc [options] directory
null
null
ppdi
ppdi imports one or more PPD files into a PPD compiler source file. Multiple languages of the same PPD file are merged into a single printer definition to facilitate accurate changes for all localizations. This program is deprecated and will be removed in a future release of CUPS.
ppdi - import ppd files (deprecated)
ppdi [ -I include-directory ] [ -o source-file ] ppd-file [ ... ppd-file ]
ppdi supports the following options: -I include-directory Specifies an alternate include directory. Multiple -I options can be supplied to add additional directories. -o source-file Specifies the PPD source file to update. If the source file does not exist, a new source file is created. Otherwise the existing file is merged with the new PPD file(s) on the command-line. If no source file is specified, the filename ppdi.drv is used. NOTES PPD files are deprecated and will no longer be supported in a future feature release of CUPS. Printers that do not support IPP can be supported using applications such as ippeveprinter(1). SEE ALSO ppdc(1), ppdhtml(1), ppdmerge(1), ppdpo(1), ppdcfile(5), CUPS Online Help (http://localhost:631/help) COPYRIGHT Copyright © 2007-2019 by Apple Inc. 26 April 2019 CUPS ppdi(1)
null
pcap-config
When run with the --cflags option, pcap-config writes to the standard output the -I compiler flags required to include libpcap's header files. When run with the --libs option, pcap-config writes to the standard output the -L and -l linker flags required to link with libpcap, including -l flags for libraries required by libpcap. When run with the --additional-libs option, pcap-config writes to the standard output the -L and -l flags for libraries required by libpcap, but not the -lpcap flag to link with libpcap itself. By default, it writes flags appropriate for compiling with a dynamically-linked version of libpcap; the --static flag causes it to write flags appropriate for compiling with a statically-linked version of libpcap. SEE ALSO pcap(3PCAP) 15 February 2015 PCAP-CONFIG(1)
pcap-config - write libpcap compiler and linker flags to standard output
pcap-config [ --static ] [ --cflags | --libs | --additional-libs ]
null
null
jpackage
The jpackage tool will take as input a Java application and a Java run- time image, and produce a Java application image that includes all the necessary dependencies. It will be able to produce a native package in a platform-specific format, such as an exe on Windows or a dmg on macOS. Each format must be built on the platform it runs on, there is no cross-platform support. The tool will have options that allow packaged applications to be customized in various ways. JPACKAGE OPTIONS Generic Options: @filename Read options from a file. This option can be used multiple times. --type or -t type The type of package to create Valid values are: {"app-image", "exe", "msi", "rpm", "deb", "pkg", "dmg"} If this option is not specified a platform dependent default type will be created. --app-version version Version of the application and/or package --copyright copyright Copyright for the application --description description Description of the application --help or -h Print the usage text with a list and description of each valid option for the current platform to the output stream, and exit. --icon path Path of the icon of the application package (absolute path or relative to the current directory) --name or -n name Name of the application and/or package --dest or -d destination Path where generated output file is placed (absolute path or relative to the current directory). Defaults to the current working directory. --temp directory Path of a new or empty directory used to create temporary files (absolute path or relative to the current directory) If specified, the temp dir will not be removed upon the task completion and must be removed manually. If not specified, a temporary directory will be created and removed upon the task completion. --vendor vendor Vendor of the application --verbose Enables verbose output. --version Print the product version to the output stream and exit. Options for creating the runtime image: --add-modules module-name [,module-name...] A comma (",") separated list of modules to add This module list, along with the main module (if specified) will be passed to jlink as the --add-module argument. If not specified, either just the main module (if --module is specified), or the default set of modules (if --main-jar is specified) are used. This option can be used multiple times. --module-path or -p module-path [,module-path...] A File.pathSeparator separated list of paths Each path is either a directory of modules or the path to a modular jar, and is absolute or relative to the current directory. This option can be used multiple times. --jlink-options options A space separated list of options to pass to jlink If not specified, defaults to "--strip-native-commands --strip- debug --no-man-pages --no-header-files" This option can be used multiple times. --runtime-image directory Path of the predefined runtime image that will be copied into the application image (absolute path or relative to the current directory) If --runtime-image is not specified, jpackage will run jlink to create the runtime image using options specified by --jlink- options. Options for creating the application image: --input or -i directory Path of the input directory that contains the files to be packaged (absolute path or relative to the current directory) All files in the input directory will be packaged into the application image. `--app-content additional-content[,additional-content...] A comma separated list of paths to files and/or directories to add to the application payload. This option can be used more than once. Options for creating the application launcher(s): --add-launcher name=path Name of launcher, and a path to a Properties file that contains a list of key, value pairs (absolute path or relative to the current directory) The keys "module", "main-jar", "main-class", "description", "arguments", "java-options", "app-version", "icon", "launcher- as-service", "win-console", "win-shortcut", "win-menu", "linux- app-category", and "linux-shortcut" can be used. These options are added to, or used to overwrite, the original command line options to build an additional alternative launcher. The main application launcher will be built from the command line options. Additional alternative launchers can be built using this option, and this option can be used multiple times to build multiple additional launchers. --arguments arguments Command line arguments to pass to the main class if no command line arguments are given to the launcher This option can be used multiple times. --java-options options Options to pass to the Java runtime This option can be used multiple times. --main-class class-name Qualified name of the application main class to execute This option can only be used if --main-jar is specified. --main-jar main-jar The main JAR of the application; containing the main class (specified as a path relative to the input path) Either --module or --main-jar option can be specified but not both. --module or -m module-name[/main-class] The main module (and optionally main class) of the application This module must be located on the module path. When this option is specified, the main module will be linked in the Java runtime image. Either --module or --main-jar option can be specified but not both. Platform dependent option for creating the application launcher: Windows platform options (available only when running on Windows): --win-console Creates a console launcher for the application, should be specified for application which requires console interactions macOS platform options (available only when running on macOS): --mac-package-identifier identifier An identifier that uniquely identifies the application for macOS Defaults to the main class name. May only use alphanumeric (A-Z,a-z,0-9), hyphen (-), and period (.) characters. --mac-package-name name Name of the application as it appears in the Menu Bar This can be different from the application name. This name must be less than 16 characters long and be suitable for displaying in the menu bar and the application Info window. Defaults to the application name. --mac-package-signing-prefix prefix When signing the application package, this value is prefixed to all components that need to be signed that don't have an existing package identifier. --mac-sign Request that the package or the predefined application image be signed. --mac-signing-keychain keychain-name Name of the keychain to search for the signing identity If not specified, the standard keychains are used. --mac-signing-key-user-name name Team or user name portion in Apple signing identities --mac-app-store Indicates that the jpackage output is intended for the Mac App Store. --mac-entitlements path Path to file containing entitlements to use when signing executables and libraries in the bundle --mac-app-category category String used to construct LSApplicationCategoryType in application plist The default value is "utilities". Options for creating the application package: --about-url url URL of the application's home page --app-image directory Location of the predefined application image that is used to build an installable package (on all platforms) or to be signed (on macOS) (absolute path or relative to the current directory) --file-associations path Path to a Properties file that contains list of key, value pairs (absolute path or relative to the current directory) The keys "extension", "mime-type", "icon", and "description" can be used to describe the association. This option can be used multiple times. --install-dir path Absolute path of the installation directory of the application (on macOS or linux), or relative sub-path of the installation directory such as "Program Files" or "AppData" (on Windows) --license-file path Path to the license file (absolute path or relative to the current directory) --resource-dir path Path to override jpackage resources (absolute path or relative to the current directory) Icons, template files, and other resources of jpackage can be over-ridden by adding replacement resources to this directory. --runtime-image path Path of the predefined runtime image to install (absolute path or relative to the current directory) Option is required when creating a runtime installer. --launcher-as-service Request to create an installer that will register the main application launcher as a background service-type application. Platform dependent options for creating the application package: Windows platform options (available only when running on Windows): --win-dir-chooser Adds a dialog to enable the user to choose a directory in which the product is installed. --win-help-url url URL where user can obtain further information or technical support --win-menu Request to add a Start Menu shortcut for this application --win-menu-group menu-group-name Start Menu group this application is placed in --win-per-user-install Request to perform an install on a per-user basis --win-shortcut Request to create a desktop shortcut for this application --win-shortcut-prompt Adds a dialog to enable the user to choose if shortcuts will be created by installer --win-update-url url URL of available application update information --win-upgrade-uuid id UUID associated with upgrades for this package Linux platform options (available only when running on Linux): --linux-package-name name Name for Linux package Defaults to the application name. --linux-deb-maintainer email-address Maintainer for .deb bundle --linux-menu-group menu-group-name Menu group this application is placed in --linux-package-deps Required packages or capabilities for the application --linux-rpm-license-type type Type of the license ("License: value" of the RPM .spec) --linux-app-release release Release value of the RPM <name>.spec file or Debian revision value of the DEB control file --linux-app-category category-value Group value of the RPM /.spec file or Section value of DEB control file --linux-shortcut Creates a shortcut for the application. macOS platform options (available only when running on macOS): '--mac-dmg-content additional-content[,additional-content...] Include all the referenced content in the dmg. This option can be used more than once. JPACKAGE EXAMPLES Generate an application package suitable for the host system: For a modular application: jpackage -n name -p modulePath -m moduleName/className For a non-modular application: jpackage -i inputDir -n name \ --main-class className --main-jar myJar.jar From a pre-built application image: jpackage -n name --app-image appImageDir Generate an application image: For a modular application: jpackage --type app-image -n name -p modulePath \ -m moduleName/className For a non-modular application: jpackage --type app-image -i inputDir -n name \ --main-class className --main-jar myJar.jar To provide your own options to jlink, run jlink separately: jlink --output appRuntimeImage -p modulePath \ --add-modules moduleName \ --no-header-files [<additional jlink options>...] jpackage --type app-image -n name \ -m moduleName/className --runtime-image appRuntimeImage Generate a Java runtime package: jpackage -n name --runtime-image <runtime-image> Sign the predefined application image (on macOS): jpackage --type app-image --app-image <app-image> \ --mac-sign [<additional signing options>...] Note: the only additional options that are permitted in this mode are: the set of additional mac signing options and --verbose JPACKAGE RESOURCE DIRECTORY Icons, template files, and other resources of jpackage can be over- ridden by adding replacement resources to this directory. jpackage will lookup files by specific names in the resource directory. Resource directory files considered only when running on Linux: <launcher-name>.png Application launcher icon Default resource is JavaApp.png <launcher-name>.desktop A desktop file to be used with xdg-desktop-menu command Considered with application launchers registered for file associations and/or have an icon Default resource is template.desktop Resource directory files considered only when building Linux DEB/RPM installer: <package-name>-<launcher-name>.service systemd unit file for application launcher registered as a background service-type application Default resource is unit-template.service Resource directory files considered only when building Linux RPM installer: <package-name>.spec RPM spec file Default resource is template.spec Resource directory files considered only when building Linux DEB installer: control Control file Default resource is template.control copyright Copyright file Default resource is template.copyright preinstall Pre-install shell script Default resource is template.preinstall prerm Pre-remove shell script Default resource is template.prerm postinstall Post-install shell script Default resource is template.postinstall postrm Post-remove shell script Default resource is template.postrm Resource directory files considered only when running on Windows: <launcher-name>.ico Application launcher icon Default resource is JavaApp.ico <launcher-name>.properties Properties file for application launcher executable Default resource is WinLauncher.template Resource directory files considered only when building Windows MSI/EXE installer: <application-name>-post-image.wsf A Windows Script File (WSF) to run after building application image main.wxs Main WiX project file Default resource is main.wxs overrides.wxi Overrides WiX project file Default resource is overrides.wxi service-installer.exe Service installer executable Considered if some application launchers are registered as background service-type applications <launcher-name>-service-install.wxi Service installer WiX project file Considered if some application launchers are registered as background service-type applications Default resource is service-install.wxi <launcher-name>-service-config.wxi Service installer WiX project file Considered if some application launchers are registered as background service-type applications Default resource is service-config.wxi InstallDirNotEmptyDlg.wxs WiX project file for installer UI dialog checking installation directory doesn't exist or is empty Default resource is InstallDirNotEmptyDlg.wxs ShortcutPromptDlg.wxs WiX project file for installer UI dialog configuring shortcuts Default resource is ShortcutPromptDlg.wxs bundle.wxf WiX project file with the hierarchy of components of application image ui.wxf WiX project file for installer UI Resource directory files considered only when building Windows EXE installer: WinInstaller.properties Properties file for the installer executable Default resource is WinInstaller.template <package-name>-post-msi.wsf A Windows Script File (WSF) to run after building embedded MSI installer for EXE installer Resource directory files considered only when running on macOS: <launcher-name>.icns Application launcher icon Default resource is JavaApp.icns Info.plist Application property list file Default resource is Info-lite.plist.template Runtime-Info.plist Java Runtime property list file Default resource is Runtime-Info.plist.template <application-name>.entitlements Signing entitlements property list file Default resource is sandbox.plist Resource directory files considered only when building macOS PKG/DMG installer: <package-name>-post-image.sh Shell script to run after building application image Resource directory files considered only when building macOS PKG installer: uninstaller Uninstaller shell script Considered if some application launchers are registered as background service-type applications Default resource is uninstall.command.template preinstall Pre-install shell script Default resource is preinstall.template postinstall Post-install shell script Default resource is postinstall.template services-preinstall Pre-install shell script for services package Considered if some application launchers are registered as background service-type applications Default resource is services-preinstall.template services-postinstall Post-install shell script for services package Considered if some application launchers are registered as background service-type applications Default resource is services-postinstall.template <package-name>-background.png Background image Default resource is background_pkg.png <package-name>-background-darkAqua.png Dark background image Default resource is background_pkg.png product-def.plist Package property list file Default resource is product-def.plist <package-name>-<launcher-name>.plist launchd property list file for application launcher registered as a background service-type application Default resource is launchd.plist.template Resource directory files considered only when building macOS DMG installer: <package-name>-dmg-setup.scpt Setup AppleScript script Default resource is DMGsetup.scpt <package-name>-license.plist License property list file Default resource is lic_template.plist <package-name>-background.tiff Background image Default resource is background_dmg.tiff <package-name>-volume.icns Volume icon Default resource is JavaApp.icns JDK 22 2024 JPACKAGE(1)
jpackage - tool for packaging self-contained Java applications.
jpackage [options]
Command-line options separated by spaces. See jpackage Options.
null
avmetareadwrite
null
null
null
null
null
gen_bridge_metadata
gen_bridge_metadata is a tool that generates bridging metadata information for a given framework or set of headers. The Objective-C bridges supported in Mac OS X, such as PyObjC (Python), read this information at runtime. As of Mac OS 10.7, gen_bridge_metadata uses an improved parser, based on clang. This means the generated files should be more correct and complete, and the true parsing allows the automatic extraction of metadata from existing __attribute__() information supported by the compiler. File generation time should also be faster. Metadata files describe the parts of an Objective-C framework that the bridges cannot automatically handle. These are primarily the ANSI C elements of the framework -- functions, constants, enumerations, and so on -- but also include special cases such as functions or methods that accept pointer-like arguments. These special cases must be manually specified in separate files called exceptions. The gen_bridge_metadata tool can then read in the exceptions file when it generates the framework metadata. The file extension used for x86_64 metadata files should be .bridgesupport. The extension for arm64e metadata files should be .arm64e.bridgesupport. Certain elements, such as inline functions, cannot be described in the metadata files. It is therefore required to generate a dynamic library in order to make the bridges use them. The gen_bridge_metadata tool can take care of that for you. The file extension for the dynamic libraries should be .dylib. You should install metadata files in one of three filesystem locations. For example, for a framework named MyFramework that is installed as /Library/Frameworks/MyFramework.framework, you can install the MyFramework.bridgesupport and MyFramework.dylib files in one of the following possible locations, in order of priority: • /Library/Frameworks/MyFramework/Resources/BridgeSupport • /Library/BridgeSupport • ~/Library/BridgeSupport
gen_bridge_metadata – Objective-C Bridges Metadata Generator
gen_bridge_metadata [options...] headers...
The gen_bridge_metadata tool accepts the following command-line options: -f framework, --framework framework Generates metadata for the given framework. This argument can accept both the name of a framework of an absolute path to a framework. When passing a framework name, the program will try to locate the framework in one of the standard framework locations. -p, --private Generates metadata based on the private headers of the given frameworks. This argument must be used with the -f argument. -F format, --format format Selects the metadata format that will be generated. Possible values are: final The final metadata format. This is the default value. dylib The dynamic library format. This is only required if you want to support inline functions. In order to use this format you need to pass a value for the -o argument. exceptions-template This will generate an exception template. Please consult BridgeSupport(5) for more details about the exception format. Once your exception file is finished you can pass it to the -e argument in order to generate the final metadata. -e file, --exception file Considers the given exception file when generating the final metadata format. The given exception file must conform to a certain format, described in bridgeSupport(5). Exception files are manually written, but you can generate a template by passing -F exceptions-template to the generator. --arm64e Write arm64e annotations instead of x86_64 and compiles the dylib as arm64e. If a dylib already exists at the output file path, a multi- architecture file will be created. An arm64e slice will be added to an x86_64 dylib. Conversely, if an arm64e dylib exists first, running the generator without the --arm64e argument will add an x86_64 slice. --64-bit This option has no effect. It is included for backwards compatibility, as 32-bit support is deprecated. Only 64-bit support exists. --no-32-bit This option has no effect. It is included for backwards compatibility, as 32-bit support is deprecated. Only 64-bit support exists. --no-64-bit This option has no effect. It is included for backwards compatibility, as 32-bit support is deprecated. Only 64-bit support exists. -c, --cflags flags Provides custom flags that will be passed to the C compiler. The generator compiles and executes several C and Objective-C programs during the generation of the final metadata format. Some flags are determined by default, but you might want to provide your own flags according to the piece of code you want to generate metadata for (for example, a framework part of a umbrella framework). -C, --cflags-64 flags Provides custom flags that will be passed to the C compiler, when generating 64-bit annotations. By default the same flags are passed to the C compiler when generating both 32-bit and 64-bit annotations. -o, --output file Writes the output to the given file. This argument is mandatory when generating the “dylib” format. For other formats, by default the output is redirected to the standard output. -h, --help Prints a summary of the options. -d, --debug Turns on debugging messages. You probably don't want to enable this option, unless you are going to debug the metadata generator. -v, --version Shows the version of the program. The version is also marked in generated metadata files, as the “version” attribute of the “signatures” top-level element.
This generates bridge support metadata for a custom framework: mkdir -p /Path/To/YourFramework.framework/Resources/BridgeSupport gen_bridge_metadata -f /Path/To/YourFramework.framework -o /Path/To/YourFramework.framework/Resources/BridgeSupport/YourFramework.bridgesupport If the custom framework has inline functions and you want to be able to call them, here is how you can generate a “dylib” file: gen_bridge_metadata -f /Path/To/YourFramework.framework -F dylib -o /Path/To/YourFramework.framework/Resources/BridgeSupport/YourFramework.dylib It is also possible to generate bridge support metadata for a standalone C library (here, libcurl): gen_bridge_metadata -c '-lcurl -I/usr/include/curl' /usr/include/curl/*.h > /Library/BridgeSupport/curl.bridgesupport SEE ALSO BridgeSupport(5) /System/Library/DTDs/BridgeSupport.dtd ruby(1) python(1) macOS 14.5 May 24, 2010 macOS 14.5
parl5.34
This stand-alone command offers roughly the same feature as "perl -MPAR", except that it takes the pre-loaded .par files via "-Afoo.par" instead of "-MPAR=foo.par". Additionally, it lets you convert a CPAN distribution to a PAR distribution, as well as manipulate such distributions. For more information about PAR distributions, see PAR::Dist. You can use it to run .par files: # runs script/run.pl in archive, uses its lib/* as libraries % parl myapp.par run.pl # runs run.pl or script/run.pl in myapp.par % parl otherapp.pl # also runs normal perl scripts However, if the .par archive contains either main.pl or script/main.pl, it is used instead: % parl myapp.par run.pl # runs main.pl, with 'run.pl' as @ARGV Finally, the "-O" option makes a stand-alone binary executable from a PAR file: % parl -B -Omyapp myapp.par % ./myapp # run it anywhere without perl binaries With the "--par-options" flag, generated binaries can act as "parl" to pack new binaries: % ./myapp --par-options -Omyap2 myapp.par # identical to ./myapp % ./myapp --par-options -Omyap3 myap3.par # now with different PAR For an explanation of stand-alone executable format, please see par.pl. SEE ALSO PAR, PAR::Dist, par.pl, pp AUTHORS Audrey Tang <cpan@audreyt.org> You can write to the mailing list at <par@perl.org>, or send an empty mail to <par-subscribe@perl.org> to participate in the discussion. Please submit bug reports to <bug-par-packer@rt.cpan.org>. COPYRIGHT Copyright 2002-2009 by Audrey Tang <cpan@audreyt.org>. Neither this program nor the associated pp program impose any licensing restrictions on files generated by their execution, in accordance with the 8th article of the Artistic License: "Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package." Therefore, you are absolutely free to place any license on the resulting executable, as long as the packed 3rd-party libraries are also available under the Artistic License. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See LICENSE. perl v5.34.0 2020-03-08 PARL(1)
parl - Binary PAR Loader
(Please see pp for convenient ways to make self-contained executables, scripts or PAR archives from perl programs.) To make a PAR distribution from a CPAN module distribution: % parl -p # make a PAR dist under the current path % parl -p Foo-0.01 # assume unpacked CPAN dist in Foo-0.01/ To manipulate a PAR distribution: % parl -i Foo-0.01-i386-freebsd-5.8.0.par # install % parl -i http://foo.com/Foo-0.01 # auto-appends archname + perlver % parl -i cpan://AUTRIJUS/PAR-0.74 # uses CPAN author directory % parl -u Foo-0.01-i386-freebsd-5.8.0.par # uninstall % parl -s Foo-0.01-i386-freebsd-5.8.0.par # sign % parl -v Foo-0.01-i386-freebsd-5.8.0.par # verify To use Hello.pm from ./foo.par: % parl -A./foo.par -MHello % parl -A./foo -MHello # the .par part is optional Same thing, but search foo.par in the @INC; % parl -Ifoo.par -MHello % parl -Ifoo -MHello # ditto Run test.pl or script/test.pl from foo.par: % parl foo.par test.pl # looks for 'main.pl' by default, # otherwise run 'test.pl' To make a self-containing executable containing a PAR file : % parl -O./foo foo.par % ./foo test.pl # same as above To embed the necessary non-core modules and shared objects for PAR's execution (like "Zlib", "IO", "Cwd", etc), use the -b flag: % parl -b -O./foo foo.par % ./foo test.pl # runs anywhere with core modules installed If you also wish to embed core modules along, use the -B flag instead: % parl -B -O./foo foo.par % ./foo test.pl # runs anywhere with the perl interpreter This is particularly useful when making stand-alone binary executables; see pp for details.
null
null
gem
RubyGems is a sophisticated package manager for the Ruby programming language. On OS X the default bindir for gems that install binaries is /Library/Ruby/bin. For more information about it, you can use its --help flag. There is also online documentation available at "http://docs.rubygems.org". SEE ALSO ruby(1) AUTHORS RubyGems was originally developed at RubyConf 2003 by Rich Kilmer, Chad Fowler, David Black, Paul Brannan and Jim Weirch, and has received a lot of contributions since then. You can obtain the RubyGems sources at http://rubyforge.org/projects/rubygems/. macOS 14.5 February 6, 2013 macOS 14.5
gem – RubyGems program
gem command [arguments...] [options...]
null
null
spfd5.30
spfd is a simple forking Sender Policy Framework (SPF) query proxy server. spfd receives and answers SPF query requests on a TCP/IP or UNIX domain socket. The --port form listens on a TCP/IP socket on the specified port. The default port is 5970. The --socket form listens on a UNIX domain socket that is created with the specified filename. The socket can be assigned specific user and group ownership with the --socket-user and --socket-group options, and specific filesystem permissions with the --socket-perms option. Generally, spfd can be instructed with the --set-user and --set-group options to drop root privileges and change to another user and group before it starts listening for requests. The --help form prints usage information for spfd. REQUEST A request consists of a series of lines delimited by \x0A (LF) characters (or whatever your system considers a newline). Each line must be of the form key=value, where the following keys are required: ip The sender IP address. sender The envelope sender address (from the SMTP "MAIL FROM" command). helo The envelope sender hostname (from the SMTP "HELO" command). RESPONSE spfd responds to query requests with similar series of lines of the form key=value. The most important response keys are: result The result of the SPF query: pass The specified IP address is an authorized mailer for the sender domain/address. fail The specified IP address is not an authorized mailer for the sender domain/address. softfail The specified IP address is not an authorized mailer for the sender domain/address, however the domain is still in the process of transitioning to SPF. neutral The sender domain makes no assertion about the status of the IP address. unknown The sender domain has a syntax error in its SPF record. error A temporary DNS error occurred while resolving the sender policy. Try again later. none There is no SPF record for the sender domain. smtp_comment The text that should be included in the receiver's SMTP response. header_comment The text that should be included as a comment in the message's "Received-SPF:" header. spf_record The SPF record of the envelope sender domain. For the description of other response keys see Mail::SPF::Query. For more information on SPF see <http://www.openspf.org>. EXAMPLE A running spfd could be tested using the "netcat" utility like this: $ echo -e "ip=11.22.33.44\nsender=user@pobox.com\nhelo=spammer.example.net\n" | nc localhost 5970 result=neutral smtp_comment=Please see http://spf.pobox.com/why.html?sender=user%40pobox.com&ip=11.22.33.44&receiver=localhost header_comment=localhost: 11.22.33.44 is neither permitted nor denied by domain of user@pobox.com guess=neutral smtp_guess= header_guess= guess_tf=neutral smtp_tf= header_tf= spf_record=v=spf1 ?all SEE ALSO Mail::SPF::Query, <http://www.openspf.org> AUTHORS This version of spfd was written by Meng Weng Wong <mengwong+spf@pobox.com>. Improved argument parsing was added by Julian Mehnle <julian@mehnle.net>. This man-page was written by Julian Mehnle <julian@mehnle.net>. perl v5.30.3 2006-02-07 SPFD(1)
spfd - simple forking daemon to provide SPF query services VERSION 2006-02-07
spfd --port port [--set-user uid|username] [--set-group gid|groupname] spfd --socket filename [--socket-user uid|username] [--socket-group gid|groupname] [--socket-perms octal-perms] [--set-user uid|username] [--set-group gid|groupname] spfd --help
null
null
opendiff
opendiff is a command line utility that provides a convenient way to launch the FileMerge application from Terminal to graphically compare files or directories. If FileMerge is already running, opendiff will connect to that running instance for the new comparison. opendiff exits immediately after the comparison request has been sent to FileMerge. opendiff and FileMerge can be used to compare two files file1 and file2 or to compare two directories dir1 and dir2. If the -ancestor flag is given, FileMerge will compare the two files or directories to a common ancestor. This is useful if two people independently modify copies of a single original file or directory. FileMerge lets you merge two files or directories together to create a third file or directory. To see the contents of a merged file, drag the splitter bar at the bottom of FileMerge's file comparison window. The contents of the merged file can be directly edited within FileMerge. After editing, the merged file can be saved to the file (or into the directory) specified with the -merge flag. If a destination is not specified with the -merge flag, FileMerge will ask for a destination file or directory when you try to save a merged file. For further information, please consult the Help information available from the FileMerge application. FILES opendiff and FileMerge are installed as part of the Xcode Developer Tools. SEE ALSO diff(1), diff3(1), cmp(1) Xcode 2016-09-02 Xcode
opendiff – Use FileMerge to graphically compare or merge file or directories
opendiff file1 file2 [-ancestor ancestorFile] [-merge mergeFile] opendiff dir1 dir2 [-ancestor ancestorDirectory] [-merge mergeDirectory]
null
null
crc325.30
null
null
null
null
null
talk
The talk utility is a visual communication program which copies lines from your terminal to that of another user. Options available: person If you wish to talk to someone on your own machine, then person is just the person's login name. If you wish to talk to a user on another host, then person is of the form ‘user@host’ or ‘host!user’ or ‘host:user’. ttyname If you wish to talk to a user who is logged in more than once, the ttyname argument may be used to indicate the appropriate terminal name, where ttyname is of the form ‘ttyXX’. When first called, talk sends the message Message from TalkDaemon@his_machine... talk: connection requested by your_name@your_machine. talk: respond with: talk your_name@your_machine to the user you wish to talk to. At this point, the recipient of the message should reply by typing talk your_name@your_machine It does not matter from which machine the recipient replies, as long as his login-name is the same. Once communication is established, the two parties may type simultaneously, with their output appearing in separate windows. Typing control-L ‘^L’ will cause the screen to be reprinted. Typing control-D ‘^D’ will clear both parts of your screen to be cleared, while the control-D character will be sent to the remote side (and just displayed by this talk client). Your erase, kill, and word kill characters will behave normally. To exit, just type your interrupt character; talk then moves the cursor to the bottom of the screen and restores the terminal to its previous state. Permission to talk may be denied or granted by use of the mesg(1) command. At the outset talking is allowed. CONFIGURATION The talk utility relies on the talkd system daemon. See talkd(8) for information about enabling talkd. FILES /etc/hosts to find the recipient's machine /var/run/utmpx to find the recipient's tty SEE ALSO mail(1), mesg(1), wall(1), who(1), write(1), talkd(8) HISTORY The talk command appeared in 4.2BSD. In FreeBSD 5.3, the default behaviour of talk was changed to treat local- to-local talk requests as originating and terminating at localhost. Before this change, it was required that the hostname (as per gethostname(3)) resolved to a valid IPv4 address (via gethostbyname(3)), making talk unsuitable for use in configurations where talkd(8) was bound to the loopback interface (normally for security reasons). BUGS The version of talk released with 4.3BSD uses a protocol that is incompatible with the protocol used in the version released with 4.2BSD. Multibyte characters are not recognized. macOS 14.5 January 21, 2010 macOS 14.5
talk – talk to another user
talk person [ttyname]
null
null
expect
null
expect - programmed dialogue with interactive programs, Version 5
expect [ -dDinN ] [ -c cmds ] [ [ -[f|b] ] cmdfile ] [ args ] INTRODUCTION Expect is a program that "talks" to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be. An interpreted language provides branching and high-level control structures to direct the dialogue. In addition, the user can take control and interact directly when desired, afterward returning control to the script. Expectk is a mixture of Expect and Tk. It behaves just like Expect and Tk's wish. Expect can also be used directly in C or C++ (that is, without Tcl). See libexpect(3). The name "Expect" comes from the idea of send/expect sequences popularized by uucp, kermit and other modem control programs. However unlike uucp, Expect is generalized so that it can be run as a user- level command with any program and task in mind. Expect can actually talk to several programs at the same time. For example, here are some things Expect can do: • Cause your computer to dial you back, so that you can login without paying for the call. • Start a game (e.g., rogue) and if the optimal configuration doesn't appear, restart it (again and again) until it does, then hand over control to you. • Run fsck, and in response to its questions, answer "yes", "no" or give control back to you, based on predetermined criteria. • Connect to another network or BBS (e.g., MCI Mail, CompuServe) and automatically retrieve your mail so that it appears as if it was originally sent to your local system. • Carry environment variables, current directory, or any kind of information across rlogin, telnet, tip, su, chgrp, etc. There are a variety of reasons why the shell cannot perform these tasks. (Try, you'll see.) All are possible with Expect. In general, Expect is useful for running any program which requires interaction between the program and the user. All that is necessary is that the interaction can be characterized programmatically. Expect can also give the user back control (without halting the program being controlled) if desired. Similarly, the user can return control to the script at any time. USAGE Expect reads cmdfile for a list of commands to execute. Expect may also be invoked implicitly on systems which support the #! notation by marking the script executable, and making the first line in your script: #!/usr/local/bin/expect -f Of course, the path must accurately describe where Expect lives. /usr/local/bin is just an example. The -c flag prefaces a command to be executed before any in the script. The command should be quoted to prevent being broken up by the shell. This option may be used multiple times. Multiple commands may be executed with a single -c by separating them with semicolons. Commands are executed in the order they appear. (When using Expectk, this option is specified as -command.) The -d flag enables some diagnostic output, which primarily reports internal activity of commands such as expect and interact. This flag has the same effect as "exp_internal 1" at the beginning of an Expect script, plus the version of Expect is printed. (The strace command is useful for tracing statements, and the trace command is useful for tracing variable assignments.) (When using Expectk, this option is specified as -diag.) The -D flag enables an interactive debugger. An integer value should follow. The debugger will take control before the next Tcl procedure if the value is non-zero or if a ^C is pressed (or a breakpoint is hit, or other appropriate debugger command appears in the script). See the README file or SEE ALSO (below) for more information on the debugger. (When using Expectk, this option is specified as -Debug.) The -f flag prefaces a file from which to read commands from. The flag itself is optional as it is only useful when using the #! notation (see above), so that other arguments may be supplied on the command line. (When using Expectk, this option is specified as -file.) By default, the command file is read into memory and executed in its entirety. It is occasionally desirable to read files one line at a time. For example, stdin is read this way. In order to force arbitrary files to be handled this way, use the -b flag. (When using Expectk, this option is specified as -buffer.)Notethatstdio-bufferingmaystilltakeplacehoweverthisshouldn'tcauseproblemswhenreadingfromafifoorstdin. If the string "-" is supplied as a filename, standard input is read instead. (Use "./-" to read from a file actually named "-".) The -i flag causes Expect to interactively prompt for commands instead of reading them from a file. Prompting is terminated via the exit command or upon EOF. See interpreter (below) for more information. -i is assumed if neither a command file nor -c is used. (When using Expectk, this option is specified as -interactive.) -- may be used to delimit the end of the options. This is useful if you want to pass an option-like argument to your script without it being interpreted by Expect. This can usefully be placed in the #! line to prevent any flag-like interpretation by Expect. For example, the following will leave the original arguments (including the script name) in the variable argv. #!/usr/local/bin/expect -- Note that the usual getopt(3) and execve(2) conventions must be observed when adding arguments to the #! line. The file $exp_library/expect.rc is sourced automatically if present, unless the -N flag is used. (When using Expectk, this option is specified as -NORC.) Immediately after this, the file ~/.expect.rc is sourced automatically, unless the -n flag is used. If the environment variable DOTDIR is defined, it is treated as a directory and .expect.rc is read from there. (When using Expectk, this option is specified as -norc.) This sourcing occurs only after executing any -c flags. -v causes Expect to print its version number and exit. (The corresponding flag in Expectk, which uses long flag names, is -version.) Optional args are constructed into a list and stored in the variable named argv. argc is initialized to the length of argv. argv0 is defined to be the name of the script (or binary if no script is used). For example, the following prints out the name of the script and the first three arguments: send_user "$argv0 [lrange $argv 0 2]\n" COMMANDS Expect uses Tcl (Tool Command Language). Tcl provides control flow (e.g., if, for, break), expression evaluation and several other features such as recursion, procedure definition, etc. Commands used here but not defined (e.g., set, if, exec) are Tcl commands (see tcl(3)). Expect supports additional commands, described below. Unless otherwise specified, commands return the empty string. Commands are listed alphabetically so that they can be quickly located. However, new users may find it easier to start by reading the descriptions of spawn, send, expect, and interact, in that order. Note that the best introduction to the language (both Expect and Tcl) is provided in the book "Exploring Expect" (see SEE ALSO below). Examples are included in this man page but they are very limited since this man page is meant primarily as reference material. Note that in the text of this man page, "Expect" with an uppercase "E" refers to the Expect program while "expect" with a lower-case "e" refers to the expect command within the Expect program.) close [-replica] [-onexec 0|1] [-i spawn_id] closes the connection to the current process. Most interactive programs will detect EOF on their stdin and exit; thus close usually suffices to kill the process as well. The -i flag declares the process to close corresponding to the named spawn_id. Both expect and interact will detect when the current process exits and implicitly do a close. But if you kill the process by, say, "exec kill $pid", you will need to explicitly call close. The -onexec flag determines whether the spawn id will be closed in any new spawned processes or if the process is overlayed. To leave a spawn id open, use the value 0. A non-zero integer value will force the spawn closed (the default) in any new processes. The -replica flag closes the replica associated with the spawn id. (See "spawn -pty".) When the connection is closed, the replica is automatically closed as well if still open. No matter whether the connection is closed implicitly or explicitly, you should call wait to clear up the corresponding kernel process slot. close does not call wait since there is no guarantee that closing a process connection will cause it to exit. See wait below for more info. debug [[-now] 0|1] controls a Tcl debugger allowing you to step through statements, set breakpoints, etc. With no arguments, a 1 is returned if the debugger is not running, otherwise a 0 is returned. With a 1 argument, the debugger is started. With a 0 argument, the debugger is stopped. If a 1 argument is preceded by the -now flag, the debugger is started immediately (i.e., in the middle of the debug command itself). Otherwise, the debugger is started with the next Tcl statement. The debug command does not change any traps. Compare this to starting Expect with the -D flag (see above). See the README file or SEE ALSO (below) for more information on the debugger. disconnect disconnects a forked process from the terminal. It continues running in the background. The process is given its own process group (if possible). Standard I/O is redirected to /dev/null. The following fragment uses disconnect to continue running the script in the background. if {[fork]!=0} exit disconnect . . . The following script reads a password, and then runs a program every hour that demands a password each time it is run. The script supplies the password so that you only have to type it once. (See the stty command which demonstrates how to turn off password echoing.) send_user "password?\ " expect_user -re "(.*)\n" for {} 1 {} { if {[fork]!=0} {sleep 3600;continue} disconnect spawn priv_prog expect Password: send "$expect_out(1,string)\r" . . . exit } An advantage to using disconnect over the shell asynchronous process feature (&) is that Expect can save the terminal parameters prior to disconnection, and then later apply them to new ptys. With &, Expect does not have a chance to read the terminal's parameters since the terminal is already disconnected by the time Expect receives control. exit [-opts] [status] causes Expect to exit or otherwise prepare to do so. The -onexit flag causes the next argument to be used as an exit handler. Without an argument, the current exit handler is returned. The -noexit flag causes Expect to prepare to exit but stop short of actually returning control to the operating system. The user- defined exit handler is run as well as Expect's own internal handlers. No further Expect commands should be executed. This is useful if you are running Expect with other Tcl extensions. The current interpreter (and main window if in the Tk environment) remain so that other Tcl extensions can clean up. If Expect's exit is called again (however this might occur), the handlers are not rerun. Upon exiting, all connections to spawned processes are closed. Closure will be detected as an EOF by spawned processes. exit takes no other actions beyond what the normal _exit(2) procedure does. Thus, spawned processes that do not check for EOF may continue to run. (A variety of conditions are important to determining, for example, what signals a spawned process will be sent, but these are system-dependent, typically documented under exit(3).) Spawned processes that continue to run will be inherited by init. status (or 0 if not specified) is returned as the exit status of Expect. exit is implicitly executed if the end of the script is reached. exp_continue [-continue_timer] The command exp_continue allows expect itself to continue executing rather than returning as it normally would. By default exp_continue resets the timeout timer. The -continue_timer flag prevents timer from being restarted. (See expect for more information.) exp_internal [-f file] value causes further commands to send diagnostic information internal to Expect to stderr if value is non-zero. This output is disabled if value is 0. The diagnostic information includes every character received, and every attempt made to match the current output against the patterns. If the optional file is supplied, all normal and debugging output is written to that file (regardless of the value of value). Any previous diagnostic output file is closed. The -info flag causes exp_internal to return a description of the most recent non-info arguments given. exp_open [args] [-i spawn_id] returns a Tcl file identifier that corresponds to the original spawn id. The file identifier can then be used as if it were opened by Tcl's open command. (The spawn id should no longer be used. A wait should not be executed. The -leaveopen flag leaves the spawn id open for access through Expect commands. A wait must be executed on the spawn id. exp_pid [-i spawn_id] returns the process id corresponding to the currently spawned process. If the -i flag is used, the pid returned corresponds to that of the given spawn id. exp_send is an alias for send. exp_send_error is an alias for send_error. exp_send_log is an alias for send_log. exp_send_tty is an alias for send_tty. exp_send_user is an alias for send_user. exp_version [[-exit] version] is useful for assuring that the script is compatible with the current version of Expect. With no arguments, the current version of Expect is returned. This version may then be encoded in your script. If you actually know that you are not using features of recent versions, you can specify an earlier version. Versions consist of three numbers separated by dots. First is the major number. Scripts written for versions of Expect with a different major number will almost certainly not work. exp_version returns an error if the major numbers do not match. Second is the minor number. Scripts written for a version with a greater minor number than the current version may depend upon some new feature and might not run. exp_version returns an error if the major numbers match, but the script minor number is greater than that of the running Expect. Third is a number that plays no part in the version comparison. However, it is incremented when the Expect software distribution is changed in any way, such as by additional documentation or optimization. It is reset to 0 upon each new minor version. With the -exit flag, Expect prints an error and exits if the version is out of date. expect [[-opts] pat1 body1] ... [-opts] patn [bodyn] waits until one of the patterns matches the output of a spawned process, a specified time period has passed, or an end-of-file is seen. If the final body is empty, it may be omitted. Patterns from the most recent expect_before command are implicitly used before any other patterns. Patterns from the most recent expect_after command are implicitly used after any other patterns. If the arguments to the entire expect statement require more than one line, all the arguments may be "braced" into one so as to avoid terminating each line with a backslash. In this one case, the usual Tcl substitutions will occur despite the braces. If a pattern is the keyword eof, the corresponding body is executed upon end-of-file. If a pattern is the keyword timeout, the corresponding body is executed upon timeout. If no timeout keyword is used, an implicit null action is executed upon timeout. The default timeout period is 10 seconds but may be set, for example to 30, by the command "set timeout 30". An infinite timeout may be designated by the value -1. If a pattern is the keyword default, the corresponding body is executed upon either timeout or end-of-file. If a pattern matches, then the corresponding body is executed. expect returns the result of the body (or the empty string if no pattern matched). In the event that multiple patterns match, the one appearing first is used to select a body. Each time new output arrives, it is compared to each pattern in the order they are listed. Thus, you may test for absence of a match by making the last pattern something guaranteed to appear, such as a prompt. In situations where there is no prompt, you must use timeout (just like you would if you were interacting manually). Patterns are specified in three ways. By default, patterns are specified as with Tcl's string match command. (Such patterns are also similar to C-shell regular expressions usually referred to as "glob" patterns). The -gl flag may may be used to protect patterns that might otherwise match expect flags from doing so. Any pattern beginning with a "-" should be protected this way. (All strings starting with "-" are reserved for future options.) For example, the following fragment looks for a successful login. (Note that abort is presumed to be a procedure defined elsewhere in the script.) expect { busy {puts busy\n ; exp_continue} failed abort "invalid password" abort timeout abort connected } Quotes are necessary on the fourth pattern since it contains a space, which would otherwise separate the pattern from the action. Patterns with the same action (such as the 3rd and 4th) require listing the actions again. This can be avoid by using regexp-style patterns (see below). More information on forming glob-style patterns can be found in the Tcl manual. Regexp-style patterns follow the syntax defined by Tcl's regexp (short for "regular expression") command. regexp patterns are introduced with the flag -re. The previous example can be rewritten using a regexp as: expect { busy {puts busy\n ; exp_continue} -re "failed|invalid password" abort timeout abort connected } Both types of patterns are "unanchored". This means that patterns do not have to match the entire string, but can begin and end the match anywhere in the string (as long as everything else matches). Use ^ to match the beginning of a string, and $ to match the end. Note that if you do not wait for the end of a string, your responses can easily end up in the middle of the string as they are echoed from the spawned process. While still producing correct results, the output can look unnatural. Thus, use of $ is encouraged if you can exactly describe the characters at the end of a string. Note that in many editors, the ^ and $ match the beginning and end of lines respectively. However, because expect is not line oriented, these characters match the beginning and end of the data (as opposed to lines) currently in the expect matching buffer. (Also, see the note below on "system indigestion.") The -ex flag causes the pattern to be matched as an "exact" string. No interpretation of *, ^, etc is made (although the usual Tcl conventions must still be observed). Exact patterns are always unanchored. The -nocase flag causes uppercase characters of the output to compare as if they were lowercase characters. The pattern is not affected. While reading output, more than 2000 bytes can force earlier bytes to be "forgotten". This may be changed with the function match_max. (Note that excessively large values can slow down the pattern matcher.) If patlist is full_buffer, the corresponding body is executed if match_max bytes have been received and no other patterns have matched. Whether or not the full_buffer keyword is used, the forgotten characters are written to expect_out(buffer). If patlist is the keyword null, and nulls are allowed (via the remove_nulls command), the corresponding body is executed if a single ASCII 0 is matched. It is not possible to match 0 bytes via glob or regexp patterns. Upon matching a pattern (or eof or full_buffer), any matching and previously unmatched output is saved in the variable expect_out(buffer). Up to 9 regexp substring matches are saved in the variables expect_out(1,string) through expect_out(9,string). If the -indices flag is used before a pattern, the starting and ending indices (in a form suitable for lrange) of the 10 strings are stored in the variables expect_out(X,start) and expect_out(X,end) where X is a digit, corresponds to the substring position in the buffer. 0 refers to strings which matched the entire pattern and is generated for glob patterns as well as regexp patterns. For example, if a process has produced output of "abcdefgh\n", the result of: expect "cd" is as if the following statements had executed: set expect_out(0,string) cd set expect_out(buffer) abcd and "efgh\n" is left in the output buffer. If a process produced the output "abbbcabkkkka\n", the result of: expect -indices -re "b(b*).*(k+)" is as if the following statements had executed: set expect_out(0,start) 1 set expect_out(0,end) 10 set expect_out(0,string) bbbcabkkkk set expect_out(1,start) 2 set expect_out(1,end) 3 set expect_out(1,string) bb set expect_out(2,start) 10 set expect_out(2,end) 10 set expect_out(2,string) k set expect_out(buffer) abbbcabkkkk and "a\n" is left in the output buffer. The pattern "*" (and -re ".*") will flush the output buffer without reading any more output from the process. Normally, the matched output is discarded from Expect's internal buffers. This may be prevented by prefixing a pattern with the -notransfer flag. This flag is especially useful in experimenting (and can be abbreviated to "-not" for convenience while experimenting). The spawn id associated with the matching output (or eof or full_buffer) is stored in expect_out(spawn_id). The -timeout flag causes the current expect command to use the following value as a timeout instead of using the value of the timeout variable. By default, patterns are matched against output from the current process, however the -i flag declares the output from the named spawn_id list be matched against any following patterns (up to the next -i). The spawn_id list should either be a whitespace separated list of spawn_ids or a variable referring to such a list of spawn_ids. For example, the following example waits for "connected" from the current process, or "busy", "failed" or "invalid password" from the spawn_id named by $proc2. expect { -i $proc2 busy {puts busy\n ; exp_continue} -re "failed|invalid password" abort timeout abort connected } The value of the global variable any_spawn_id may be used to match patterns to any spawn_ids that are named with all other -i flags in the current expect command. The spawn_id from a -i flag with no associated pattern (i.e., followed immediately by another -i) is made available to any other patterns in the same expect command associated with any_spawn_id. The -i flag may also name a global variable in which case the variable is read for a list of spawn ids. The variable is reread whenever it changes. This provides a way of changing the I/O source while the command is in execution. Spawn ids provided this way are called "indirect" spawn ids. Actions such as break and continue cause control structures (i.e., for, proc) to behave in the usual way. The command exp_continue allows expect itself to continue executing rather than returning as it normally would. This is useful for avoiding explicit loops or repeated expect statements. The following example is part of a fragment to automate rlogin. The exp_continue avoids having to write a second expect statement (to look for the prompt again) if the rlogin prompts for a password. expect { Password: { stty -echo send_user "password (for $user) on $host: " expect_user -re "(.*)\n" send_user "\n" send "$expect_out(1,string)\r" stty echo exp_continue } incorrect { send_user "invalid password or account\n" exit } timeout { send_user "connection to $host timed out\n" exit } eof { send_user \ "connection to host failed: $expect_out(buffer)" exit } -re $prompt } For example, the following fragment might help a user guide an interaction that is already totally automated. In this case, the terminal is put into raw mode. If the user presses "+", a variable is incremented. If "p" is pressed, several returns are sent to the process, perhaps to poke it in some way, and "i" lets the user interact with the process, effectively stealing away control from the script. In each case, the exp_continue allows the current expect to continue pattern matching after executing the current action. stty raw -echo expect_after { -i $user_spawn_id "p" {send "\r\r\r"; exp_continue} "+" {incr foo; exp_continue} "i" {interact; exp_continue} "quit" exit } By default, exp_continue resets the timeout timer. The timer is not restarted, if exp_continue is called with the -continue_timer flag. expect_after [expect_args] works identically to the expect_before except that if patterns from both expect and expect_after can match, the expect pattern is used. See the expect_before command for more information. expect_background [expect_args] takes the same arguments as expect, however it returns immediately. Patterns are tested whenever new input arrives. The pattern timeout and default are meaningless to expect_background and are silently discarded. Otherwise, the expect_background command uses expect_before and expect_after patterns just like expect does. When expect_background actions are being evaluated, background processing for the same spawn id is blocked. Background processing is unblocked when the action completes. While background processing is blocked, it is possible to do a (foreground) expect on the same spawn id. It is not possible to execute an expect while an expect_background is unblocked. expect_background for a particular spawn id is deleted by declaring a new expect_background with the same spawn id. Declaring expect_background with no pattern removes the given spawn id from the ability to match patterns in the background. expect_before [expect_args] takes the same arguments as expect, however it returns immediately. Pattern-action pairs from the most recent expect_before with the same spawn id are implicitly added to any following expect commands. If a pattern matches, it is treated as if it had been specified in the expect command itself, and the associated body is executed in the context of the expect command. If patterns from both expect_before and expect can match, the expect_before pattern is used. If no pattern is specified, the spawn id is not checked for any patterns. Unless overridden by a -i flag, expect_before patterns match against the spawn id defined at the time that the expect_before command was executed (not when its pattern is matched). The -info flag causes expect_before to return the current specifications of what patterns it will match. By default, it reports on the current spawn id. An optional spawn id specification may be given for information on that spawn id. For example expect_before -info -i $proc At most one spawn id specification may be given. The flag -indirect suppresses direct spawn ids that come only from indirect specifications. Instead of a spawn id specification, the flag "-all" will cause "-info" to report on all spawn ids. The output of the -info flag can be reused as the argument to expect_before. expect_tty [expect_args] is like expect but it reads characters from /dev/tty (i.e. keystrokes from the user). By default, reading is performed in cooked mode. Thus, lines must end with a return in order for expect to see them. This may be changed via stty (see the stty command below). expect_user [expect_args] is like expect but it reads characters from stdin (i.e. keystrokes from the user). By default, reading is performed in cooked mode. Thus, lines must end with a return in order for expect to see them. This may be changed via stty (see the stty command below). fork creates a new process. The new process is an exact copy of the current Expect process. On success, fork returns 0 to the new (child) process and returns the process ID of the child process to the parent process. On failure (invariably due to lack of resources, e.g., swap space, memory), fork returns -1 to the parent process, and no child process is created. Forked processes exit via the exit command, just like the original process. Forked processes are allowed to write to the log files. If you do not disable debugging or logging in most of the processes, the result can be confusing. Some pty implementations may be confused by multiple readers and writers, even momentarily. Thus, it is safest to fork before spawning processes. interact [string1 body1] ... [stringn [bodyn]] gives control of the current process to the user, so that keystrokes are sent to the current process, and the stdout and stderr of the current process are returned. String-body pairs may be specified as arguments, in which case the body is executed when the corresponding string is entered. (By default, the string is not sent to the current process.) The interpreter command is assumed, if the final body is missing. If the arguments to the entire interact statement require more than one line, all the arguments may be "braced" into one so as to avoid terminating each line with a backslash. In this one case, the usual Tcl substitutions will occur despite the braces. For example, the following command runs interact with the following string-body pairs defined: When ^Z is pressed, Expect is suspended. (The -reset flag restores the terminal modes.) When ^A is pressed, the user sees "you typed a control-A" and the process is sent a ^A. When $ is pressed, the user sees the date. When ^C is pressed, Expect exits. If "foo" is entered, the user sees "bar". When ~~ is pressed, the Expect interpreter runs interactively. set CTRLZ \032 interact { -reset $CTRLZ {exec kill -STOP [pid]} \001 {send_user "you typed a control-A\n"; send "\001" } $ {send_user "The date is [clock format [clock seconds]]."} \003 exit foo {send_user "bar"} ~~ } In string-body pairs, strings are matched in the order they are listed as arguments. Strings that partially match are not sent to the current process in anticipation of the remainder coming. If characters are then entered such that there can no longer possibly be a match, only the part of the string will be sent to the process that cannot possibly begin another match. Thus, strings that are substrings of partial matches can match later, if the original strings that was attempting to be match ultimately fails. By default, string matching is exact with no wild cards. (In contrast, the expect command uses glob-style patterns by default.) The -ex flag may be used to protect patterns that might otherwise match interact flags from doing so. Any pattern beginning with a "-" should be protected this way. (All strings starting with "-" are reserved for future options.) The -re flag forces the string to be interpreted as a regexp- style pattern. In this case, matching substrings are stored in the variable interact_out similarly to the way expect stores its output in the variable expect_out. The -indices flag is similarly supported. The pattern eof introduces an action that is executed upon end- of-file. A separate eof pattern may also follow the -output flag in which case it is matched if an eof is detected while writing output. The default eof action is "return", so that interact simply returns upon any EOF. The pattern timeout introduces a timeout (in seconds) and action that is executed after no characters have been read for a given time. The timeout pattern applies to the most recently specified process. There is no default timeout. The special variable "timeout" (used by the expect command) has no affect on this timeout. For example, the following statement could be used to autologout users who have not typed anything for an hour but who still get frequent system messages: interact -input $user_spawn_id timeout 3600 return -output \ $spawn_id If the pattern is the keyword null, and nulls are allowed (via the remove_nulls command), the corresponding body is executed if a single ASCII 0 is matched. It is not possible to match 0 bytes via glob or regexp patterns. Prefacing a pattern with the flag -iwrite causes the variable interact_out(spawn_id) to be set to the spawn_id which matched the pattern (or eof). Actions such as break and continue cause control structures (i.e., for, proc) to behave in the usual way. However return causes interact to return to its caller, while inter_return causes interact to cause a return in its caller. For example, if "proc foo" called interact which then executed the action inter_return, proc foo would return. (This means that if interact calls interpreter interactively typing return will cause the interact to continue, while inter_return will cause the interact to return to its caller.) During interact, raw mode is used so that all characters may be passed to the current process. If the current process does not catch job control signals, it will stop if sent a stop signal (by default ^Z). To restart it, send a continue signal (such as by "kill -CONT <pid>"). If you really want to send a SIGSTOP to such a process (by ^Z), consider spawning csh first and then running your program. On the other hand, if you want to send a SIGSTOP to Expect itself, first call interpreter (perhaps by using an escape character), and then press ^Z. String-body pairs can be used as a shorthand for avoiding having to enter the interpreter and execute commands interactively. The previous terminal mode is used while the body of a string-body pair is being executed. For speed, actions execute in raw mode by default. The -reset flag resets the terminal to the mode it had before interact was executed (invariably, cooked mode). Note that characters entered when the mode is being switched may be lost (an unfortunate feature of the terminal driver on some systems). The only reason to use -reset is if your action depends on running in cooked mode. The -echo flag sends characters that match the following pattern back to the process that generated them as each character is read. This may be useful when the user needs to see feedback from partially typed patterns. If a pattern is being echoed but eventually fails to match, the characters are sent to the spawned process. If the spawned process then echoes them, the user will see the characters twice. -echo is probably only appropriate in situations where the user is unlikely to not complete the pattern. For example, the following excerpt is from rftp, the recursive-ftp script, where the user is prompted to enter ~g, ~p, or ~l, to get, put, or list the current directory recursively. These are so far away from the normal ftp commands, that the user is unlikely to type ~ followed by anything else, except mistakenly, in which case, they'll probably just ignore the result anyway. interact { -echo ~g {getcurdirectory 1} -echo ~l {getcurdirectory 0} -echo ~p {putcurdirectory} } The -nobuffer flag sends characters that match the following pattern on to the output process as characters are read. This is useful when you wish to let a program echo back the pattern. For example, the following might be used to monitor where a person is dialing (a Hayes-style modem). Each time "atd" is seen the script logs the rest of the line. proc lognumber {} { interact -nobuffer -re "(.*)\r" return puts $log "[clock format [clock seconds]]: dialed $interact_out(1,string)" } interact -nobuffer "atd" lognumber During interact, previous use of log_user is ignored. In particular, interact will force its output to be logged (sent to the standard output) since it is presumed the user doesn't wish to interact blindly. The -o flag causes any following key-body pairs to be applied to the output of the current process. This can be useful, for example, when dealing with hosts that send unwanted characters during a telnet session. By default, interact expects the user to be writing stdin and reading stdout of the Expect process itself. The -u flag (for "user") makes interact look for the user as the process named by its argument (which must be a spawned id). This allows two unrelated processes to be joined together without using an explicit loop. To aid in debugging, Expect diagnostics always go to stderr (or stdout for certain logging and debugging information). For the same reason, the interpreter command will read interactively from stdin. For example, the following fragment creates a login process. Then it dials the user (not shown), and finally connects the two together. Of course, any process may be substituted for login. A shell, for example, would allow the user to work without supplying an account and password. spawn login set login $spawn_id spawn tip modem # dial back out to user # connect user to login interact -u $login To send output to multiple processes, list each spawn id list prefaced by a -output flag. Input for a group of output spawn ids may be determined by a spawn id list prefaced by a -input flag. (Both -input and -output may take lists in the same form as the -i flag in the expect command, except that any_spawn_id is not meaningful in interact.) All following flags and strings (or patterns) apply to this input until another -input flag appears. If no -input appears, -output implies "-input $user_spawn_id -output". (Similarly, with patterns that do not have -input.) If one -input is specified, it overrides $user_spawn_id. If a second -input is specified, it overrides $spawn_id. Additional -input flags may be specified. The two implied input processes default to having their outputs specified as $spawn_id and $user_spawn_id (in reverse). If a -input flag appears with no -output flag, characters from that process are discarded. The -i flag introduces a replacement for the current spawn_id when no other -input or -output flags are used. A -i flag implies a -o flag. It is possible to change the processes that are being interacted with by using indirect spawn ids. (Indirect spawn ids are described in the section on the expect command.) Indirect spawn ids may be specified with the -i, -u, -input, or -output flags. interpreter [args] causes the user to be interactively prompted for Expect and Tcl commands. The result of each command is printed. Actions such as break and continue cause control structures (i.e., for, proc) to behave in the usual way. However return causes interpreter to return to its caller, while inter_return causes interpreter to cause a return in its caller. For example, if "proc foo" called interpreter which then executed the action inter_return, proc foo would return. Any other command causes interpreter to continue prompting for new commands. By default, the prompt contains two integers. The first integer describes the depth of the evaluation stack (i.e., how many times Tcl_Eval has been called). The second integer is the Tcl history identifier. The prompt can be set by defining a procedure called "prompt1" whose return value becomes the next prompt. If a statement has open quotes, parens, braces, or brackets, a secondary prompt (by default "+> ") is issued upon newline. The secondary prompt may be set by defining a procedure called "prompt2". During interpreter, cooked mode is used, even if the its caller was using raw mode. If stdin is closed, interpreter will return unless the -eof flag is used, in which case the subsequent argument is invoked. log_file [args] [[-a] file] If a filename is provided, log_file will record a transcript of the session (beginning at that point) in the file. log_file will stop recording if no argument is given. Any previous log file is closed. Instead of a filename, a Tcl file identifier may be provided by using the -open or -leaveopen flags. This is similar to the spawn command. (See spawn for more info.) The -a flag forces output to be logged that was suppressed by the log_user command. By default, the log_file command appends to old files rather than truncating them, for the convenience of being able to turn logging off and on multiple times in one session. To truncate files, use the -noappend flag. The -info flag causes log_file to return a description of the most recent non-info arguments given. log_user -info|0|1 By default, the send/expect dialogue is logged to stdout (and a logfile if open). The logging to stdout is disabled by the command "log_user 0" and reenabled by "log_user 1". Logging to the logfile is unchanged. The -info flag causes log_user to return a description of the most recent non-info arguments given. match_max [-d] [-i spawn_id] [size] defines the size of the buffer (in bytes) used internally by expect. With no size argument, the current size is returned. With the -d flag, the default size is set. (The initial default is 2000.) With the -i flag, the size is set for the named spawn id, otherwise it is set for the current process. overlay [-# spawn_id] [-# spawn_id] [...] program [args] executes program args in place of the current Expect program, which terminates. A bare hyphen argument forces a hyphen in front of the command name as if it was a login shell. All spawn_ids are closed except for those named as arguments. These are mapped onto the named file identifiers. Spawn_ids are mapped to file identifiers for the new program to inherit. For example, the following line runs chess and allows it to be controlled by the current process - say, a chess master. overlay -0 $spawn_id -1 $spawn_id -2 $spawn_id chess This is more efficient than "interact -u", however, it sacrifices the ability to do programmed interaction since the Expect process is no longer in control. Note that no controlling terminal is provided. Thus, if you disconnect or remap standard input, programs that do job control (shells, login, etc) will not function properly. parity [-d] [-i spawn_id] [value] defines whether parity should be retained or stripped from the output of spawned processes. If value is zero, parity is stripped, otherwise it is not stripped. With no value argument, the current value is returned. With the -d flag, the default parity value is set. (The initial default is 1, i.e., parity is not stripped.) With the -i flag, the parity value is set for the named spawn id, otherwise it is set for the current process. remove_nulls [-d] [-i spawn_id] [value] defines whether nulls are retained or removed from the output of spawned processes before pattern matching or storing in the variable expect_out or interact_out. If value is 1, nulls are removed. If value is 0, nulls are not removed. With no value argument, the current value is returned. With the -d flag, the default value is set. (The initial default is 1, i.e., nulls are removed.) With the -i flag, the value is set for the named spawn id, otherwise it is set for the current process. Whether or not nulls are removed, Expect will record null bytes to the log and stdout. send [-flags] string Sends string to the current process. For example, the command send "hello world\r" sends the characters, h e l l o <blank> w o r l d <return> to the current process. (Tcl includes a printf-like command (called format) which can build arbitrarily complex strings.) Characters are sent immediately although programs with line- buffered input will not read the characters until a return character is sent. A return character is denoted "\r". The -- flag forces the next argument to be interpreted as a string rather than a flag. Any string can be preceded by "--" whether or not it actually looks like a flag. This provides a reliable mechanism to specify variable strings without being tripped up by those that accidentally look like flags. (All strings starting with "-" are reserved for future options.) The -i flag declares that the string be sent to the named spawn_id. If the spawn_id is user_spawn_id, and the terminal is in raw mode, newlines in the string are translated to return- newline sequences so that they appear as if the terminal was in cooked mode. The -raw flag disables this translation. The -null flag sends null characters (0 bytes). By default, one null is sent. An integer may follow the -null to indicate how many nulls to send. The -break flag generates a break condition. This only makes sense if the spawn id refers to a tty device opened via "spawn -open". If you have spawned a process such as tip, you should use tip's convention for generating a break. The -s flag forces output to be sent "slowly", thus avoid the common situation where a computer outtypes an input buffer that was designed for a human who would never outtype the same buffer. This output is controlled by the value of the variable "send_slow" which takes a two element list. The first element is an integer that describes the number of bytes to send atomically. The second element is a real number that describes the number of seconds by which the atomic sends must be separated. For example, "set send_slow {10 .001}" would force "send -s" to send strings with 1 millisecond in between each 10 characters sent. The -h flag forces output to be sent (somewhat) like a human actually typing. Human-like delays appear between the characters. (The algorithm is based upon a Weibull distribution, with modifications to suit this particular application.) This output is controlled by the value of the variable "send_human" which takes a five element list. The first two elements are average interarrival time of characters in seconds. The first is used by default. The second is used at word endings, to simulate the subtle pauses that occasionally occur at such transitions. The third parameter is a measure of variability where .1 is quite variable, 1 is reasonably variable, and 10 is quite invariable. The extremes are 0 to infinity. The last two parameters are, respectively, a minimum and maximum interarrival time. The minimum and maximum are used last and "clip" the final time. The ultimate average can be quite different from the given average if the minimum and maximum clip enough values. As an example, the following command emulates a fast and consistent typist: set send_human {.1 .3 1 .05 2} send -h "I'm hungry. Let's do lunch." while the following might be more suitable after a hangover: set send_human {.4 .4 .2 .5 100} send -h "Goodd party lash night!" Note that errors are not simulated, although you can set up error correction situations yourself by embedding mistakes and corrections in a send argument. The flags for sending null characters, for sending breaks, for forcing slow output and for human-style output are mutually exclusive. Only the one specified last will be used. Furthermore, no string argument can be specified with the flags for sending null characters or breaks. It is a good idea to precede the first send to a process by an expect. expect will wait for the process to start, while send cannot. In particular, if the first send completes before the process starts running, you run the risk of having your data ignored. In situations where interactive programs offer no initial prompt, you can precede send by a delay as in: # To avoid giving hackers hints on how to break in, # this system does not prompt for an external password. # Wait for 5 seconds for exec to complete spawn telnet very.secure.gov sleep 5 send password\r exp_send is an alias for send. If you are using Expectk or some other variant of Expect in the Tk environment, send is defined by Tk for an entirely different purpose. exp_send is provided for compatibility between environments. Similar aliases are provided for other Expect's other send commands. send_error [-flags] string is like send, except that the output is sent to stderr rather than the current process. send_log [--] string is like send, except that the string is only sent to the log file (see log_file.) The arguments are ignored if no log file is open. send_tty [-flags] string is like send, except that the output is sent to /dev/tty rather than the current process. send_user [-flags] string is like send, except that the output is sent to stdout rather than the current process. sleep seconds causes the script to sleep for the given number of seconds. Seconds may be a decimal number. Interrupts (and Tk events if you are using Expectk) are processed while Expect sleeps. spawn [args] program [args] creates a new process running program args. Its stdin, stdout and stderr are connected to Expect, so that they may be read and written by other Expect commands. The connection is broken by close or if the process itself closes any of the file identifiers. When a process is started by spawn, the variable spawn_id is set to a descriptor referring to that process. The process described by spawn_id is considered the current process. spawn_id may be read or written, in effect providing job control. user_spawn_id is a global variable containing a descriptor which refers to the user. For example, when spawn_id is set to this value, expect behaves like expect_user. error_spawn_id is a global variable containing a descriptor which refers to the standard error. For example, when spawn_id is set to this value, send behaves like send_error. tty_spawn_id is a global variable containing a descriptor which refers to /dev/tty. If /dev/tty does not exist (such as in a cron, at, or batch script), then tty_spawn_id is not defined. This may be tested as: if {[info vars tty_spawn_id]} { # /dev/tty exists } else { # /dev/tty doesn't exist # probably in cron, batch, or at script } spawn returns the UNIX process id. If no process is spawned, 0 is returned. The variable spawn_out(replica,name) is set to the name of the pty replica device. By default, spawn echoes the command name and arguments. The -noecho flag stops spawn from doing this. The -console flag causes console output to be redirected to the spawned process. This is not supported on all systems. Internally, spawn uses a pty, initialized the same way as the user's tty. This is further initialized so that all settings are "sane" (according to stty(1)). If the variable stty_init is defined, it is interpreted in the style of stty arguments as further configuration. For example, "set stty_init raw" will cause further spawned processes's terminals to start in raw mode. -nottycopy skips the initialization based on the user's tty. -nottyinit skips the "sane" initialization. Normally, spawn takes little time to execute. If you notice spawn taking a significant amount of time, it is probably encountering ptys that are wedged. A number of tests are run on ptys to avoid entanglements with errant processes. (These take 10 seconds per wedged pty.) Running Expect with the -d option will show if Expect is encountering many ptys in odd states. If you cannot kill the processes to which these ptys are attached, your only recourse may be to reboot. If program cannot be spawned successfully because exec(2) fails (e.g. when program doesn't exist), an error message will be returned by the next interact or expect command as if program had run and produced the error message as output. This behavior is a natural consequence of the implementation of spawn. Internally, spawn forks, after which the spawned process has no way to communicate with the original Expect process except by communication via the spawn_id. The -open flag causes the next argument to be interpreted as a Tcl file identifier (i.e., returned by open.) The spawn id can then be used as if it were a spawned process. (The file identifier should no longer be used.) This lets you treat raw devices, files, and pipelines as spawned processes without using a pty. 0 is returned to indicate there is no associated process. When the connection to the spawned process is closed, so is the Tcl file identifier. The -leaveopen flag is similar to -open except that -leaveopen causes the file identifier to be left open even after the spawn id is closed. The -pty flag causes a pty to be opened but no process spawned. 0 is returned to indicate there is no associated process. Spawn_id is set as usual. The variable spawn_out(replica,fd) is set to a file identifier corresponding to the pty replica. It can be closed using "close -replica". The -ignore flag names a signal to be ignored in the spawned process. Otherwise, signals get the default behavior. Signals are named as in the trap command, except that each signal requires a separate flag. strace level causes following statements to be printed before being executed. (Tcl's trace command traces variables.) level indicates how far down in the call stack to trace. For example, the following command runs Expect while tracing the first 4 levels of calls, but none below that. expect -c "strace 4" script.exp The -info flag causes strace to return a description of the most recent non-info arguments given. stty args changes terminal modes similarly to the external stty command. By default, the controlling terminal is accessed. Other terminals can be accessed by appending "< /dev/tty..." to the command. (Note that the arguments should not be grouped into a single argument.) Requests for status return it as the result of the command. If no status is requested and the controlling terminal is accessed, the previous status of the raw and echo attributes are returned in a form which can later be used by the command. For example, the arguments raw or -cooked put the terminal into raw mode. The arguments -raw or cooked put the terminal into cooked mode. The arguments echo and -echo put the terminal into echo and noecho mode respectively. The following example illustrates how to temporarily disable echoing. This could be used in otherwise-automatic scripts to avoid embedding passwords in them. (See more discussion on this under EXPECT HINTS below.) stty -echo send_user "Password: " expect_user -re "(.*)\n" set password $expect_out(1,string) stty echo system args gives args to sh(1) as input, just as if it had been typed as a command from a terminal. Expect waits until the shell terminates. The return status from sh is handled the same way that exec handles its return status. In contrast to exec which redirects stdin and stdout to the script, system performs no redirection (other than that indicated by the string itself). Thus, it is possible to use programs which must talk directly to /dev/tty. For the same reason, the results of system are not recorded in the log. timestamp [args] returns a timestamp. With no arguments, the number of seconds since the epoch is returned. The -format flag introduces a string which is returned but with substitutions made according to the POSIX rules for strftime. For example %a is replaced by an abbreviated weekday name (i.e., Sat). Others are: %a abbreviated weekday name %A full weekday name %b abbreviated month name %B full month name %c date-time as in: Wed Oct 6 11:45:56 1993 %d day of the month (01-31) %H hour (00-23) %I hour (01-12) %j day (001-366) %m month (01-12) %M minute (00-59) %p am or pm %S second (00-61) %u day (1-7, Monday is first day of week) %U week (00-53, first Sunday is first day of week one) %V week (01-53, ISO 8601 style) %w day (0-6) %W week (00-53, first Monday is first day of week one) %x date-time as in: Wed Oct 6 1993 %X time as in: 23:59:59 %y year (00-99) %Y year as in: 1993 %Z timezone (or nothing if not determinable) %% a bare percent sign Other % specifications are undefined. Other characters will be passed through untouched. Only the C locale is supported. The -seconds flag introduces a number of seconds since the epoch to be used as a source from which to format. Otherwise, the current time is used. The -gmt flag forces timestamp output to use the GMT timezone. With no flag, the local timezone is used. trap [[command] signals] causes the given command to be executed upon future receipt of any of the given signals. The command is executed in the global scope. If command is absent, the signal action is returned. If command is the string SIG_IGN, the signals are ignored. If command is the string SIG_DFL, the signals are result to the system default. signals is either a single signal or a list of signals. Signals may be specified numerically or symbolically as per signal(3). The "SIG" prefix may be omitted. With no arguments (or the argument -number), trap returns the signal number of the trap command currently being executed. The -code flag uses the return code of the command in place of whatever code Tcl was about to return when the command originally started running. The -interp flag causes the command to be evaluated using the interpreter active at the time the command started running rather than when the trap was declared. The -name flag causes the trap command to return the signal name of the trap command currently being executed. The -max flag causes the trap command to return the largest signal number that can be set. For example, the command "trap {send_user "Ouch!"} SIGINT" will print "Ouch!" each time the user presses ^C. By default, SIGINT (which can usually be generated by pressing ^C) and SIGTERM cause Expect to exit. This is due to the following trap, created by default when Expect starts. trap exit {SIGINT SIGTERM} If you use the -D flag to start the debugger, SIGINT is redefined to start the interactive debugger. This is due to the following trap: trap {exp_debug 1} SIGINT The debugger trap can be changed by setting the environment variable EXPECT_DEBUG_INIT to a new trap command. You can, of course, override both of these just by adding trap commands to your script. In particular, if you have your own "trap exit SIGINT", this will override the debugger trap. This is useful if you want to prevent users from getting to the debugger at all. If you want to define your own trap on SIGINT but still trap to the debugger when it is running, use: if {![exp_debug]} {trap mystuff SIGINT} Alternatively, you can trap to the debugger using some other signal. trap will not let you override the action for SIGALRM as this is used internally to Expect. The disconnect command sets SIGALRM to SIG_IGN (ignore). You can reenable this as long as you disable it during subsequent spawn commands. See signal(3) for more info. wait [args] delays until a spawned process (or the current process if none is named) terminates. wait normally returns a list of four integers. The first integer is the pid of the process that was waited upon. The second integer is the corresponding spawn id. The third integer is -1 if an operating system error occurred, or 0 otherwise. If the third integer was 0, the fourth integer is the status returned by the spawned process. If the third integer was -1, the fourth integer is the value of errno set by the operating system. The global variable errorCode is also set. Additional elements may appear at the end of the return value from wait. An optional fifth element identifies a class of information. Currently, the only possible value for this element is CHILDKILLED in which case the next two values are the C-style signal name and a short textual description. The -i flag declares the process to wait corresponding to the named spawn_id (NOT the process id). Inside a SIGCHLD handler, it is possible to wait for any spawned process by using the spawn id -1. The -nowait flag causes the wait to return immediately with the indication of a successful wait. When the process exits (later), it will automatically disappear without the need for an explicit wait. The wait command may also be used wait for a forked process using the arguments "-i -1". Unlike its use with spawned processes, this command can be executed at any time. There is no control over which process is reaped. However, the return value can be checked for the process id. LIBRARIES Expect automatically knows about two built-in libraries for Expect scripts. These are defined by the directories named in the variables exp_library and exp_exec_library. Both are meant to contain utility files that can be used by other scripts. exp_library contains architecture-independent files. exp_exec_library contains architecture-dependent files. Depending on your system, both directories may be totally empty. The existence of the file $exp_exec_library/cat-buffers describes whether your /bin/cat buffers by default. PRETTY-PRINTING A vgrind definition is available for pretty-printing Expect scripts. Assuming the vgrind definition supplied with the Expect distribution is correctly installed, you can use it as: vgrind -lexpect file
null
It many not be apparent how to put everything together that the man page describes. I encourage you to read and try out the examples in the example directory of the Expect distribution. Some of them are real programs. Others are simply illustrative of certain techniques, and of course, a couple are just quick hacks. The INSTALL file has a quick overview of these programs. The Expect papers (see SEE ALSO) are also useful. While some papers use syntax corresponding to earlier versions of Expect, the accompanying rationales are still valid and go into a lot more detail than this man page. CAVEATS Extensions may collide with Expect's command names. For example, send is defined by Tk for an entirely different purpose. For this reason, most of the Expect commands are also available as "exp_XXXX". Commands and variables beginning with "exp", "inter", "spawn", and "timeout" do not have aliases. Use the extended command names if you need this compatibility between environments. Expect takes a rather liberal view of scoping. In particular, variables read by commands specific to the Expect program will be sought first from the local scope, and if not found, in the global scope. For example, this obviates the need to place "global timeout" in every procedure you write that uses expect. On the other hand, variables written are always in the local scope (unless a "global" command has been issued). The most common problem this causes is when spawn is executed in a procedure. Outside the procedure, spawn_id no longer exists, so the spawned process is no longer accessible simply because of scoping. Add a "global spawn_id" to such a procedure. If you cannot enable the multispawning capability (i.e., your system supports neither select (BSD *.*), poll (SVR>2), nor something equivalent), Expect will only be able to control a single process at a time. In this case, do not attempt to set spawn_id, nor should you execute processes via exec while a spawned process is running. Furthermore, you will not be able to expect from multiple processes (including the user as one) at the same time. Terminal parameters can have a big effect on scripts. For example, if a script is written to look for echoing, it will misbehave if echoing is turned off. For this reason, Expect forces sane terminal parameters by default. Unfortunately, this can make things unpleasant for other programs. As an example, the emacs shell wants to change the "usual" mappings: newlines get mapped to newlines instead of carriage-return newlines, and echoing is disabled. This allows one to use emacs to edit the input line. Unfortunately, Expect cannot possibly guess this. You can request that Expect not override its default setting of terminal parameters, but you must then be very careful when writing scripts for such environments. In the case of emacs, avoid depending upon things like echoing and end-of-line mappings. The commands that accepted arguments braced into a single list (the expect variants and interact) use a heuristic to decide if the list is actually one argument or many. The heuristic can fail only in the case when the list actually does represent a single argument which has multiple embedded \n's with non-whitespace characters between them. This seems sufficiently improbable, however the argument "-nobrace" can be used to force a single argument to be handled as a single argument. This could conceivably be used with machine-generated Expect code. Similarly, -brace forces a single argument to be handle as multiple patterns/actions. BUGS It was really tempting to name the program "sex" (for either "Smart EXec" or "Send-EXpect"), but good sense (or perhaps just Puritanism) prevailed. On some systems, when a shell is spawned, it complains about not being able to access the tty but runs anyway. This means your system has a mechanism for gaining the controlling tty that Expect doesn't know about. Please find out what it is, and send this information back to me. Ultrix 4.1 (at least the latest versions around here) considers timeouts of above 1000000 to be equivalent to 0. Digital UNIX 4.0A (and probably other versions) refuses to allocate ptys if you define a SIGCHLD handler. See grantpt page for more info. IRIX 6.0 does not handle pty permissions correctly so that if Expect attempts to allocate a pty previously used by someone else, it fails. Upgrade to IRIX 6.1. Telnet (verified only under SunOS 4.1.2) hangs if TERM is not set. This is a problem under cron, at and in cgi scripts, which do not define TERM. Thus, you must set it explicitly - to what type is usually irrelevant. It just has to be set to something! The following probably suffices for most cases. set env(TERM) vt100 Tip (verified only under BSDI BSD/OS 3.1 i386) hangs if SHELL and HOME are not set. This is a problem under cron, at and in cgi scripts, which do not define these environment variables. Thus, you must set them explicitly - to what type is usually irrelevant. It just has to be set to something! The following probably suffices for most cases. set env(SHELL) /bin/sh set env(HOME) /usr/local/bin Some implementations of ptys are designed so that the kernel throws away any unread output after 10 to 15 seconds (actual number is implementation-dependent) after the process has closed the file descriptor. Thus Expect programs such as spawn date sleep 20 expect will fail. To avoid this, invoke non-interactive programs with exec rather than spawn. While such situations are conceivable, in practice I have never encountered a situation in which the final output of a truly interactive program would be lost due to this behavior. On the other hand, Cray UNICOS ptys throw away any unread output immediately after the process has closed the file descriptor. I have reported this to Cray and they are working on a fix. Sometimes a delay is required between a prompt and a response, such as when a tty interface is changing UART settings or matching baud rates by looking for start/stop bits. Usually, all this is require is to sleep for a second or two. A more robust technique is to retry until the hardware is ready to receive input. The following example uses both strategies: send "speed 9600\r"; sleep 1 expect { timeout {send "\r"; exp_continue} $prompt } trap -code will not work with any command that sits in Tcl's event loop, such as sleep. The problem is that in the event loop, Tcl discards the return codes from async event handlers. A workaround is to set a flag in the trap code. Then check the flag immediately after the command (i.e., sleep). The expect_background command ignores -timeout arguments and has no concept of timeouts in general. EXPECT HINTS There are a couple of things about Expect that may be non-intuitive. This section attempts to address some of these things with a couple of suggestions. A common expect problem is how to recognize shell prompts. Since these are customized differently by differently people and different shells, portably automating rlogin can be difficult without knowing the prompt. A reasonable convention is to have users store a regular expression describing their prompt (in particular, the end of it) in the environment variable EXPECT_PROMPT. Code like the following can be used. If EXPECT_PROMPT doesn't exist, the code still has a good chance of functioning correctly. set prompt "(%|#|\\$) $" ;# default prompt catch {set prompt $env(EXPECT_PROMPT)} expect -re $prompt I encourage you to write expect patterns that include the end of whatever you expect to see. This avoids the possibility of answering a question before seeing the entire thing. In addition, while you may well be able to answer questions before seeing them entirely, if you answer early, your answer may appear echoed back in the middle of the question. In other words, the resulting dialogue will be correct but look scrambled. Most prompts include a space character at the end. For example, the prompt from ftp is 'f', 't', 'p', '>' and <blank>. To match this prompt, you must account for each of these characters. It is a common mistake not to include the blank. Put the blank in explicitly. If you use a pattern of the form X*, the * will match all the output received from the end of X to the last thing received. This sounds intuitive but can be somewhat confusing because the phrase "last thing received" can vary depending upon the speed of the computer and the processing of I/O both by the kernel and the device driver. In particular, humans tend to see program output arriving in huge chunks (atomically) when in reality most programs produce output one line at a time. Assuming this is the case, the * in the pattern of the previous paragraph may only match the end of the current line even though there seems to be more, because at the time of the match that was all the output that had been received. expect has no way of knowing that further output is coming unless your pattern specifically accounts for it. Even depending on line-oriented buffering is unwise. Not only do programs rarely make promises about the type of buffering they do, but system indigestion can break output lines up so that lines break at seemingly random places. Thus, if you can express the last few characters of a prompt when writing patterns, it is wise to do so. If you are waiting for a pattern in the last output of a program and the program emits something else instead, you will not be able to detect that with the timeout keyword. The reason is that expect will not timeout - instead it will get an eof indication. Use that instead. Even better, use both. That way if that line is ever moved around, you won't have to edit the line itself. Newlines are usually converted to carriage return, linefeed sequences when output by the terminal driver. Thus, if you want a pattern that explicitly matches the two lines, from, say, printf("foo\nbar"), you should use the pattern "foo\r\nbar". A similar translation occurs when reading from the user, via expect_user. In this case, when you press return, it will be translated to a newline. If Expect then passes that to a program which sets its terminal to raw mode (like telnet), there is going to be a problem, as the program expects a true return. (Some programs are actually forgiving in that they will automatically translate newlines to returns, but most don't.) Unfortunately, there is no way to find out that a program put its terminal into raw mode. Rather than manually replacing newlines with returns, the solution is to use the command "stty raw", which will stop the translation. Note, however, that this means that you will no longer get the cooked line- editing features. interact implicitly sets your terminal to raw mode so this problem will not arise then. It is often useful to store passwords (or other private information) in Expect scripts. This is not recommended since anything that is stored on a computer is susceptible to being accessed by anyone. Thus, interactively prompting for passwords from a script is a smarter idea than embedding them literally. Nonetheless, sometimes such embedding is the only possibility. Unfortunately, the UNIX file system has no direct way of creating scripts which are executable but unreadable. Systems which support setgid shell scripts may indirectly simulate this as follows: Create the Expect script (that contains the secret data) as usual. Make its permissions be 750 (-rwxr-x---) and owned by a trusted group, i.e., a group which is allowed to read it. If necessary, create a new group for this purpose. Next, create a /bin/sh script with permissions 2751 (-rwxr-s--x) owned by the same group as before. The result is a script which may be executed (and read) by anyone. When invoked, it runs the Expect script. SEE ALSO Tcl(3), libexpect(3) "Exploring Expect: A Tcl-Based Toolkit for Automating Interactive Programs" by Don Libes, pp. 602, ISBN 1-56592-090-2, O'Reilly and Associates, 1995. "expect: Curing Those Uncontrollable Fits of Interactivity" by Don Libes, Proceedings of the Summer 1990 USENIX Conference, Anaheim, California, June 11-15, 1990. "Using expect to Automate System Administration Tasks" by Don Libes, Proceedings of the 1990 USENIX Large Installation Systems Administration Conference, Colorado Springs, Colorado, October 17-19, 1990. "Tcl: An Embeddable Command Language" by John Ousterhout, Proceedings of the Winter 1990 USENIX Conference, Washington, D.C., January 22-26, 1990. "expect: Scripts for Controlling Interactive Programs" by Don Libes, Computing Systems, Vol. 4, No. 2, University of California Press Journals, November 1991. "Regression Testing and Conformance Testing Interactive Programs", by Don Libes, Proceedings of the Summer 1992 USENIX Conference, pp. 135-144, San Antonio, TX, June 12-15, 1992. "Kibitz - Connecting Multiple Interactive Programs Together", by Don Libes, Software - Practice & Experience, John Wiley & Sons, West Sussex, England, Vol. 23, No. 5, May, 1993. "A Debugger for Tcl Applications", by Don Libes, Proceedings of the 1993 Tcl/Tk Workshop, Berkeley, CA, June 10-11, 1993. AUTHOR Don Libes, National Institute of Standards and Technology ACKNOWLEDGMENTS Thanks to John Ousterhout for Tcl, and Scott Paisley for inspiration. Thanks to Rob Savoye for Expect's autoconfiguration code. The HISTORY file documents much of the evolution of expect. It makes interesting reading and might give you further insight to this software. Thanks to the people mentioned in it who sent me bug fixes and gave other assistance. Design and implementation of Expect was paid for in part by the U.S. government and is therefore in the public domain. However the author and NIST would like credit if this program and documentation or portions of them are used. 29 December 1994 EXPECT(1)
jimage
null
null
null
null
null
lockstat
The lockstat utility gathers and displays kernel locking and profiling statistics. lockstat allows you to specify which events to watch (for example, spin on adaptive mutex, block on read access to rwlock due to waiting writers, and so forth) how much data to gather for each event, and how to display the data. By default, lockstat monitors all lock contention events, gathers frequency and timing data about those events, and displays the data in decreasing frequency order, so that the most common events appear first. lockstat gathers data until the specified command completes. For example, to gather statistics for a fixed-time interval, use sleep(1) as the command, as follows: example# lockstat sleep 5 When the -I option is specified, lockstat establishes a per-processor high-level periodic interrupt source to gather profiling data. The interrupt handler simply generates a lockstat event whose caller is the interrupted PC (program counter). The profiling event is just like any other lockstat event, so all of the normal lockstat options are applicable. lockstat relies on DTrace to modify the running kernel's text to intercept events of interest. This imposes a small but measurable overhead on all system activity, so access to lockstat is restricted to super-user by default. The system administrator can permit other users to use lockstat by granting them additional DTrace privileges. Refer to the Solaris Dynamic Tracing Guide for more information about DTrace security features.
lockstat - report kernel lock and profiling statistics
lockstat [-ACEHIS] [-e event_list] [-i rate] [-b | -t | -h | -s depth] [-n nrecords] [-l lock [, size]] [-d duration] [-f function [, size]] [-T] [-ckgwWRpP] [-D count] [-o filename] [-x opt [=val]] command [args]
The following options are supported: Event Selection If no event selection options are specified, the default is -C. -A Watch all lock events. -A is equivalent to -CH. -C Watch contention events. -E Watch error events. -e event_list Only watch the specified events. event list is a comma-separated list of events or ranges of events such as 1,4-7,35. Run lockstat with no arguments to get a brief description of all events. -H Watch hold events. -S Watch spinning time per lock group. -S Watch held/miss event counts per lock group. -I Watch profiling interrupt events. -i rate Interrupt rate (per second) for -I. The default is 97 Hz. Data Gathering -x arg[=val] Enable or modify a DTrace runtime option or D compiler option. The list of options is found in the . Boolean options are enabled by specifying their name. Options with values are set by separating the option name and value with an equals sign (=). Data Gathering (Mutually Exclusive) -b Basic statistics: lock, caller, number of events. -h Histogram: Timing plus time-distribution histograms. -s depth Stack trace: Histogram plus stack traces up to depth frames deep. -t Timing: Basic plus timing for all events [default]. Data Filtering -d duration Only watch events longer than duration. -f func[,size] Only watch events generated by func, which can be specified as a symbolic name or hex address. size defaults to the ELF symbol size if available, or 1 if not. -l lock[,size] Only watch lock, which can be specified as a symbolic name or hex address. size defaults to the ELF symbol size or 1 if the symbol size is not available. -n nrecords Maximum number of data records. -T Trace (rather than sample) events [off by default]. Data Reporting -c Coalesce lock data for lock arrays (for example, pse_mutex[]). -D count Only display the top count events of each type. -g Show total events generated by function. For example, if foo() calls bar() in a loop, the work done by bar() counts as work generated by foo() (along with any work done by foo() itself). The -g option works by counting the total number of stack frames in which each function appears. This implies two things: (1) the data reported by -g can be misleading if the stack traces are not deep enough, and (2) functions that are called recursively might show greater than 100% activity. In light of issue (1), the default data gathering mode when using -g is -s 50. -k Coalesce PCs within functions. -o filename Direct output to filename. -P Sort data by (count * time) product. -p Parsable output format. -R Display rates (events per second) rather than counts. -W Whichever: distinguish events only by caller, not by lock. -w Wherever: distinguish events only by lock, not by caller. DISPLAY FORMATS The following headers appear over various columns of data. abs Average duration of the events in mach tick units, as appropriate for the event. See mach_timebase_info to convert to nanoseconds. Count or ops/s Number of times this event occurred, or the rate (times per second) if -R was specified. indv Percentage of all events represented by this individual event. genr Percentage of all events generated by this function. cuml Cumulative percentage; a running total of the individuals. rcnt Average reference count. This will always be 1 for exclusive locks (mutexes, spin locks, rwlocks held as writer) but can be greater than 1 for shared locks (rwlocks held as reader). nsec Average duration of the events in nanoseconds, as appropriate for the event. For the profiling event, duration means interrupt latency. Lock Address of the lock; displayed symbolically if possible. CPU CPU, reported as cpu[id]. Caller Address of the caller; displayed symbolically if possible.
Example 1 Measuring Kernel Lock Contention example# lockstat sleep 5 Adaptive mutex spin: 2210 events in 5.055 seconds (437 events/sec) Count indv cuml rcnt nsec Lock Caller ------------------------------------------------------------------------ 269 12% 12% 1.00 2160 service_queue background+0xdc 249 11% 23% 1.00 86 service_queue qenable_locked+0x64 228 10% 34% 1.00 131 service_queue background+0x15c 68 3% 37% 1.00 79 0x30000024070 untimeout+0x1c 59 3% 40% 1.00 384 0x300066fa8e0 background+0xb0 43 2% 41% 1.00 30 rqcred_lock svc_getreq+0x3c 42 2% 43% 1.00 341 0x30006834eb8 background+0xb0 41 2% 45% 1.00 135 0x30000021058 untimeout+0x1c 40 2% 47% 1.00 39 rqcred_lock svc_getreq+0x260 37 2% 49% 1.00 2372 0x300068e83d0 hmestart+0x1c4 36 2% 50% 1.00 77 0x30000021058 timeout_common+0x4 36 2% 52% 1.00 354 0x300066fa120 background+0xb0 32 1% 53% 1.00 97 0x30000024070 timeout_common+0x4 31 1% 55% 1.00 2923 0x300069883d0 hmestart+0x1c4 29 1% 56% 1.00 366 0x300066fb290 background+0xb0 28 1% 57% 1.00 117 0x3000001e040 untimeout+0x1c 25 1% 59% 1.00 93 0x3000001e040 timeout_common+0x4 22 1% 60% 1.00 25 0x30005161110 sync_stream_buf+0xdc 21 1% 60% 1.00 291 0x30006834eb8 putq+0xa4 19 1% 61% 1.00 43 0x3000515dcb0 mdf_alloc+0xc 18 1% 62% 1.00 456 0x30006834eb8 qenable+0x8 18 1% 63% 1.00 61 service_queue queuerun+0x168 17 1% 64% 1.00 268 0x30005418ee8 vmem_free+0x3c [...] R/W reader blocked by writer: 76 events in 5.055 seconds (15 events/sec) Count indv cuml rcnt nsec Lock Caller ------------------------------------------------------------------------ 23 30% 30% 1.00 22590137 0x300098ba358 ufs_dirlook+0xd0 17 22% 53% 1.00 5820995 0x3000ad815e8 find_bp+0x10 13 17% 70% 1.00 2639918 0x300098ba360 ufs_iget+0x198 4 5% 75% 1.00 3193015 0x300098ba360 ufs_getattr+0x54 3 4% 79% 1.00 7953418 0x3000ad817c0 find_bp+0x10 3 4% 83% 1.00 935211 0x3000ad815e8 find_read_lof+0x14 2 3% 86% 1.00 16357310 0x300073a4720 find_bp+0x10 2 3% 88% 1.00 2072433 0x300073a4720 find_read_lof+0x14 2 3% 91% 1.00 1606153 0x300073a4370 find_bp+0x10 1 1% 92% 1.00 2656909 0x300107e7400 ufs_iget+0x198 [...] Example 2 Measuring Hold Times example# lockstat -H -D 10 sleep 1 Adaptive mutex spin: 513 events Count indv cuml rcnt nsec Lock Caller ------------------------------------------------------------------------- 480 5% 5% 1.00 1136 0x300007718e8 putnext+0x40 286 3% 9% 1.00 666 0x3000077b430 getf+0xd8 271 3% 12% 1.00 537 0x3000077b430 msgio32+0x2fc 270 3% 15% 1.00 3670 0x300007718e8 strgetmsg+0x3d4 270 3% 18% 1.00 1016 0x300007c38b0 getq_noenab+0x200 264 3% 20% 1.00 1649 0x300007718e8 strgetmsg+0xa70 216 2% 23% 1.00 6251 tcp_mi_lock tcp_snmp_get+0xfc 206 2% 25% 1.00 602 thread_free_lock clock+0x250 138 2% 27% 1.00 485 0x300007c3998 putnext+0xb8 138 2% 28% 1.00 3706 0x300007718e8 strrput+0x5b8 ------------------------------------------------------------------------- [...] Example 3 Measuring Hold Times for Stack Traces Containing a Specific Function example# lockstat -H -f tcp_rput_data -s 50 -D 10 sleep 1 Adaptive mutex spin: 11 events in 1.023 seconds (11 events/sec) ------------------------------------------------------------------------- Count indv cuml rcnt nsec Lock Caller 9 82% 82% 1.00 2540 0x30000031380 tcp_rput_data+0x2b90 nsec ------ Time Distribution ------ count Stack 256 |@@@@@@@@@@@@@@@@ 5 tcp_rput_data+0x2b90 512 |@@@@@@ 2 putnext+0x78 1024 |@@@ 1 ip_rput+0xec4 2048 | 0 _c_putnext+0x148 4096 | 0 hmeread+0x31c 8192 | 0 hmeintr+0x36c 16384 |@@@ 1 sbus_intr_wrapper+0x30 [...] Count indv cuml rcnt nsec Lock Caller 1 9% 91% 1.00 1036 0x30000055380 freemsg+0x44 nsec ------ Time Distribution ------ count Stack 1024 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 1 freemsg+0x44 tcp_rput_data+0x2fd0 putnext+0x78 ip_rput+0xec4 _c_putnext+0x148 hmeread+0x31c hmeintr+0x36c sbus_intr_wrapper+0x30 ------------------------------------------------------------------------- [...] Example 4 Basic Kernel Profiling For basic profiling, we don't care whether the profiling interrupt sampled foo()+0x4c or foo()+0x78; we care only that it sampled somewhere in foo(), so we use -k. The CPU and PIL aren't relevant to basic profiling because we are measuring the system as a whole, not a particular CPU or interrupt level, so we use -W. example# lockstat -kIW -D 20 ./polltest Profiling interrupt: 82 events in 0.424 seconds (194 events/sec) Count indv cuml rcnt nsec Hottest CPU Caller ----------------------------------------------------------------------- 8 10% 10% 1.00 698 cpu[1] utl0 6 7% 17% 1.00 299 master_cpu read 5 6% 23% 1.00 124 cpu[1] getf 4 5% 28% 1.00 327 master_cpu fifo_read 4 5% 33% 1.00 112 cpu[1] poll 4 5% 38% 1.00 212 cpu[1] uiomove 4 5% 43% 1.00 361 cpu[1] mutex_tryenter 3 4% 46% 1.00 682 master_cpu write 3 4% 50% 1.00 89 master_cpu pcache_poll 3 4% 54% 1.00 118 cpu[1] set_active_fd 3 4% 57% 1.00 105 master_cpu syscall_trap32 3 4% 61% 1.00 640 cpu[1] (usermode) 2 2% 63% 1.00 127 cpu[1] fifo_poll 2 2% 66% 1.00 300 cpu[1] fifo_write 2 2% 68% 1.00 669 master_cpu releasef 2 2% 71% 1.00 112 cpu[1] bt_getlowbit 2 2% 73% 1.00 247 cpu[1] splx 2 2% 76% 1.00 503 master_cpu mutex_enter 2 2% 78% 1.00 467 master_cpu disp_lock_enter 2 2% 80% 1.00 139 cpu[1] default_copyin ----------------------------------------------------------------------- [...] Example 5 Generated-load Profiling In the example above, 5% of the samples were in poll(). This tells us how much time was spent inside poll() itself, but tells us nothing about how much work was generated by poll(); that is, how much time we spent in functions called by poll(). To determine that, we use the -g option. The example below shows that although polltest spends only 5% of its time in poll() itself, poll()-induced work accounts for 34% of the load. Note that the functions that generate the profiling interrupt (lockstat_intr(), cyclic_fire(), and so forth) appear in every stack trace, and therefore are considered to have generated 100% of the load. This illustrates an important point: the generated load percentages do not add up to 100% because they are not independent. If 72% of all stack traces contain both foo() and bar(), then both foo() and bar() are 72% load generators. example# lockstat -kgIW -D 20 ./polltest Profiling interrupt: 80 events in 0.412 seconds (194 events/sec) Count genr cuml rcnt nsec Hottest CPU Caller ------------------------------------------------------------------------- 80 100% ---- 1.00 310 cpu[1] lockstat_intr 80 100% ---- 1.00 310 cpu[1] cyclic_fire 80 100% ---- 1.00 310 cpu[1] cbe_level14 80 100% ---- 1.00 310 cpu[1] current_thread 27 34% ---- 1.00 176 cpu[1] poll 20 25% ---- 1.00 221 master_cpu write 19 24% ---- 1.00 249 cpu[1] read 17 21% ---- 1.00 232 master_cpu write32 17 21% ---- 1.00 207 cpu[1] pcache_poll 14 18% ---- 1.00 319 master_cpu fifo_write 13 16% ---- 1.00 214 cpu[1] read32 10 12% ---- 1.00 208 cpu[1] fifo_read 10 12% ---- 1.00 787 cpu[1] utl0 9 11% ---- 1.00 178 master_cpu pcacheset_resolve 9 11% ---- 1.00 262 master_cpu uiomove 7 9% ---- 1.00 506 cpu[1] (usermode) 5 6% ---- 1.00 195 cpu[1] fifo_poll 5 6% ---- 1.00 136 cpu[1] syscall_trap32 4 5% ---- 1.00 139 master_cpu releasef 3 4% ---- 1.00 277 cpu[1] polllock ------------------------------------------------------------------------- [...] Example 6 Gathering Lock Contention and Profiling Data for a Specific Module In this example we use the -f option not to specify a single function, but rather to specify the entire text space of the sbus module. We gather both lock contention and profiling statistics so that contention can be correlated with overall load on the module. example# modinfo | grep sbus 24 102a8b6f b8b4 59 1 sbus (SBus (sysio) nexus driver) example# lockstat -kICE -f 0x102a8b6f,0xb8b4 sleep 10 Adaptive mutex spin: 39 events in 10.042 seconds (4 events/sec) Count indv cuml rcnt nsec Lock Caller ------------------------------------------------------------------------- 15 38% 38% 1.00 206 0x30005160528 sync_stream_buf 7 18% 56% 1.00 14 0x30005160d18 sync_stream_buf 6 15% 72% 1.00 27 0x300060c3118 sync_stream_buf 5 13% 85% 1.00 24 0x300060c3510 sync_stream_buf 2 5% 90% 1.00 29 0x300060c2d20 sync_stream_buf 2 5% 95% 1.00 24 0x30005161cf8 sync_stream_buf 1 3% 97% 1.00 21 0x30005161110 sync_stream_buf 1 3% 100% 1.00 23 0x30005160130 sync_stream_buf [...] Adaptive mutex block: 9 events in 10.042 seconds (1 events/sec) Count indv cuml rcnt nsec Lock Caller ------------------------------------------------------------------------- 4 44% 44% 1.00 156539 0x30005160528 sync_stream_buf 2 22% 67% 1.00 763516 0x30005160d18 sync_stream_buf 1 11% 78% 1.00 462130 0x300060c3510 sync_stream_buf 1 11% 89% 1.00 288749 0x30005161110 sync_stream_buf 1 11% 100% 1.00 1015374 0x30005160130 sync_stream_buf [...] Profiling interrupt: 229 events in 10.042 seconds (23 events/sec) Count indv cuml rcnt nsec Hottest CPU Caller ------------------------------------------------------------------------- 89 39% 39% 1.00 426 master_cpu sync_stream_buf 64 28% 67% 1.00 398 master_cpu sbus_intr_wrapper 23 10% 77% 1.00 324 master_cpu iommu_dvma_kaddr_load 21 9% 86% 1.00 512 master_cpu iommu_tlb_flush 14 6% 92% 1.00 342 master_cpu iommu_dvma_unload 13 6% 98% 1.00 306 cpu[1] iommu_dvma_sync 5 2% 100% 1.00 389 cpu[1] iommu_dma_bindhdl ------------------------------------------------------------------------- [...] Example 8 Determining which Subsystem is Causing the System to be Busy example# lockstat -s 10 -I sleep 20 Profiling interrupt: 4863 events in 47.375 seconds (103 events/sec) Count indv cuml rcnt nsec CPU Caller ----------------------------------------------------------------------- 1929 40% 40% 0.00 3215 master_cpu usec_delay+0x78 nsec ------ Time Distribution ------ count Stack 4096 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 1872 ata_wait+0x90 8192 | 27 acersb_get_intr_status+0x34 16384 | 29 ata_set_feature+0x124 32768 | 1 ata_disk_start+0x15c ata_hba_start+0xbc ghd_waitq_process_and \ _mutex_hold+0x70 ghd_waitq_process_and \ _mutex_exit+0x4 ghd_transport+0x12c ata_disk_tran_start+0x108 ----------------------------------------------------------------------- [...] SEE ALSO dtrace(1M), plockstat(1M) Solaris Dynamic Tracing Guide NOTES The profiling support provided by lockstat -I replaces the old (and undocumented) /usr/bin/kgmon and /dev/profile. Tail-call elimination can affect call sites. For example, if foo()+0x50 calls bar() and the last thing bar() does is call mutex_exit(), the compiler can arrange for bar() to branch to mutex_exit()with a return address of foo()+0x58. Thus, the mutex_exit() in bar() will appear as though it occurred at foo()+0x58. The PC in the stack frame in which an interrupt occurs can be bogus because, between function calls, the compiler is free to use the return address register for local storage. When using the -I and -s options together, the interrupted PC will usually not appear anywhere in the stack since the interrupt handler is entered asynchronously, not by a function call from that PC. The lockstat technology is provided on an as-is basis. The format and content of lockstat output reflect the current Darwin kernel implementation and are therefore subject to change in future releases. July 24, 2020 LOCKSTAT(1M)
dapptrace
dapptrace prints details on user and library function calls. By default it traces user functions only, options can be used to trace library activity. Of particular interest is the elapsed times and on cpu times, which can identify both function calls that are slow to complete, and those which are consuming CPU cycles. Since this uses DTrace, only users with root privileges can run this command.
dapptrace - trace user and library function usage. Uses DTrace.
dapptrace [-acdeFlhoU] [-u lib] { -p PID | command }
-a print all details -b bufsize dynamic variable buffer size. Increase this if you notice dynamic variable drop errors. The default is "4m" for 4 megabytes per CPU. -c print function call counts -d print relative timestamps, us -e print elapsed times, us -F print flow indentation -l force printing of pid/lwpid per line -o print on-cpu times, us -p PID examine this PID -u lib trace this library instead -U trace all library and user functions
run and examine the "df -h" command, # dapptrace df -h examine PID 1871, # dapptrace -p 1871 print using flow indents, # dapptrace -Fp 1871 print elapsed and CPU times, # dapptrace -eop 1871 FIELDS PID/LWPID Process ID / Lightweight Process ID RELATIVE relative timestamps to the start of the thread, us (microseconds) ELAPSD elapsed time for this system call, us CPU on-cpu time for this system call, us CALL(args) function call name, with some arguments in hexadecimal DOCUMENTATION See the DTraceToolkit for further documentation under the Docs directory. The DTraceToolkit docs may include full worked examples with verbose descriptions explaining the output. EXIT dapptrace will run forever until Ctrl-C is hit, or if a command was executed dapptrace will finish when the command ends. AUTHOR Brendan Gregg [Sydney, Australia] SEE ALSO dappprof(1M), dtrace(1M), apptrace(1) version 1.10 May 14, 2005 dapptrace(1m)
xattr
The xattr command can be used to display, modify or remove the extended attributes of one or more files, including directories and symbolic links. Extended attributes are arbitrary metadata stored with a file, but separate from the filesystem attributes (such as modification time or file size). The metadata is often a null-terminated UTF-8 string, but can also be arbitrary binary data. One or more files may be specified on the command line. For the first two forms of the command, when there are more than one file, the file name is displayed along with the actual results. When only one file is specified, the display of the file name is usually suppressed (unless the -v option described below, is also specified). In the first form of the command (without any other mode option specified), the names of all extended attributes are listed. Attribute names can also be displayed using “ls -l@”. In the second form, using the -p option (“print”), the value associated with the given attribute name is displayed. Attribute values are usually displayed as strings. However, if nils are detected in the data, the value is displayed in a hexadecimal representation. The third form, with the -w option (“write”), causes the given attribute name to be assigned the given value. The fourth form, with the -d option (“delete”), causes the given attribute name (and associated value), to be removed. In the fifth form, with the -c option (“clear”), causes all attributes (including their associated values), to be removed. Finally, the last form, with either the -h or --help option, displays a short help message and exits immediately.
xattr – display and manipulate extended attributes
xattr [-lrsvx] file ... xattr -p [-lrsvx] attr_name file ... xattr -w [-rsx] attr_name attr_value file ... xattr -d [-rsv] attr_name file ... xattr -c [-rsv] file ... xattr -h | --help
-l By default, the first two command forms either displays just the attribute names or values, respectively. The -l option causes both the attribute names and corresponding values to be displayed. For hexadecimal display of values, the output is preceeded with the hexadecimal offset values and followed by ASCII display, enclosed by “|”. -r If a file argument is a directory, act as if the entire contents of the directory recursively were also specified (so that every file in the directory tree is acted upon). -s If a file argument is a symbolic link, act on the symbolic link itself, rather than the file that the symbolic link points at. -v Force the file name to be displayed, even for a single file. -x Force the attribute value to be displayed in the hexadecimal representation. The -w option normally assumes the input attribute value is a string. Specifying the -x option causes xattr to expect the input in hexadecimal (whitespace is ignored). The xxd(1) command can be used to create hexadecimal representations from existing binary data, to pass to xattr. EXIT STATUS The xattr command exits with zero status on success. On error, non-zero is returned, and an error message is printed to the standard error. For system call errors, both the error code and error string are printed (see getxattr(2), listxattr(2), removexattr(2) and setxattr(2) for a complete list of possible error codes). Some attribute data may have a fixed length that is enforced by the system. For example, % xattr -w com.apple.FinderInfo 0 foo xattr: [Errno 34] Result too large: 'foo' The com.apple.FinderInfo attribute must be 32 bytes in length.
This example copies the com.apple.FinderInfo attribute from the /usr directory to the MyDir directory: % xattr -px com.apple.FinderInfo /usr 00 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 % xattr -l MyDir % xattr -wx com.apple.FinderInfo \ "`xattr -px com.apple.FinderInfo /usr`" MyDir % xattr -l MyDir com.apple.FinderInfo: 00000000 00 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00 |........@.......| 00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 00000020 SEE ALSO ls(1), xxd(1), getxattr(2), listxattr(2), removexattr(2), setxattr(2) macOS 14.5 November 29, 2010 macOS 14.5
w
The w utility prints a summary of the current activity on the system, including what each user is doing. The first line displays the current time of day, how long the system has been running, the number of users logged into the system, and the load averages. The load average numbers give the number of jobs in the run queue averaged over 1, 5 and 15 minutes. The fields output are the user's login name, the name of the terminal the user is on, the host from which the user is logged in, the time the user logged on, the time since the user last typed anything, and the name and arguments of the current process. The options are as follows: --libxo Generate output via libxo(3) in a selection of different human and machine readable formats. See xo_parse_args(3) for details on command line arguments. -h Suppress the heading. -i Output is sorted by idle time. -n Do not attempt to resolve network addresses (normally w interprets addresses and attempts to display them as names). When -n is specified more than once, hostnames stored in utmp are attempted to resolve to display them as network addresses. If one or more user names are specified, the output is restricted to those users. COMPATIBILITY The -M, -N, -d, -f, -l, -s, and -w flags are no longer supported. SEE ALSO finger(1), ps(1), uptime(1), who(1), libxo(3), xo_parse_args(3) HISTORY The w command appeared in 3.0BSD. BUGS The notion of the “current process” is muddy. The current algorithm is “the highest numbered process on the terminal that is not ignoring interrupts, or, if there is none, the highest numbered process on the terminal”. This fails, for example, in critical sections of programs like the shell and editor, or when faulty programs running in the background fork and fail to ignore interrupts. (In cases where no process can be found, w prints ‘-’.) The CPU time is only an estimate, in particular, if someone leaves a background process running after logging out, the person currently on that terminal is “charged” with the time. Background processes are not shown, even though they account for much of the load on the system. Sometimes processes, typically those in the background, are printed with null or garbaged arguments. In these cases, the name of the command is printed in parentheses. The w utility does not know about the new conventions for detection of background jobs. It will sometimes find a background job instead of the right one. Long hostnames and IPv6 addresses may be truncated. macOS 14.5 August 24, 2020 macOS 14.5
w – display who is logged in and what they are doing
w [--libxo] [-hin] [user ...]
null
null
gunzip
The gzip program compresses and decompresses files using Lempel-Ziv coding (LZ77). If no files are specified, gzip will compress from standard input, or decompress to standard output. When in compression mode, each file will be replaced with another file with the suffix, set by the -S suffix option, added, if possible. In decompression mode, each file will be checked for existence, as will the file with the suffix added. Each file argument must contain a separate complete archive; when multiple files are indicated, each is decompressed in turn. In the case of gzcat the resulting data is then concatenated in the manner of cat(1). If invoked as gunzip then the -d option is enabled. If invoked as zcat or gzcat then both the -c and -d options are enabled. This version of gzip is also capable of decompressing files compressed using compress(1), bzip2(1), lzip, or xz(1).
gzip, gunzip, zcat – compression/decompression tool using Lempel-Ziv coding (LZ77)
gzip [-cdfhkLlNnqrtVv] [-S suffix] file [file [...]] gunzip [-cfhkLNqrtVv] [-S suffix] file [file [...]] zcat [-fhV] file [file [...]]
The following options are available: -1, --fast -2, -3, -4, -5, -6, -7, -8 -9, --best These options change the compression level used, with the -1 option being the fastest, with less compression, and the -9 option being the slowest, with optimal compression. The default compression level is 6. -c, --stdout, --to-stdout This option specifies that output will go to the standard output stream, leaving files intact. -d, --decompress, --uncompress This option selects decompression rather than compression. -f, --force This option turns on force mode. This allows files with multiple links, symbolic links to regular files, overwriting of pre-existing files, reading from or writing to a terminal, and when combined with the -c option, allowing non-compressed data to pass through unchanged. -h, --help This option prints a usage summary and exits. -k, --keep This option prevents gzip from deleting input files after (de)compression. -L, --license This option prints gzip license. -l, --list This option displays information about the file's compressed and uncompressed size, ratio, uncompressed name. With the -v option, it also displays the compression method, CRC, date and time embedded in the file. -N, --name This option causes the stored filename in the input file to be used as the output file. -n, --no-name This option stops the filename and timestamp from being stored in the output file. -q, --quiet With this option, no warnings or errors are printed. -r, --recursive This option is used to gzip the files in a directory tree individually, using the fts(3) library. -S suffix, --suffix suffix This option changes the default suffix from .gz to suffix. -t, --test This option will test compressed files for integrity. -V, --version This option prints the version of the gzip program. -v, --verbose This option turns on verbose mode, which prints the compression ratio for each file compressed. ENVIRONMENT If the environment variable GZIP is set, it is parsed as a white-space separated list of options handled before any options on the command line. Options on the command line will override anything in GZIP. EXIT STATUS The gzip utility exits 0 on success, 1 on errors, and 2 if a warning occurs. SIGNALS gzip responds to the following signals: SIGINFO Report progress to standard error. SEE ALSO bzip2(1), compress(1), xz(1), fts(3), zlib(3) HISTORY The gzip program was originally written by Jean-loup Gailly, licensed under the GNU Public Licence. Matthew R. Green wrote a simple front end for NetBSD 1.3 distribution media, based on the freely re-distributable zlib library. It was enhanced to be mostly feature-compatible with the original GNU gzip program for NetBSD 2.0. This implementation of gzip was ported based on the NetBSD gzip version 20181111, and first appeared in FreeBSD 7.0. AUTHORS This implementation of gzip was written by Matthew R. Green <mrg@eterna.com.au> with unpack support written by Xin LI <delphij@FreeBSD.org>. BUGS According to RFC 1952, the recorded file size is stored in a 32-bit integer, therefore, it cannot represent files larger than 4GB. This limitation also applies to -l option of gzip utility. macOS 14.5 January 7, 2019 macOS 14.5
null
cat
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. If file is a UNIX domain socket, cat connects to it and then reads it until EOF. This complements the UNIX domain binding capability available in inetd(8). The options are as follows: -b Number the non-blank output lines, starting at 1. -e Display non-printing characters (see the -v option), and display a dollar sign (‘$’) at the end of each line. -l Set an exclusive advisory lock on the standard output file descriptor. This lock is set using fcntl(2) with the F_SETLKW command. If the output file is already locked, cat will block until the lock is acquired. -n Number the output lines, starting at 1. -s Squeeze multiple adjacent empty lines, causing the output to be single spaced. -t Display non-printing characters (see the -v option), and display tab characters as ‘^I’. -u Disable output buffering. -v Display non-printing characters so they are visible. Control characters print as ‘^X’ for control-X; the delete 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. EXIT STATUS The cat utility exits 0 on success, and >0 if an error occurs.
cat – concatenate and print files
cat [-belnstuv] [file ...]
null
The command: cat file1 will print the contents of file1 to the standard output. The command: cat file1 file2 > file3 will 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. The command: cat file1 - file2 - file3 will 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. SEE ALSO head(1), more(1), pr(1), sh(1), tail(1), vis(1), zcat(1), fcntl(2), 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. The flags [-belnstv] are extensions to the specification. HISTORY A cat utility appeared in Version 1 AT&T UNIX. Dennis Ritchie designed and wrote the first man page. It appears to have been for cat. 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! The cat utility does not recognize multibyte characters when the -t or -v option is in effect. macOS 14.5 January 29, 2013 macOS 14.5
echo
The echo utility writes any specified operands, separated by single blank (‘ ’) characters and followed by a newline (‘\n’) character, to the standard output. The following option is available: -n Do not print the trailing newline character. This may also be achieved by appending ‘\c’ to the end of the string, as is done by iBCS2 compatible systems. Note that this option as well as the effect of ‘\c’ are implementation-defined in IEEE Std 1003.1-2001 (“POSIX.1”) as amended by Cor. 1-2002. Applications aiming for maximum portability are strongly encouraged to use printf(1) to suppress the newline character. Some shells may provide a builtin echo command which is similar or identical to this utility. Most notably, the builtin echo in sh(1) does not accept the -n option. Consult the builtin(1) manual page. EXIT STATUS The echo utility exits 0 on success, and >0 if an error occurs. SEE ALSO builtin(1), csh(1), printf(1), sh(1) STANDARDS The echo utility conforms to IEEE Std 1003.1-2001 (“POSIX.1”) as amended by Cor. 1-2002. macOS 14.5 April 12, 2003 macOS 14.5
echo – write arguments to the standard output
echo [-n] [string ...]
null
null
launchctl
launchctl interfaces with launchd to manage and inspect daemons, agents and XPC services. SUBCOMMANDS launchctl allows for detailed examination of launchd's data structures. The fundamental structures are domains, services, and endpoints. A domain manages the execution policy for a collection of services. A service may be thought of as a virtual process that is always available to be spawned in response to demand. Each service has a collection of endpoints, and sending a message to one of those endpoints will cause the service to launch on demand. Domains advertise these endpoints in a shared namespace and may be thought of as synonymous with Mach bootstrap subsets. Many subcommands in launchctl take a specifier which indicates the target domain or service for the subcommand. This specifier may take one of the following forms: system/[service-name] Targets the system domain or a service within the system domain. The system domain manages the root Mach bootstrap and is considered a privileged execution context. Anyone may read or query the system domain, but root privileges are required to make modifications. user/<uid>/[service-name] Targets the user domain for the given UID or a service within that domain. A user domain may exist independently of a logged- in user. User domains do not exist on iOS. login/<asid>/[service-name] Targets a user-login domain or service within that domain. A user-login domain is created when the user logs in at the GUI and is identified by the audit session identifier associated with that login. If a user domain has an associated login domain, the print subcommand will display the ASID of that login domain. User-login domains do not exist on iOS. gui/<uid>/[service-name] Another form of the login specifier. Rather than specifying a user-login domain by its ASID, this specifier targets the domain based on which user it is associated with and is generally more convenient. Note: GUI domains and user domains share many resources. For the purposes of the Mach bootstrap name lookups, they are "flat", so they share the same set of registered names. But they still have discrete sets of services. So when printing the user domain's contents, you may see many Mach bootstrap name registrations from services that exist in the GUI domain for that user, but you will not see the services themselves in that list. pid/<pid>/[service-name] Targets the domain for the given PID or a service within that domain. Each process on the system will have a PID domain associated with it that consists of the XPC services visible to that process which can be reached with xpc_connection_create(3). For instance, when referring to a service with the identifier com.apple.example loaded into the GUI domain of a user with UID 501, domain-target is gui/501/, service-name is com.apple.example, and service-target is gui/501/com.apple.example. SUBCOMMANDS bootstrap | bootout domain-target [service-path service-path2 ...] | service-target Bootstraps or removes domains and services. When service arguments are present, bootstraps and correspondingly removes their definitions into the domain. Services may be specified as a series of paths or a service identifier. Paths may point to XPC service bundles, launchd.plist(5) s, or a directories containing a collection of either. If there were one or more errors while bootstrapping or removing a collection of services, the problematic paths will be printed with the errors that occurred. If no paths or service target are specified, these commands can either bootstrap or remove a domain specified as a domain target. Some domains will implicitly bootstrap pre-defined paths as part of their creation. enable | disable service-target Enables or disables the service in the requested domain. Once a service is disabled, it cannot be loaded in the specified domain until it is once again enabled. This state persists across boots of the device. This subcommand may only target services within the system domain or user and user-login domains. kickstart [-kp] service-target Instructs launchd to run the specified service immediately, regardless of its configured launch conditions. -k If the service is already running, kill the running instance before restarting the service. -p Upon success, print the PID of the new process or the already-running process to stdout. attach [-ksx] service-target Attaches the system's debugger to the process currently backing the specified service. By default, if the service is not running, this subcommand will block until the service starts. -k If the service is already running, kill the running instance. -s Force the service to start. -x Attach to xpcproxy(3) before it execs and becomes the service process. This flag is generally not useful for anyone but the launchd maintainer. debug service-target [--program <program path>] [--guard-malloc] [--malloc-stack-logging] [--debug-libraries] [--introspection-libraries] [--NSZombie] [--32] [--stdin] [--stdout] [--stderr] [--environment] [--] [argv0 argv1 argv2 ...] Configures the next invocation of a service for debugging. This subcommand allows you to temporarily replace the main executable of the service with one at a different path, enable libgmalloc(3), set environment variables, set the argument vector and more. This is a convenient alternative to editing the launchd.plist(5) for the service and then reloading it, as the additional debugging properties are cleared once the service has run once with them. --program <program-path> Instructs launchd(8) to use program-path as the service's executable. --guard-malloc Turns on libgmalloc(3) for the service. --malloc-stack-logging Turns on malloc(3) stack logging for the service. --malloc-nano-allocator Turns on the malloc(3) nano allocator for the service. --debug-libraries Sets the DYLD_IMAGE_SUFFIX for the service to "_debug", which prefers the debug variants of libraries if they exist. See dyld(1) for more information. --introspection-libraries Adds /usr/lib/system/introspection to the DYLD_LIBRARY_PATH environment variable for the service. This causes the system to prefer the introspection variants of libraries if they exist. --NSZombie Enables NSZombie. --32 Runs the service in the appropriate 32-bit architecture. Only available on 64-bit platforms. --stdin [stdin-path] Sets the service's standard input to be stdin-path. If no file is given, uses the current terminal as the service's standard input. If stdin-path does not exist, it is created. --stdout [stdout-path] Sets the service's standard input to be stdout-path. If no file is given, uses the current terminal as the service's standard input. If stdout-path does not exist, it is created. --stderr [stderr-path] Sets the service's standard input to be stderr-path. If no file is given, uses the current terminal as the service's standard input. If stderr-path does not exist, it is created. --environment VARIABLE0=value VARIABLE1=value ... Sets the given environment variables on the service. -- argv0 argv1 ... Any arguments following the -- are given to the service as its argument vector. IMPORTANT: These arguments replace the service's default argument vector; they are not merged in any way. The first argument following -- is given as the initial (zeroth) element of the service's argument vector. As with the ProgramArguments launchd.plist(5) key, you should read carefully and understand the execve(2) man page. kill signal-name | signal-number service-target Sends the specified signal to the specified service if it is running. The signal number or name (SIGTERM, SIGKILL, etc.) may be specified. blame service-target If the service is running, prints a human-readable string describing why launchd launched the service. Note that services may run for many reasons; this subcommand will only show the most proximate reason. So if a service was run due to a timer firing, this subcommand will print that reason, irrespective of whether there were messages waiting on the service's various endpoints. This subcommand is only intended for debugging and profiling use and its output should not be relied upon in production scenarios. print domain-target | service-target Prints information about the specified service or domain. Domain output includes various properties about the domain as well as a list of services and endpoints in the domain with state pertaining to each. Service output includes various properties of the service, including information about its origin on-disk, its current state, execution context, and last exit status. IMPORTANT: This output is NOT API in any sense at all. Do NOT rely on the structure or information emitted for ANY reason. It may change from release to release without warning. print-cache Prints the contents of the launchd service cache. print-disabled domain-target Prints the list of disabled services in the specified domain. plist [segment,section] Mach-O Prints the the property list embedded in the __TEXT,__info_plist segment/section of the target Mach-O or the specified segment/section. procinfo pid Prints information about the execution context of the specified PID. This information includes Mach task-special ports and exception ports (and when run against a DEVELOPMENT launchd, what names the ports are advertised as in the Mach bootstrap namespace, if they are known to launchd) and audit session context. This subcommand is intended for diagnostic purposes only, and its output should not be relied upon in production scenarios. This command requires root privileges. hostinfo Prints information about the system's host-special ports, including the host-exception port. This subcommand requires root privileges. resolveport owner-pid port-name Given a PID and the name of a Mach port right in that process' port namespace, resolves that port to an endpoint name known to launchd. This subcommand requires root privileges. examine [tool arg0 arg1 @PID ...] Causes launchd to fork(2) itself for examination by a profiling tool and prints the PID of this new instance to stdout. You are responsible for killing this snapshot when it is no longer needed. Many profiling tools cannot safely examine launchd because they depend on the functionality it provides. This subcommand creates an effective snapshot of launchd that can be examined independently. Note that on Darwin platforms, fork(2) is implemented such that only the thread which called fork(2) is replicated into the new child process, so this subcommand is not useful for examining any thread other than the main event loop. This subcommand takes an optional invocation of a tool to be used on the launchd snapshot. Where you would normally give the PID of the process to be examined in the tool's invocation, instead specify the argument "@PID", and launchctl will substitute that argument with the PID of the launchd snapshot in its subsequent execution of the tool. If used in this form, launchctl will automatically kill the snapshot instance when the examination tool exits. This subcommand may only be used against a DEVELOPMENT launchd. config system | user parameter value Sets persistent configuration information for launchd(8) domains. Only the system domain and user domains may be configured. The location of the persistent storage is an implementation detail, and changes to that storage should only be made through this subcommand. A reboot is required for changes made through this subcommand to take effect. Supported configuration parameters are: umask Sets the umask(2) for services within the target domain to the value specified by value. Note that this value is parsed by strtoul(3) as an octal-encoded number, so there is no need to prefix it with a leading '0'. path Sets the PATH environment variable for all services within the target domain to the string value. The string value should conform to the format outlined for the PATH environment variable in environ(7). Note that if a service specifies its own PATH, the service- specific environment variable will take precedence. NOTE: This facility cannot be used to set general environment variables for all services within the domain. It is intentionally scoped to the PATH environment variable and nothing else for security reasons. reboot [system|userspace|halt|logout|apps] Instructs launchd to begin tearing down userspace. With no argument given or with the system argument given, launchd will make the reboot(2) system call when userspace has been completely torn down. With the halt argument given, launchd will make the reboot(2) system call when userspace has been completely torn down and pass the RB_HALT flag, halting the system and not initiating a reboot. With the userspace argument given, launchd will re-exec itself when userspace has been torn down and bring userspace back up. This is useful for rebooting the system quickly under conditions where kernel data structures or hardware do not need to be re- initialized. With the logout argument given, launchd will tear down the caller's GUI login session in a manner similar to a logout initiated from the Apple menu. The key difference is that a logout initiated through this subcommand will be much faster since it will not give apps a chance to display modal dialogs to block logout indefinitely; therefore there is data corruption risk to using this option. Only use it when you know you have no unsaved data in your running apps. With the apps argument given, launchd will terminate all apps running in the caller's GUI login session that did not come from a launchd.plist(5) on-disk. Apps like Finder, Dock and SystemUIServer will be unaffected. Apps are terminated in the same manner as the logout argument, and all the same caveats apply. error [posix|mach|bootstrap] code Prints a human-readable string of the given error code. By default, launchctl will attempt to guess which error domain the code given belongs to. The caller may optionally specify which domain (either posix, mach, or bootstrap) to interpret the given code as an error from that subsystem. variant Prints the launchd variant currently active on the system. Possible variants include RELEASE, DEVELOPMENT and DEBUG. version Prints the launchd version string. LEGACY SUBCOMMANDS Legacy subcommands select the target domain based on whether they are executed as root or not. When executed as root, they target the system domain. load | unload [-wF] [-S sessiontype] [-D searchpath] paths ... Recommended alternative subcommands: bootstrap | bootout | enable | disable Load the specified configuration files or directories of configuration files. Jobs that are not on-demand will be started as soon as possible. All specified jobs will be loaded before any of them are allowed to start. Note that per-user configuration files (LaunchAgents) must be owned by root (if they are located in /Library/LaunchAgents) or the user loading them (if they are located in $HOME/Library/LaunchAgents). All system-wide daemons (LaunchDaemons) must be owned by root. Configuration files must disallow group and world writes. These restrictions are in place for security reasons, as allowing writability to a launchd configuration file allows one to specify which executable will be launched. Note that allowing non-root write access to the /System/Library/LaunchDaemons directory WILL render your system unbootable. -w Overrides the Disabled key and sets it to false or true for the load and unload subcommands respectively. In previous versions, this option would modify the configuration file. Now the state of the Disabled key is stored elsewhere on- disk in a location that may not be directly manipulated by any process other than launchd. -F Force the loading or unloading of the plist. Ignore the Disabled key. -S sessiontype Some jobs only make sense in certain contexts. This flag instructs launchctl to look for jobs in a different location when using the -D flag, and allows launchctl to restrict which jobs are loaded into which session types. Sessions are only relevant for per-user launchd contexts. Relevant sessions are Aqua (the default), Background and LoginWindow. Background agents may be loaded independently of a GUI login. Aqua agents are loaded only when a user has logged in at the GUI. LoginWindow agents are loaded when the LoginWindow UI is displaying and currently run as root. -D searchpath Load or unload all plist(5) files in the search path given. This option may be thought of as expanding into many individual paths depending on the search path given. Valid search paths include "system," "local," and "all." When providing a session type, an additional search path is available for use called "user." For example, without a session type given, "-D system" would load from or unload all property list files from /System/Library/LaunchDaemons. With a session type passed, it would load from /System/Library/LaunchAgents. Note that launchctl no longer respects the network search path. In a previous version of launchd, these search paths were called "domains", hence -D. The word "domain" is now used for a totally different concept. NOTE: Due to bugs in the previous implementation and long- standing client expectations around those bugs, the load and unload subcommands will only return a non-zero exit code due to improper usage. Otherwise, zero is always returned. submit -l label [-p executable] [-o stdout-path] [-e stderr-path] -- command [arg0] [arg1] [...] A simple way of submitting a program to run without a configuration file. This mechanism also tells launchd to keep the program alive in the event of failure. -l label What unique label to assign this job to launchd. -p program What program to really execute, regardless of what follows the -- in the submit sub-command. -o stdout-path Where to send the stdout of the program. -e stderr-path Where to send the stderr of the program. remove label Remove the job from launchd by label. This subcommand will return immediately and not block until the job has been stopped. start label Start the specified job by label. The expected use of this subcommand is for debugging and testing so that one can manually kick-start an on-demand server. stop label Stop the specified job by label. If a job is on-demand, launchd may immediately restart the job if launchd finds any criteria that is satisfied. list [-x] [label] Recommended alternative subcommand: print With no arguments, list all of the jobs loaded into launchd in three columns. The first column displays the PID of the job if it is running. The second column displays the last exit status of the job. If the number in this column is negative, it represents the negative of the signal which stopped the job. Thus, "-15" would indicate that the job was terminated with SIGTERM. The third column is the job's label. If [label] is specified, prints information about the requested job. -x This flag is no longer supported. setenv key value Specify an environment variable to be set on all future processes launched by launchd in the caller's context. unsetenv key Specify that an environment variable no longer be set on any future processes launched by launchd in the caller's context. getenv key Print the value of an environment variable that launchd would set for all processes launched into the caller's context. export Export all of the environment variables of launchd for use in a shell eval statement. getrusage self | children Get the resource utilization statistics for launchd or the children of launchd. This subcommand is not implemented. limit [cpu | filesize | data | stack | core | rss | memlock | maxproc | maxfiles] [both [soft | hard]] With no arguments, this command prints all the resource limits of launchd as found via getrlimit(2). When a given resource is specified, it prints the limits for that resource. With a third argument, it sets both the hard and soft limits to that value. With four arguments, the third and forth argument represent the soft and hard limits respectively. See setrlimit(2). shutdown Tell launchd to prepare for shutdown by removing all jobs. This subcommand is not implemented. umask [newmask] Get or optionally set the umask(2) of launchd. This subcommand is not implemented. bslist [PID | ..] [-j] This subcommand is not implemented and has been superseded by the print subcommand, which provides much richer information. bsexec PID command [args] This executes the given command in as similar an execution context as possible to the target PID. Adopted attributes include the Mach bootstrap namespace, exception server and security audit session. It does not modify the process' credentials (UID, GID, etc.) or adopt any environment variables from the target process. It affects only the Mach bootstrap context and directly-related attributes. asuser UID command [args] This executes the given command in as similar an execution context as possible to that of the target user's bootstrap. Adopted attributes include the Mach bootstrap namespace, exception server and security audit session. It does not modify the process' credentials (UID, GID, etc.) or adopt any user- specific environment variables. It affects only the Mach bootstrap context and directly- related attributes. bstree This subcommand is not implemented and has been superseded by the print subcommand, which provides much richer information. managerpid This prints the PID of the launchd which manages the current bootstrap. In prior implementations, there could be multiple launchd processes each managing their own Mach bootstrap subsets. In the current implementation, all bootstraps are managed by one process, so this subcommand will always print "1". manageruid This prints the UID associated with the caller's launchd context. managername This prints the name of the launchd job manager which manages the current launchd context. See LimitLoadToSessionType in launchd.plist(5) for more details. help Print out a quick usage statement. CAVEATS The output produced by the "legacy" subcommands (chiefly list) should match their output on previous OS X releases. However, the output of newer subcommands does not conform to any particular format and is not guaranteed to remain stable across releases. These commands are intended for use by human developers and system administrators, not for automation by programs or scripts. Their output does not constitute an API and no promises of forward compatibility are offered to programs that attempt to parse it. DEPRECATED AND REMOVED FUNCTIONALITY launchctl no longer has an interactive mode, nor does it accept commands from stdin. The /etc/launchd.conf file is no longer consulted for subcommands to run during early boot time; this functionality was removed for security considerations. While it was documented that $HOME/.launchd.conf would be consulted prior to setting up a user's session, this functionality was never implemented. launchd no longer uses Unix domain sockets for communication, so the LAUNCHD_SOCKET environment variable is no longer relevant and is not set. launchd no longer loads configuration files from the network FILES ~/Library/LaunchAgents Per-user agents provided by the user. /Library/LaunchAgents Per-user agents provided by the administrator. /Library/LaunchDaemons System wide daemons provided by the administrator. /System/Library/LaunchAgents OS X Per-user agents. /System/Library/LaunchDaemons OS X System wide daemons. EXIT STATUS launchctl will exit with status 0 if the subcommand succeeded. Otherwise, it will exit with an error code that can be given to the error subcommand to be decoded into human-readable form. SEE ALSO launchd.plist(5), launchd(8), audit(8), setaudit_addr(2) Darwin 1 October, 2014 Darwin
launchctl – Interfaces with launchd
launchctl subcommand [arguments ...]
null
null
df
The df utility displays statistics about the amount of free disk space on the specified mounted file system or on the file system of which file is a part. By default block counts are displayed with an assumed block size of 512 bytes. If neither a file or a file system operand is specified, statistics for all mounted file systems are displayed (subject to the -t option below). The following options are available: --libxo Generate output via libxo(3) in a selection of different human and machine readable formats. See xo_parse_args(3) for details on command line arguments. -a Show all mount points, including those that were mounted with the MNT_IGNORE flag. This is implied for file systems specified on the command line. -b Explicitly use 512 byte blocks, overriding any BLOCKSIZE specification from the environment. This is the same as the -P option. The -k option overrides this option. -c Display a grand total. -g Use 1073741824 byte (1 Gibibyte) blocks rather than the default. This overrides any BLOCKSIZE specification from the environment. -h “Human-readable” output. Use unit suffixes: Byte, Kibibyte, Mebibyte, Gibibyte, Tebibyte and Pebibyte (based on powers of 1024) in order to reduce the number of digits to four or fewer. This applies to the Size, Used, and Avail columns only; the iused and ifree columns will be displayed in powers of 1000. -H, --si Same as -h but based on powers of 1000. -I Suppress inode counts. See -i below. -i Include statistics on the number of free and used inodes. In conjunction with the -h or -H options, the number of inodes is scaled by powers of 1000. In case the filesystem has no inodes then ‘-’ is displayed instead of the usage percentage. This option is now the default to conform to Version 3 of the Single UNIX Specification (“SUSv3”). Use -I to suppress this output. -k Use 1024 byte (1 Kibibyte) blocks rather than the default. This overrides the -P option and any BLOCKSIZE specification from the environment. -l Select locally-mounted file system for display. If used in combination with the -T type option, file system types will be added or excluded acccording to the parameters of that option. -m Use 1048576 byte (1 Mebibyte) blocks rather than the default. This overrides any BLOCKSIZE specification from the environment. -n Print out the previously obtained statistics from the file systems. This option should be used if it is possible that one or more file systems are in a state such that they will not be able to provide statistics without a long delay. When this option is specified, df will not request new statistics from the file systems, but will respond with the possibly stale statistics that were previously obtained. -P Explicitly use 512 byte blocks, overriding any BLOCKSIZE specification from the environment. This is the same as the -b option. The -g and -k options override this option. In compatibility mode, this also suppresses inode counts. -T type Select file systems to display. More than one type may be specified in a comma separated list. The list of file system types can be prefixed with “no” to specify the file system types for which action should not be taken. If used in combination with the -l option, the parameters of this option will modify the list of locally-mounted file systems selected by the -l option. For example, the df command: df -T nonfs,mfs lists all file systems except those of type NFS and MFS. The lsvfs(1) command can be used to find out the types of file systems that are available on the system. -t If used with no arguments, this option is a no-op (macOS already prints the total allocated-space figures). If used with an argument, it acts like -T, but this usage is deprecated and should not be relied upon. -Y Include file system type. -, (Comma) Print sizes grouped and separated by thousands using the non-monetary separator returned by localeconv(3), typically a comma or period. If no locale is set, or the locale does not have a non-monetary separator, this option has no effect. ENVIRONMENT BLOCKSIZE Specifies the units in which to report block counts. This uses getbsize(3), which allows units of bytes or numbers scaled with the letters k (for multiples of 1024 bytes), m (for multiples of 1048576 bytes) or g (for gibibytes). The allowed range is 512 bytes to 1 GB. If the value is outside, it will be set to the appropriate limit.
df – display free disk space
df [--libxo] [-b | -g | -H | -h | -k | -m | -P] [-acIilntY] [-,] [-T type] [file | filesystem ...] LEGACY SYNOPSIS df [--libxo] [-b | -g | -H | -h | -k | -m | -P] [-acIilnY] [-,] [-T type] [-t type] [file | filesystem ...]
null
Show human readable free disk space for all mount points including file system type: $ df -ahY Filesystem Type Size Used Avail Capacity iused ifree %iused Mounted on /dev/disk1s5s1 apfs 465Gi 15Gi 266Gi 6% 533k 2.8G 0% / devfs devfs 194Ki 194Ki 0Bi 100% 672 0 100% /dev /dev/disk1s2 apfs 465Gi 3.4Gi 266Gi 2% 1.6k 2.8G 0% /System/Volumes/Preboot /dev/disk1s4 apfs 465Gi 3.0Gi 266Gi 2% 3 2.8G 0% /System/Volumes/VM /dev/disk1s6 apfs 465Gi 11Mi 266Gi 1% 33 2.8G 0% /System/Volumes/Update /dev/disk1s1 apfs 465Gi 177Gi 266Gi 40% 3.9M 2.8G 0% /System/Volumes/Data The filesystems on this machine are virtual volumes on a single partition. Therefore, the size and space available is the same for all filesystems even though the space in use is different. The capacity column shows the amount of space used by each filesystem as a percentage of the sum of space used and space available. Show previously collected data, excluding inode information, except for the devfs file system. Note that the “no” prefix affects all the file systems in the list and the -t option can be specified only once: $ df -l -I -n -t nodevfs Filesystem 1K-blocks Used Available Capacity Mounted on /dev/disk1s5s1 487196712 15300072 278432984 6% / /dev/disk1s2 487196712 3604640 278430312 2% /System/Volumes/Preboot /dev/disk1s4 487196712 3145748 278430312 2% /System/Volumes/VM /dev/disk1s6 487196712 11576 278430312 1% /System/Volumes/Update /dev/disk1s1 487196712 185371244 278432984 40% /System/Volumes/Data Show human readable information for the file system containing the file /etc/rc.common: $ df -h /etc/rc.common Filesystem Size Used Avail Capacity iused ifree %iused Mounted on /dev/disk1s1 465Gi 177Gi 266Gi 40% 3.9M 2.8G 0% /System/Volumes/Data Same as above but specifying some file system: $ df -h /dev/disk1s1 Filesystem Size Used Avail Capacity iused ifree %iused Mounted on /dev/disk1s1 465Gi 177Gi 266Gi 40% 3.9M 2.8G 0% /System/Volumes/Data LEGACY DESCRIPTION The "capacity" percentage is normally rounded up to the next higher integer. In legacy mode, it is rounded down to the next lower integer. When the -P option and the -k option are used together, sizes are reported in 1024-byte blocks. The -t option is normally a no-op (macOS already prints the total allocated-space figures). In legacy mode, it is equivalent to -T. For more information about legacy mode, see compat(5). SEE ALSO lsvfs(1), quota(1), fstatfs(2), getfsstat(2), statfs(2), getbsize(3), getmntinfo(3), libxo(3), localeconv(3), xo_parse_args(3), compat(5), fstab(5), mount(8), pstat(8), quot(8), swapinfo(8) STANDARDS With the exception of most options, the df utility conforms to IEEE Std 1003.1-2004 (“POSIX.1”), which defines only the -k, -P and -t options. HISTORY A df command appeared in Version 1 AT&T UNIX. BUGS The -n flag is ignored if a file or file system is specified. Also, if a mount point is not accessible by the user, it is possible that the file system information could be stale. The -b and -P options are identical. The former comes from the BSD tradition, and the latter is required for IEEE Std 1003.1-2004 (“POSIX.1”) conformity. macOS 14.5 February 22, 2023 macOS 14.5
pwd
The pwd utility writes the absolute pathname of the current working directory to the standard output. Some shells may provide a builtin pwd command which is similar or identical to this utility. Consult the builtin(1) manual page. The options are as follows: -L Display the logical current working directory. -P Display the physical current working directory (all symbolic links resolved). If no options are specified, the -L option is assumed. ENVIRONMENT Environment variables used by pwd: PWD Logical current working directory. EXIT STATUS The pwd utility exits 0 on success, and >0 if an error occurs.
pwd – return working directory name
pwd [-L | -P]
null
Show current working directory with symbolic links resolved: $ /bin/pwd -P /usr/home/fernape Show the logical current directory. Then use file(1) to inspect the /home directory: $ /bin/pwd /home/fernape $ file /home /home: symbolic link to usr/home SEE ALSO builtin(1), cd(1), csh(1), realpath(1), sh(1), getcwd(3) STANDARDS The pwd utility conforms to IEEE Std 1003.1-2001 (“POSIX.1”). HISTORY The pwd command appeared in Version 5 AT&T UNIX. BUGS In csh(1) the command dirs is always faster because it is built into that shell. However, it can give a different answer in the rare case that the current directory or a containing directory was moved after the shell descended into it. The -L option does not work unless the PWD environment variable is exported by the shell. macOS 14.5 October 24, 2020 macOS 14.5
test
The test utility evaluates the expression and, if it evaluates to true, returns a zero (true) exit status; otherwise it returns 1 (false). If there is no expression, test also returns 1 (false). All operators and flags are separate arguments to the test utility. The following primaries are used to construct expression: -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 (regardless of type). -f file True if file exists and is a regular file. -g file True if file exists and its set group ID flag is set. -h file True if file exists and is a symbolic link. This operator is retained for compatibility with previous versions of this program. Do not rely on its existence; use -L instead. -k file True if file exists and its sticky bit is set. -n string True if the length of string is nonzero. -p file True if file is a named pipe (FIFO). -r file True if file exists and is readable. -s file True if file exists and has a size greater than zero. -t file_descriptor True if the file whose file descriptor number is file_descriptor is open and is associated with a terminal. -u file True if file exists and its set user ID flag is set. -w file True if file exists and is writable. True indicates only that the write flag is on. The file is not writable on a read-only file system even if this test indicates true. -x file True if file exists and is executable. True indicates only that the execute flag is on. If file is a directory, true indicates that file can be searched. -z string True if the length of string is zero. -L file True if file exists and is a symbolic link. -O file True if file exists and its owner matches the effective user id of this process. -G file True if file exists and its group matches the effective group id of this process. -S file True if file exists and is a socket. 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 True if string is not the null string. s1 = s2 True if the strings s1 and s2 are identical. s1 != s2 True if the strings s1 and s2 are not identical. s1 < s2 True if string s1 comes before s2 based on the binary value of their characters. s1 > s2 True if string s1 comes after s2 based on the binary value of their characters. n1 -eq n2 True if the integers n1 and n2 are algebraically equal. n1 -ne n2 True if the integers n1 and n2 are not algebraically equal. n1 -gt n2 True if the integer n1 is algebraically greater than the integer n2. n1 -ge n2 True if the integer n1 is algebraically greater than or equal to the integer n2. n1 -lt n2 True if the integer n1 is algebraically less than the integer n2. n1 -le n2 True if the integer n1 is algebraically less than or equal to the integer n2. If file is a symbolic link, test will fully dereference it and then evaluate the expression against the file referenced, except for the -h and -L primaries. These primaries can be combined with the following operators: ! expression True if expression is false. expression1 -a expression2 True if both expression1 and expression2 are true. expression1 -o expression2 True if either expression1 or expression2 are true. ( expression ) True if expression is true. The -a operator has higher precedence than the -o operator. Some shells may provide a builtin test command which is similar or identical to this utility. Consult the builtin(1) manual page. GRAMMAR AMBIGUITY The test grammar is inherently ambiguous. In order to assure a degree of consistency, the cases described in the IEEE Std 1003.2 (“POSIX.2”), section D11.2/4.62.4, standard are evaluated consistently according to the rules specified in the standards document. All other cases are subject to the ambiguity in the command semantics. In particular, only expressions containing -a, -o, ( or ) can be ambiguous. EXIT STATUS The test utility exits with one of the following values: 0 expression evaluated to true. 1 expression evaluated to false or expression was missing. >1 An error occurred.
test, [ – condition evaluation utility
test expression [ expression ]
null
Implement test FILE1 -nt FILE2 using only POSIX functionality: test -n "$(find -L -- FILE1 -prune -newer FILE2 2>/dev/null)" This can be modified using non-standard find(1) primaries like -newerca to compare other timestamps. COMPATIBILITY For compatibility with some other implementations, the = primary can be substituted with == with the same meaning. SEE ALSO builtin(1), expr(1), find(1), sh(1), stat(1), symlink(7) STANDARDS The test utility implements a superset of the IEEE Std 1003.2 (“POSIX.2”) specification. The primaries <, ==, >, -ef, -nt, -ot, -G, and -O are extensions. HISTORY A test utility appeared in Version 7 AT&T UNIX. BUGS Both sides are always evaluated in -a and -o. For instance, the writable status of file will be tested by the following command even though the former expression indicated false, which results in a gratuitous access to the file system: [ -z abc -a -w file ] To avoid this, write [ -z abc ] && [ -w file ] macOS 14.5 October 5, 2016 macOS 14.5
csh
tcsh is an enhanced but completely compatible version of the Berkeley UNIX C shell, csh(1). It is a command language interpreter usable both as an interactive login shell and a shell script command processor. It includes a command-line editor (see The command-line editor), programmable word completion (see Completion and listing), spelling correction (see Spelling correction), a history mechanism (see History substitution), job control (see Jobs) and a C-like syntax. The NEW FEATURES section describes major enhancements of tcsh over csh(1). Throughout this manual, features of tcsh not found in most csh(1) implementations (specifically, the 4.4BSD csh) are labeled with `(+)', and features which are present in csh(1) but not usually documented are labeled with `(u)'. Argument list processing If the first argument (argument 0) to the shell is `-' then it is a login shell. A login shell can be also specified by invoking the shell with the -l flag as the only argument. The rest of the flag arguments are interpreted as follows: -b Forces a ``break'' from option processing, causing any further shell arguments to be treated as non-option arguments. The remaining arguments will not be interpreted as shell options. This may be used to pass options to a shell script without confusion or possible subterfuge. The shell will not run a set-user ID script without this option. -c Commands are read from the following argument (which must be present, and must be a single argument), stored in the command shell variable for reference, and executed. Any remaining arguments are placed in the argv shell variable. -d The shell loads the directory stack from ~/.cshdirs as described under Startup and shutdown, whether or not it is a login shell. (+) -Dname[=value] Sets the environment variable name to value. (Domain/OS only) (+) -e The shell exits if any invoked command terminates abnormally or yields a non-zero exit status. -f The shell does not load any resource or startup files, or perform any command hashing, and thus starts faster. -F The shell uses fork(2) instead of vfork(2) to spawn processes. This is now the default and this option is ignored. (+) -i The shell is interactive and prompts for its top-level input, even if it appears to not be a terminal. Shells are interactive without this option if their inputs and outputs are terminals. -l The shell is a login shell. Applicable only if -l is the only flag specified. -m The shell loads ~/.tcshrc even if it does not belong to the effective user. Newer versions of su(1) can pass -m to the shell. (+) -n The shell parses commands but does not execute them. This aids in debugging shell scripts. -q The shell accepts SIGQUIT (see Signal handling) and behaves when it is used under a debugger. Job control is disabled. (u) -s Command input is taken from the standard input. -t The shell reads and executes a single line of input. A `\' may be used to escape the newline at the end of this line and continue onto another line. -v Sets the verbose shell variable, so that command input is echoed after history substitution. -x Sets the echo shell variable, so that commands are echoed immediately before execution. -V Sets the verbose shell variable even before executing ~/.tcshrc. -X Is to -x as -V is to -v. --help Print a help message on the standard output and exit. (+) --version Print the version/platform/compilation options on the standard output and exit. This information is also contained in the version shell variable. (+) After processing of flag arguments, if arguments remain but none of the -c, -i, -s, or -t options were given, the first argument is taken as the name of a file of commands, or ``script'', to be executed. The shell opens this file and saves its name for possible resubstitution by `$0'. Because many systems use either the standard version 6 or version 7 shells whose shell scripts are not compatible with this shell, the shell uses such a `standard' shell to execute a script whose first character is not a `#', i.e., that does not start with a comment. Remaining arguments are placed in the argv shell variable. Startup and shutdown A login shell begins by executing commands from the system files /etc/csh.cshrc and /etc/csh.login. It then executes commands from files in the user's home directory: first ~/.tcshrc (+) or, if ~/.tcshrc is not found, ~/.cshrc, then the contents of ~/.history (or the value of the histfile shell variable) are loaded into memory, then ~/.login, and finally ~/.cshdirs (or the value of the dirsfile shell variable) (+). The shell may read /etc/csh.login before instead of after /etc/csh.cshrc, and ~/.login before instead of after ~/.tcshrc or ~/.cshrc and ~/.history, if so compiled; see the version shell variable. (+) Non-login shells read only /etc/csh.cshrc and ~/.tcshrc or ~/.cshrc on startup. For examples of startup files, please consult http://tcshrc.sourceforge.net. Commands like stty(1) and tset(1), which need be run only once per login, usually go in one's ~/.login file. Users who need to use the same set of files with both csh(1) and tcsh can have only a ~/.cshrc which checks for the existence of the tcsh shell variable (q.v.) before using tcsh-specific commands, or can have both a ~/.cshrc and a ~/.tcshrc which sources (see the builtin command) ~/.cshrc. The rest of this manual uses `~/.tcshrc' to mean `~/.tcshrc or, if ~/.tcshrc is not found, ~/.cshrc'. In the normal case, the shell begins reading commands from the terminal, prompting with `> '. (Processing of arguments and the use of the shell to process files containing command scripts are described later.) The shell repeatedly reads a line of command input, breaks it into words, places it on the command history list, parses it and executes each command in the line. One can log out by typing `^D' on an empty line, `logout' or `login' or via the shell's autologout mechanism (see the autologout shell variable). When a login shell terminates it sets the logout shell variable to `normal' or `automatic' as appropriate, then executes commands from the files /etc/csh.logout and ~/.logout. The shell may drop DTR on logout if so compiled; see the version shell variable. The names of the system login and logout files vary from system to system for compatibility with different csh(1) variants; see FILES. Editing We first describe The command-line editor. The Completion and listing and Spelling correction sections describe two sets of functionality that are implemented as editor commands but which deserve their own treatment. Finally, Editor commands lists and describes the editor commands specific to the shell and their default bindings. The command-line editor (+) Command-line input can be edited using key sequences much like those used in emacs(1) or vi(1). The editor is active only when the edit shell variable is set, which it is by default in interactive shells. The bindkey builtin can display and change key bindings. emacs(1)-style key bindings are used by default (unless the shell was compiled otherwise; see the version shell variable), but bindkey can change the key bindings to vi(1)-style bindings en masse. The shell always binds the arrow keys (as defined in the TERMCAP environment variable) to down down-history up up-history left backward-char right forward-char unless doing so would alter another single-character binding. One can set the arrow key escape sequences to the empty string with settc to prevent these bindings. The ANSI/VT100 sequences for arrow keys are always bound. Other key bindings are, for the most part, what emacs(1) and vi(1) users would expect and can easily be displayed by bindkey, so there is no need to list them here. Likewise, bindkey can list the editor commands with a short description of each. Certain key bindings have different behavior depending if emacs(1) or vi(1) style bindings are being used; see vimode for more information. Note that editor commands do not have the same notion of a ``word'' as does the shell. The editor delimits words with any non-alphanumeric characters not in the shell variable wordchars, while the shell recognizes only whitespace and some of the characters with special meanings to it, listed under Lexical structure. Completion and listing (+) The shell is often able to complete words when given a unique abbreviation. Type part of a word (for example `ls /usr/lost') and hit the tab key to run the complete-word editor command. The shell completes the filename `/usr/lost' to `/usr/lost+found/', replacing the incomplete word with the complete word in the input buffer. (Note the terminal `/'; completion adds a `/' to the end of completed directories and a space to the end of other completed words, to speed typing and provide a visual indicator of successful completion. The addsuffix shell variable can be unset to prevent this.) If no match is found (perhaps `/usr/lost+found' doesn't exist), the terminal bell rings. If the word is already complete (perhaps there is a `/usr/lost' on your system, or perhaps you were thinking too far ahead and typed the whole thing) a `/' or space is added to the end if it isn't already there. Completion works anywhere in the line, not at just the end; completed text pushes the rest of the line to the right. Completion in the middle of a word often results in leftover characters to the right of the cursor that need to be deleted. Commands and variables can be completed in much the same way. For example, typing `em[tab]' would complete `em' to `emacs' if emacs were the only command on your system beginning with `em'. Completion can find a command in any directory in path or if given a full pathname. Typing `echo $ar[tab]' would complete `$ar' to `$argv' if no other variable began with `ar'. The shell parses the input buffer to determine whether the word you want to complete should be completed as a filename, command or variable. The first word in the buffer and the first word following `;', `|', `|&', `&&' or `||' is considered to be a command. A word beginning with `$' is considered to be a variable. Anything else is a filename. An empty line is `completed' as a filename. You can list the possible completions of a word at any time by typing `^D' to run the delete-char-or-list-or-eof editor command. The shell lists the possible completions using the ls-F builtin (q.v.) and reprints the prompt and unfinished command line, for example: > ls /usr/l[^D] lbin/ lib/ local/ lost+found/ > ls /usr/l If the autolist shell variable is set, the shell lists the remaining choices (if any) whenever completion fails: > set autolist > nm /usr/lib/libt[tab] libtermcap.a@ libtermlib.a@ > nm /usr/lib/libterm If autolist is set to `ambiguous', choices are listed only when completion fails and adds no new characters to the word being completed. A filename to be completed can contain variables, your own or others' home directories abbreviated with `~' (see Filename substitution) and directory stack entries abbreviated with `=' (see Directory stack substitution). For example, > ls ~k[^D] kahn kas kellogg > ls ~ke[tab] > ls ~kellogg/ or > set local = /usr/local > ls $lo[tab] > ls $local/[^D] bin/ etc/ lib/ man/ src/ > ls $local/ Note that variables can also be expanded explicitly with the expand- variables editor command. delete-char-or-list-or-eof lists at only the end of the line; in the middle of a line it deletes the character under the cursor and on an empty line it logs one out or, if ignoreeof is set, does nothing. `M-^D', bound to the editor command list-choices, lists completion possibilities anywhere on a line, and list-choices (or any one of the related editor commands that do or don't delete, list and/or log out, listed under delete-char-or-list-or-eof) can be bound to `^D' with the bindkey builtin command if so desired. The complete-word-fwd and complete-word-back editor commands (not bound to any keys by default) can be used to cycle up and down through the list of possible completions, replacing the current word with the next or previous word in the list. The shell variable fignore can be set to a list of suffixes to be ignored by completion. Consider the following: > ls Makefile condiments.h~ main.o side.c README main.c meal side.o condiments.h main.c~ > set fignore = (.o \~) > emacs ma[^D] main.c main.c~ main.o > emacs ma[tab] > emacs main.c `main.c~' and `main.o' are ignored by completion (but not listing), because they end in suffixes in fignore. Note that a `\' was needed in front of `~' to prevent it from being expanded to home as described under Filename substitution. fignore is ignored if only one completion is possible. If the complete shell variable is set to `enhance', completion 1) ignores case and 2) considers periods, hyphens and underscores (`.', `-' and `_') to be word separators and hyphens and underscores to be equivalent. If you had the following files comp.lang.c comp.lang.perl comp.std.c++ comp.lang.c++ comp.std.c and typed `mail -f c.l.c[tab]', it would be completed to `mail -f comp.lang.c', and ^D would list `comp.lang.c' and `comp.lang.c++'. `mail -f c..c++[^D]' would list `comp.lang.c++' and `comp.std.c++'. Typing `rm a--file[^D]' in the following directory A_silly_file a-hyphenated-file another_silly_file would list all three files, because case is ignored and hyphens and underscores are equivalent. Periods, however, are not equivalent to hyphens or underscores. If the complete shell variable is set to `Enhance', completion ignores case and differences between a hyphen and an underscore word separator only when the user types a lowercase character or a hyphen. Entering an uppercase character or an underscore will not match the corresponding lowercase character or hyphen word separator. Typing `rm a--file[^D]' in the directory of the previous example would still list all three files, but typing `rm A--file' would match only `A_silly_file' and typing `rm a__file[^D]' would match just `A_silly_file' and `another_silly_file' because the user explicitly used an uppercase or an underscore character. Completion and listing are affected by several other shell variables: recexact can be set to complete on the shortest possible unique match, even if more typing might result in a longer match: > ls fodder foo food foonly > set recexact > rm fo[tab] just beeps, because `fo' could expand to `fod' or `foo', but if we type another `o', > rm foo[tab] > rm foo the completion completes on `foo', even though `food' and `foonly' also match. autoexpand can be set to run the expand-history editor command before each completion attempt, autocorrect can be set to spelling- correct the word to be completed (see Spelling correction) before each completion attempt and correct can be set to complete commands automatically after one hits `return'. matchbeep can be set to make completion beep or not beep in a variety of situations, and nobeep can be set to never beep at all. nostat can be set to a list of directories and/or patterns that match directories to prevent the completion mechanism from stat(2)ing those directories. listmax and listmaxrows can be set to limit the number of items and rows (respectively) that are listed without asking first. recognize_only_executables can be set to make the shell list only executables when listing commands, but it is quite slow. Finally, the complete builtin command can be used to tell the shell how to complete words other than filenames, commands and variables. Completion and listing do not work on glob-patterns (see Filename substitution), but the list-glob and expand-glob editor commands perform equivalent functions for glob-patterns. Spelling correction (+) The shell can sometimes correct the spelling of filenames, commands and variable names as well as completing and listing them. Individual words can be spelling-corrected with the spell-word editor command (usually bound to M-s and M-S) and the entire input buffer with spell-line (usually bound to M-$). The correct shell variable can be set to `cmd' to correct the command name or `all' to correct the entire line each time return is typed, and autocorrect can be set to correct the word to be completed before each completion attempt. When spelling correction is invoked in any of these ways and the shell thinks that any part of the command line is misspelled, it prompts with the corrected line: > set correct = cmd > lz /usr/bin CORRECT>ls /usr/bin (y|n|e|a)? One can answer `y' or space to execute the corrected line, `e' to leave the uncorrected command in the input buffer, `a' to abort the command as if `^C' had been hit, and anything else to execute the original line unchanged. Spelling correction recognizes user-defined completions (see the complete builtin command). If an input word in a position for which a completion is defined resembles a word in the completion list, spelling correction registers a misspelling and suggests the latter word as a correction. However, if the input word does not match any of the possible completions for that position, spelling correction does not register a misspelling. Like completion, spelling correction works anywhere in the line, pushing the rest of the line to the right and possibly leaving extra characters to the right of the cursor. Editor commands (+) `bindkey' lists key bindings and `bindkey -l' lists and briefly describes editor commands. Only new or especially interesting editor commands are described here. See emacs(1) and vi(1) for descriptions of each editor's key bindings. The character or characters to which each command is bound by default is given in parentheses. `^character' means a control character and `M-character' a meta character, typed as escape-character on terminals without a meta key. Case counts, but commands that are bound to letters by default are bound to both lower- and uppercase letters for convenience. backward-char (^B, left) Move back a character. Cursor behavior modified by vimode. backward-delete-word (M-^H, M-^?) Cut from beginning of current word to cursor - saved in cut buffer. Word boundary behavior modified by vimode. backward-word (M-b, M-B) Move to beginning of current word. Word boundary and cursor behavior modified by vimode. beginning-of-line (^A, home) Move to beginning of line. Cursor behavior modified by vimode. capitalize-word (M-c, M-C) Capitalize the characters from cursor to end of current word. Word boundary behavior modified by vimode. complete-word (tab) Completes a word as described under Completion and listing. complete-word-back (not bound) Like complete-word-fwd, but steps up from the end of the list. complete-word-fwd (not bound) Replaces the current word with the first word in the list of possible completions. May be repeated to step down through the list. At the end of the list, beeps and reverts to the incomplete word. complete-word-raw (^X-tab) Like complete-word, but ignores user-defined completions. copy-prev-word (M-^_) Copies the previous word in the current line into the input buffer. See also insert-last-word. Word boundary behavior modified by vimode. dabbrev-expand (M-/) Expands the current word to the most recent preceding one for which the current is a leading substring, wrapping around the history list (once) if necessary. Repeating dabbrev-expand without any intervening typing changes to the next previous word etc., skipping identical matches much like history-search- backward does. delete-char (not bound) Deletes the character under the cursor. See also delete-char- or-list-or-eof. Cursor behavior modified by vimode. delete-char-or-eof (not bound) Does delete-char if there is a character under the cursor or end-of-file on an empty line. See also delete-char-or-list-or- eof. Cursor behavior modified by vimode. delete-char-or-list (not bound) Does delete-char if there is a character under the cursor or list-choices at the end of the line. See also delete-char-or- list-or-eof. delete-char-or-list-or-eof (^D) Does delete-char if there is a character under the cursor, list-choices at the end of the line or end-of-file on an empty line. See also those three commands, each of which does only a single action, and delete-char-or-eof, delete-char-or-list and list-or-eof, each of which does a different two out of the three. delete-word (M-d, M-D) Cut from cursor to end of current word - save in cut buffer. Word boundary behavior modified by vimode. down-history (down-arrow, ^N) Like up-history, but steps down, stopping at the original input line. downcase-word (M-l, M-L) Lowercase the characters from cursor to end of current word. Word boundary behavior modified by vimode. end-of-file (not bound) Signals an end of file, causing the shell to exit unless the ignoreeof shell variable (q.v.) is set to prevent this. See also delete-char-or-list-or-eof. end-of-line (^E, end) Move cursor to end of line. Cursor behavior modified by vimode. expand-history (M-space) Expands history substitutions in the current word. See History substitution. See also magic-space, toggle-literal-history and the autoexpand shell variable. expand-glob (^X-*) Expands the glob-pattern to the left of the cursor. See Filename substitution. expand-line (not bound) Like expand-history, but expands history substitutions in each word in the input buffer. expand-variables (^X-$) Expands the variable to the left of the cursor. See Variable substitution. forward-char (^F, right) Move forward one character. Cursor behavior modified by vimode. forward-word (M-f, M-F) Move forward to end of current word. Word boundary and cursor behavior modified by vimode. history-search-backward (M-p, M-P) Searches backwards through the history list for a command beginning with the current contents of the input buffer up to the cursor and copies it into the input buffer. The search string may be a glob-pattern (see Filename substitution) containing `*', `?', `[]' or `{}'. up-history and down-history will proceed from the appropriate point in the history list. Emacs mode only. See also history-search-forward and i-search- back. history-search-forward (M-n, M-N) Like history-search-backward, but searches forward. i-search-back (not bound) Searches backward like history-search-backward, copies the first match into the input buffer with the cursor positioned at the end of the pattern, and prompts with `bck: ' and the first match. Additional characters may be typed to extend the search, i-search-back may be typed to continue searching with the same pattern, wrapping around the history list if necessary, (i-search-back must be bound to a single character for this to work) or one of the following special characters may be typed: ^W Appends the rest of the word under the cursor to the search pattern. delete (or any character bound to backward-delete-char) Undoes the effect of the last character typed and deletes a character from the search pattern if appropriate. ^G If the previous search was successful, aborts the entire search. If not, goes back to the last successful search. escape Ends the search, leaving the current line in the input buffer. Any other character not bound to self-insert-command terminates the search, leaving the current line in the input buffer, and is then interpreted as normal input. In particular, a carriage return causes the current line to be executed. See also i- search-fwd and history-search-backward. Word boundary behavior modified by vimode. i-search-fwd (not bound) Like i-search-back, but searches forward. Word boundary behavior modified by vimode. insert-last-word (M-_) Inserts the last word of the previous input line (`!$') into the input buffer. See also copy-prev-word. list-choices (M-^D) Lists completion possibilities as described under Completion and listing. See also delete-char-or-list-or-eof and list- choices-raw. list-choices-raw (^X-^D) Like list-choices, but ignores user-defined completions. list-glob (^X-g, ^X-G) Lists (via the ls-F builtin) matches to the glob-pattern (see Filename substitution) to the left of the cursor. list-or-eof (not bound) Does list-choices or end-of-file on an empty line. See also delete-char-or-list-or-eof. magic-space (not bound) Expands history substitutions in the current line, like expand- history, and inserts a space. magic-space is designed to be bound to the space bar, but is not bound by default. normalize-command (^X-?) Searches for the current word in PATH and, if it is found, replaces it with the full path to the executable. Special characters are quoted. Aliases are expanded and quoted but commands within aliases are not. This command is useful with commands that take commands as arguments, e.g., `dbx' and `sh -x'. normalize-path (^X-n, ^X-N) Expands the current word as described under the `expand' setting of the symlinks shell variable. overwrite-mode (unbound) Toggles between input and overwrite modes. run-fg-editor (M-^Z) Saves the current input line and looks for a stopped job where the file name portion of its first word is found in the editors shell variable. If editors is not set, then the file name portion of the EDITOR environment variable (`ed' if unset) and the VISUAL environment variable (`vi' if unset) will be used. If such a job is found, it is restarted as if `fg %job' had been typed. This is used to toggle back and forth between an editor and the shell easily. Some people bind this command to `^Z' so they can do this even more easily. run-help (M-h, M-H) Searches for documentation on the current command, using the same notion of `current command' as the completion routines, and prints it. There is no way to use a pager; run-help is designed for short help files. If the special alias helpcommand is defined, it is run with the command name as a sole argument. Else, documentation should be in a file named command.help, command.1, command.6, command.8 or command, which should be in one of the directories listed in the HPATH environment variable. If there is more than one help file only the first is printed. self-insert-command (text characters) In insert mode (the default), inserts the typed character into the input line after the character under the cursor. In overwrite mode, replaces the character under the cursor with the typed character. The input mode is normally preserved between lines, but the inputmode shell variable can be set to `insert' or `overwrite' to put the editor in that mode at the beginning of each line. See also overwrite-mode. sequence-lead-in (arrow prefix, meta prefix, ^X) Indicates that the following characters are part of a multi-key sequence. Binding a command to a multi-key sequence really creates two bindings: the first character to sequence-lead-in and the whole sequence to the command. All sequences beginning with a character bound to sequence-lead-in are effectively bound to undefined-key unless bound to another command. spell-line (M-$) Attempts to correct the spelling of each word in the input buffer, like spell-word, but ignores words whose first character is one of `-', `!', `^' or `%', or which contain `\', `*' or `?', to avoid problems with switches, substitutions and the like. See Spelling correction. spell-word (M-s, M-S) Attempts to correct the spelling of the current word as described under Spelling correction. Checks each component of a word which appears to be a pathname. toggle-literal-history (M-r, M-R) Expands or `unexpands' history substitutions in the input buffer. See also expand-history and the autoexpand shell variable. undefined-key (any unbound key) Beeps. up-history (up-arrow, ^P) Copies the previous entry in the history list into the input buffer. If histlit is set, uses the literal form of the entry. May be repeated to step up through the history list, stopping at the top. upcase-word (M-u, M-U) Uppercase the characters from cursor to end of current word. Word boundary behavior modified by vimode. vi-beginning-of-next-word (not bound) Vi goto the beginning of next word. Word boundary and cursor behavior modified by vimode. vi-eword (not bound) Vi move to the end of the current word. Word boundary behavior modified by vimode. vi-search-back (?) Prompts with `?' for a search string (which may be a glob- pattern, as with history-search-backward), searches for it and copies it into the input buffer. The bell rings if no match is found. Hitting return ends the search and leaves the last match in the input buffer. Hitting escape ends the search and executes the match. vi mode only. vi-search-fwd (/) Like vi-search-back, but searches forward. which-command (M-?) Does a which (see the description of the builtin command) on the first word of the input buffer. yank-pop (M-y) When executed immediately after a yank or another yank-pop, replaces the yanked string with the next previous string from the killring. This also has the effect of rotating the killring, such that this string will be considered the most recently killed by a later yank command. Repeating yank-pop will cycle through the killring any number of times. Lexical structure The shell splits input lines into words at blanks and tabs. The special characters `&', `|', `;', `<', `>', `(', and `)' and the doubled characters `&&', `||', `<<' and `>>' are always separate words, whether or not they are surrounded by whitespace. When the shell's input is not a terminal, the character `#' is taken to begin a comment. Each `#' and the rest of the input line on which it appears is discarded before further parsing. A special character (including a blank or tab) may be prevented from having its special meaning, and possibly made part of another word, by preceding it with a backslash (`\') or enclosing it in single (`''), double (`"') or backward (``') quotes. When not otherwise quoted a newline preceded by a `\' is equivalent to a blank, but inside quotes this sequence results in a newline. Furthermore, all Substitutions (see below) except History substitution can be prevented by enclosing the strings (or parts of strings) in which they appear with single quotes or by quoting the crucial character(s) (e.g., `$' or ``' for Variable substitution or Command substitution respectively) with `\'. (Alias substitution is no exception: quoting in any way any character of a word for which an alias has been defined prevents substitution of the alias. The usual way of quoting an alias is to precede it with a backslash.) History substitution is prevented by backslashes but not by single quotes. Strings quoted with double or backward quotes undergo Variable substitution and Command substitution, but other substitutions are prevented. Text inside single or double quotes becomes a single word (or part of one). Metacharacters in these strings, including blanks and tabs, do not form separate words. Only in one special case (see Command substitution below) can a double-quoted string yield parts of more than one word; single-quoted strings never do. Backward quotes are special: they signal Command substitution (q.v.), which may result in more than one word. Quoting complex strings, particularly strings which themselves contain quoting characters, can be confusing. Remember that quotes need not be used as they are in human writing! It may be easier to quote not an entire string, but only those parts of the string which need quoting, using different types of quoting to do so if appropriate. The backslash_quote shell variable (q.v.) can be set to make backslashes always quote `\', `'', and `"'. (+) This may make complex quoting tasks easier, but it can cause syntax errors in csh(1) scripts. Substitutions We now describe the various transformations the shell performs on the input in the order in which they occur. We note in passing the data structures involved and the commands and variables which affect them. Remember that substitutions can be prevented by quoting as described under Lexical structure. History substitution Each command, or ``event'', input from the terminal is saved in the history list. The previous command is always saved, and the history shell variable can be set to a number to save that many commands. The histdup shell variable can be set to not save duplicate events or consecutive duplicate events. Saved commands are numbered sequentially from 1 and stamped with the time. It is not usually necessary to use event numbers, but the current event number can be made part of the prompt by placing an `!' in the prompt shell variable. The shell actually saves history in expanded and literal (unexpanded) forms. If the histlit shell variable is set, commands that display and store history use the literal form. The history builtin command can print, store in a file, restore and clear the history list at any time, and the savehist and histfile shell variables can be set to store the history list automatically on logout and restore it on login. History substitutions introduce words from the history list into the input stream, making it easy to repeat commands, repeat arguments of a previous command in the current command, or fix spelling mistakes in the previous command with little typing and a high degree of confidence. History substitutions begin with the character `!'. They may begin anywhere in the input stream, but they do not nest. The `!' may be preceded by a `\' to prevent its special meaning; for convenience, a `!' is passed unchanged when it is followed by a blank, tab, newline, `=' or `('. History substitutions also occur when an input line begins with `^'. This special abbreviation will be described later. The characters used to signal history substitution (`!' and `^') can be changed by setting the histchars shell variable. Any input line which contains a history substitution is printed before it is executed. A history substitution may have an ``event specification'', which indicates the event from which words are to be taken, a ``word designator'', which selects particular words from the chosen event, and/or a ``modifier'', which manipulates the selected words. An event specification can be n A number, referring to a particular event -n An offset, referring to the event n before the current event # The current event. This should be used carefully in csh(1), where there is no check for recursion. tcsh allows 10 levels of recursion. (+) ! The previous event (equivalent to `-1') s The most recent event whose first word begins with the string s ?s? The most recent event which contains the string s. The second `?' can be omitted if it is immediately followed by a newline. For example, consider this bit of someone's history list: 9 8:30 nroff -man wumpus.man 10 8:31 cp wumpus.man wumpus.man.old 11 8:36 vi wumpus.man 12 8:37 diff wumpus.man.old wumpus.man The commands are shown with their event numbers and time stamps. The current event, which we haven't typed in yet, is event 13. `!11' and `!-2' refer to event 11. `!!' refers to the previous event, 12. `!!' can be abbreviated `!' if it is followed by `:' (`:' is described below). `!n' refers to event 9, which begins with `n'. `!?old?' also refers to event 12, which contains `old'. Without word designators or modifiers history references simply expand to the entire event, so we might type `!cp' to redo the copy command or `!!|more' if the `diff' output scrolled off the top of the screen. History references may be insulated from the surrounding text with braces if necessary. For example, `!vdoc' would look for a command beginning with `vdoc', and, in this example, not find one, but `!{v}doc' would expand unambiguously to `vi wumpus.mandoc'. Even in braces, history substitutions do not nest. (+) While csh(1) expands, for example, `!3d' to event 3 with the letter `d' appended to it, tcsh expands it to the last event beginning with `3d'; only completely numeric arguments are treated as event numbers. This makes it possible to recall events beginning with numbers. To expand `!3d' as in csh(1) say `!{3}d'. To select words from an event we can follow the event specification by a `:' and a designator for the desired words. The words of an input line are numbered from 0, the first (usually command) word being 0, the second word (first argument) being 1, etc. The basic word designators are: 0 The first (command) word n The nth argument ^ The first argument, equivalent to `1' $ The last argument % The word matched by an ?s? search x-y A range of words -y Equivalent to `0-y' * Equivalent to `^-$', but returns nothing if the event contains only 1 word x* Equivalent to `x-$' x- Equivalent to `x*', but omitting the last word (`$') Selected words are inserted into the command line separated by single blanks. For example, the `diff' command in the previous example might have been typed as `diff !!:1.old !!:1' (using `:1' to select the first argument from the previous event) or `diff !-2:2 !-2:1' to select and swap the arguments from the `cp' command. If we didn't care about the order of the `diff' we might have said `diff !-2:1-2' or simply `diff !-2:*'. The `cp' command might have been written `cp wumpus.man !#:1.old', using `#' to refer to the current event. `!n:- hurkle.man' would reuse the first two words from the `nroff' command to say `nroff -man hurkle.man'. The `:' separating the event specification from the word designator can be omitted if the argument selector begins with a `^', `$', `*', `%' or `-'. For example, our `diff' command might have been `diff !!^.old !!^' or, equivalently, `diff !!$.old !!$'. However, if `!!' is abbreviated `!', an argument selector beginning with `-' will be interpreted as an event specification. A history reference may have a word designator but no event specification. It then references the previous command. Continuing our `diff' example, we could have said simply `diff !^.old !^' or, to get the arguments in the opposite order, just `diff !*'. The word or words in a history reference can be edited, or ``modified'', by following it with one or more modifiers, each preceded by a `:': h Remove a trailing pathname component, leaving the head. t Remove all leading pathname components, leaving the tail. r Remove a filename extension `.xxx', leaving the root name. e Remove all but the extension. u Uppercase the first lowercase letter. l Lowercase the first uppercase letter. s/l/r/ Substitute l for r. l is simply a string like r, not a regular expression as in the eponymous ed(1) command. Any character may be used as the delimiter in place of `/'; a `\' can be used to quote the delimiter inside l and r. The character `&' in the r is replaced by l; `\' also quotes `&'. If l is empty (``''), the l from a previous substitution or the s from a previous search or event number in event specification is used. The trailing delimiter may be omitted if it is immediately followed by a newline. & Repeat the previous substitution. g Apply the following modifier once to each word. a (+) Apply the following modifier as many times as possible to a single word. `a' and `g' can be used together to apply a modifier globally. With the `s' modifier, only the patterns contained in the original word are substituted, not patterns that contain any substitution result. p Print the new command line but do not execute it. q Quote the substituted words, preventing further substitutions. x Like q, but break into words at blanks, tabs and newlines. Modifiers are applied to only the first modifiable word (unless `g' is used). It is an error for no word to be modifiable. For example, the `diff' command might have been written as `diff wumpus.man.old !#^:r', using `:r' to remove `.old' from the first argument on the same line (`!#^'). We could say `echo hello out there', then `echo !*:u' to capitalize `hello', `echo !*:au' to say it out loud, or `echo !*:agu' to really shout. We might follow `mail -s "I forgot my password" rot' with `!:s/rot/root' to correct the spelling of `root' (but see Spelling correction for a different approach). There is a special abbreviation for substitutions. `^', when it is the first character on an input line, is equivalent to `!:s^'. Thus we might have said `^rot^root' to make the spelling correction in the previous example. This is the only history substitution which does not explicitly begin with `!'. (+) In csh as such, only one modifier may be applied to each history or variable expansion. In tcsh, more than one may be used, for example % mv wumpus.man /usr/man/man1/wumpus.1 % man !$:t:r man wumpus In csh, the result would be `wumpus.1:r'. A substitution followed by a colon may need to be insulated from it with braces: > mv a.out /usr/games/wumpus > setenv PATH !$:h:$PATH Bad ! modifier: $. > setenv PATH !{-2$:h}:$PATH setenv PATH /usr/games:/bin:/usr/bin:. The first attempt would succeed in csh but fails in tcsh, because tcsh expects another modifier after the second colon rather than `$'. Finally, history can be accessed through the editor as well as through the substitutions just described. The up- and down-history, history- search-backward and -forward, i-search-back and -fwd, vi-search-back and -fwd, copy-prev-word and insert-last-word editor commands search for events in the history list and copy them into the input buffer. The toggle-literal-history editor command switches between the expanded and literal forms of history lines in the input buffer. expand-history and expand-line expand history substitutions in the current word and in the entire input buffer respectively. Alias substitution The shell maintains a list of aliases which can be set, unset and printed by the alias and unalias commands. After a command line is parsed into simple commands (see Commands) the first word of each command, left-to-right, is checked to see if it has an alias. If so, the first word is replaced by the alias. If the alias contains a history reference, it undergoes History substitution (q.v.) as though the original command were the previous input line. If the alias does not contain a history reference, the argument list is left untouched. Thus if the alias for `ls' were `ls -l' the command `ls /usr' would become `ls -l /usr', the argument list here being undisturbed. If the alias for `lookup' were `grep !^ /etc/passwd' then `lookup bill' would become `grep bill /etc/passwd'. Aliases can be used to introduce parser metasyntax. For example, `alias print 'pr \!* | lpr'' defines a ``command'' (`print') which pr(1)s its arguments to the line printer. Alias substitution is repeated until the first word of the command has no alias. If an alias substitution does not change the first word (as in the previous example) it is flagged to prevent a loop. Other loops are detected and cause an error. Some aliases are referred to by the shell; see Special aliases. Variable substitution The shell maintains a list of variables, each of which has as value a list of zero or more words. The values of shell variables can be displayed and changed with the set and unset commands. The system maintains its own list of ``environment'' variables. These can be displayed and changed with printenv, setenv and unsetenv. (+) Variables may be made read-only with `set -r' (q.v.). Read-only variables may not be modified or unset; attempting to do so will cause an error. Once made read-only, a variable cannot be made writable, so `set -r' should be used with caution. Environment variables cannot be made read-only. Some variables are set by the shell or referred to by it. For instance, the argv variable is an image of the shell's argument list, and words of this variable's value are referred to in special ways. Some of the variables referred to by the shell are toggles; the shell does not care what their value is, only whether they are set or not. For instance, the verbose variable is a toggle which causes command input to be echoed. The -v command line option sets this variable. Special shell variables lists all variables which are referred to by the shell. Other operations treat variables numerically. The `@' command permits numeric calculations to be performed and the result assigned to a variable. Variable values are, however, always represented as (zero or more) strings. For the purposes of numeric operations, the null string is considered to be zero, and the second and subsequent words of multi- word values are ignored. After the input line is aliased and parsed, and before each command is executed, variable substitution is performed keyed by `$' characters. This expansion can be prevented by preceding the `$' with a `\' except within `"'s where it always occurs, and within `''s where it never occurs. Strings quoted by ``' are interpreted later (see Command substitution below) so `$' substitution does not occur there until later, if at all. A `$' is passed unchanged if followed by a blank, tab, or end-of-line. Input/output redirections are recognized before variable expansion, and are variable expanded separately. Otherwise, the command name and entire argument list are expanded together. It is thus possible for the first (command) word (to this point) to generate more than one word, the first of which becomes the command name, and the rest of which become arguments. Unless enclosed in `"' or given the `:q' modifier the results of variable substitution may eventually be command and filename substituted. Within `"', a variable whose value consists of multiple words expands to a (portion of a) single word, with the words of the variable's value separated by blanks. When the `:q' modifier is applied to a substitution the variable will expand to multiple words with each word separated by a blank and quoted to prevent later command or filename substitution. The following metasequences are provided for introducing variable values into the shell input. Except as noted, it is an error to reference a variable which is not set. $name ${name} Substitutes the words of the value of variable name, each separated by a blank. Braces insulate name from following characters which would otherwise be part of it. Shell variables have names consisting of letters and digits starting with a letter. The underscore character is considered a letter. If name is not a shell variable, but is set in the environment, then that value is returned (but some of the other forms given below are not available in this case). $name[selector] ${name[selector]} Substitutes only the selected words from the value of name. The selector is subjected to `$' substitution and may consist of a single number or two numbers separated by a `-'. The first word of a variable's value is numbered `1'. If the first number of a range is omitted it defaults to `1'. If the last member of a range is omitted it defaults to `$#name'. The selector `*' selects all words. It is not an error for a range to be empty if the second argument is omitted or in range. $0 Substitutes the name of the file from which command input is being read. An error occurs if the name is not known. $number ${number} Equivalent to `$argv[number]'. $* Equivalent to `$argv', which is equivalent to `$argv[*]'. The `:' modifiers described under History substitution, except for `:p', can be applied to the substitutions above. More than one may be used. (+) Braces may be needed to insulate a variable substitution from a literal colon just as with History substitution (q.v.); any modifiers must appear within the braces. The following substitutions can not be modified with `:' modifiers. $?name ${?name} Substitutes the string `1' if name is set, `0' if it is not. $?0 Substitutes `1' if the current input filename is known, `0' if it is not. Always `0' in interactive shells. $#name ${#name} Substitutes the number of words in name. $# Equivalent to `$#argv'. (+) $%name ${%name} Substitutes the number of characters in name. (+) $%number ${%number} Substitutes the number of characters in $argv[number]. (+) $? Equivalent to `$status'. (+) $$ Substitutes the (decimal) process number of the (parent) shell. $! Substitutes the (decimal) process number of the last background process started by this shell. (+) $_ Substitutes the command line of the last command executed. (+) $< Substitutes a line from the standard input, with no further interpretation thereafter. It can be used to read from the keyboard in a shell script. (+) While csh always quotes $<, as if it were equivalent to `$<:q', tcsh does not. Furthermore, when tcsh is waiting for a line to be typed the user may type an interrupt to interrupt the sequence into which the line is to be substituted, but csh does not allow this. The editor command expand-variables, normally bound to `^X-$', can be used to interactively expand individual variables. Command, filename and directory stack substitution The remaining substitutions are applied selectively to the arguments of builtin commands. This means that portions of expressions which are not evaluated are not subjected to these expansions. For commands which are not internal to the shell, the command name is substituted separately from the argument list. This occurs very late, after input- output redirection is performed, and in a child of the main shell. Command substitution Command substitution is indicated by a command enclosed in ``'. The output from such a command is broken into separate words at blanks, tabs and newlines, and null words are discarded. The output is variable and command substituted and put in place of the original string. Command substitutions inside double quotes (`"') retain blanks and tabs; only newlines force new words. The single final newline does not force a new word in any case. It is thus possible for a command substitution to yield only part of a word, even if the command outputs a complete line. By default, the shell since version 6.12 replaces all newline and carriage return characters in the command by spaces. If this is switched off by unsetting csubstnonl, newlines separate commands as usual. Filename substitution If a word contains any of the characters `*', `?', `[' or `{' or begins with the character `~' it is a candidate for filename substitution, also known as ``globbing''. This word is then regarded as a pattern (``glob-pattern''), and replaced with an alphabetically sorted list of file names which match the pattern. In matching filenames, the character `.' at the beginning of a filename or immediately following a `/', as well as the character `/' must be matched explicitly (unless either globdot or globstar or both are set(+)). The character `*' matches any string of characters, including the null string. The character `?' matches any single character. The sequence `[...]' matches any one of the characters enclosed. Within `[...]', a pair of characters separated by `-' matches any character lexically between the two. (+) Some glob-patterns can be negated: The sequence `[^...]' matches any single character not specified by the characters and/or ranges of characters in the braces. An entire glob-pattern can also be negated with `^': > echo * bang crash crunch ouch > echo ^cr* bang ouch Glob-patterns which do not use `?', `*', or `[]' or which use `{}' or `~' (below) are not negated correctly. The metanotation `a{b,c,d}e' is a shorthand for `abe ace ade'. Left- to-right order is preserved: `/usr/source/s1/{oldls,ls}.c' expands to `/usr/source/s1/oldls.c /usr/source/s1/ls.c'. The results of matches are sorted separately at a low level to preserve this order: `../{memo,*box}' might expand to `../memo ../box ../mbox'. (Note that `memo' was not sorted with the results of matching `*box'.) It is not an error when this construct expands to files which do not exist, but it is possible to get an error from a command to which the expanded list is passed. This construct may be nested. As a special case the words `{', `}' and `{}' are passed undisturbed. The character `~' at the beginning of a filename refers to home directories. Standing alone, i.e., `~', it expands to the invoker's home directory as reflected in the value of the home shell variable. When followed by a name consisting of letters, digits and `-' characters the shell searches for a user with that name and substitutes their home directory; thus `~ken' might expand to `/usr/ken' and `~ken/chmach' to `/usr/ken/chmach'. If the character `~' is followed by a character other than a letter or `/' or appears elsewhere than at the beginning of a word, it is left undisturbed. A command like `setenv MANPATH /usr/man:/usr/local/man:~/lib/man' does not, therefore, do home directory substitution as one might hope. It is an error for a glob-pattern containing `*', `?', `[' or `~', with or without `^', not to match any files. However, only one pattern in a list of glob-patterns must match a file (so that, e.g., `rm *.a *.c *.o' would fail only if there were no files in the current directory ending in `.a', `.c', or `.o'), and if the nonomatch shell variable is set a pattern (or list of patterns) which matches nothing is left unchanged rather than causing an error. The globstar shell variable can be set to allow `**' or `***' as a file glob pattern that matches any string of characters including `/', recursively traversing any existing sub-directories. For example, `ls **.c' will list all the .c files in the current directory tree. If used by itself, it will match zero or more sub-directories (e.g. `ls /usr/include/**/time.h' will list any file named `time.h' in the /usr/include directory tree; `ls /usr/include/**time.h' will match any file in the /usr/include directory tree ending in `time.h'; and `ls /usr/include/**time**.h' will match any .h file with `time' either in a subdirectory name or in the filename itself). To prevent problems with recursion, the `**' glob-pattern will not descend into a symbolic link containing a directory. To override this, use `***' (+) The noglob shell variable can be set to prevent filename substitution, and the expand-glob editor command, normally bound to `^X-*', can be used to interactively expand individual filename substitutions. Directory stack substitution (+) The directory stack is a list of directories, numbered from zero, used by the pushd, popd and dirs builtin commands (q.v.). dirs can print, store in a file, restore and clear the directory stack at any time, and the savedirs and dirsfile shell variables can be set to store the directory stack automatically on logout and restore it on login. The dirstack shell variable can be examined to see the directory stack and set to put arbitrary directories into the directory stack. The character `=' followed by one or more digits expands to an entry in the directory stack. The special case `=-' expands to the last directory in the stack. For example, > dirs -v 0 /usr/bin 1 /usr/spool/uucp 2 /usr/accts/sys > echo =1 /usr/spool/uucp > echo =0/calendar /usr/bin/calendar > echo =- /usr/accts/sys The noglob and nonomatch shell variables and the expand-glob editor command apply to directory stack as well as filename substitutions. Other substitutions (+) There are several more transformations involving filenames, not strictly related to the above but mentioned here for completeness. Any filename may be expanded to a full path when the symlinks variable (q.v.) is set to `expand'. Quoting prevents this expansion, and the normalize-path editor command does it on demand. The normalize-command editor command expands commands in PATH into full paths on demand. Finally, cd and pushd interpret `-' as the old working directory (equivalent to the shell variable owd). This is not a substitution at all, but an abbreviation recognized by only those commands. Nonetheless, it too can be prevented by quoting. Commands The next three sections describe how the shell executes commands and deals with their input and output. Simple commands, pipelines and sequences A simple command is a sequence of words, the first of which specifies the command to be executed. A series of simple commands joined by `|' characters forms a pipeline. The output of each command in a pipeline is connected to the input of the next. Simple commands and pipelines may be joined into sequences with `;', and will be executed sequentially. Commands and pipelines can also be joined into sequences with `||' or `&&', indicating, as in the C language, that the second is to be executed only if the first fails or succeeds respectively. A simple command, pipeline or sequence may be placed in parentheses, `()', to form a simple command, which may in turn be a component of a pipeline or sequence. A command, pipeline or sequence can be executed without waiting for it to terminate by following it with an `&'. Builtin and non-builtin command execution Builtin commands are executed within the shell. If any component of a pipeline except the last is a builtin command, the pipeline is executed in a subshell. Parenthesized commands are always executed in a subshell. (cd; pwd); pwd thus prints the home directory, leaving you where you were (printing this after the home directory), while cd; pwd leaves you in the home directory. Parenthesized commands are most often used to prevent cd from affecting the current shell. When a command to be executed is found not to be a builtin command the shell attempts to execute the command via execve(2). Each word in the variable path names a directory in which the shell will look for the command. If the shell is not given a -f option, the shell hashes the names in these directories into an internal table so that it will try an execve(2) in only a directory where there is a possibility that the command resides there. This greatly speeds command location when a large number of directories are present in the search path. This hashing mechanism is not used: 1. If hashing is turned explicitly off via unhash. 2. If the shell was given a -f argument. 3. For each directory component of path which does not begin with a `/'. 4. If the command contains a `/'. In the above four cases the shell concatenates each component of the path vector with the given command name to form a path name of a file which it then attempts to execute it. If execution is successful, the search stops. If the file has execute permissions but is not an executable to the system (i.e., it is neither an executable binary nor a script that specifies its interpreter), then it is assumed to be a file containing shell commands and a new shell is spawned to read it. The shell special alias may be set to specify an interpreter other than the shell itself. On systems which do not understand the `#!' script interpreter convention the shell may be compiled to emulate it; see the version shell variable. If so, the shell checks the first line of the file to see if it is of the form `#!interpreter arg ...'. If it is, the shell starts interpreter with the given args and feeds the file to it on standard input. Input/output The standard input and standard output of a command may be redirected with the following syntax: < name Open file name (which is first variable, command and filename expanded) as the standard input. << word Read the shell input up to a line which is identical to word. word is not subjected to variable, filename or command substitution, and each input line is compared to word before any substitutions are done on this input line. Unless a quoting `\', `"', `' or ``' appears in word variable and command substitution is performed on the intervening lines, allowing `\' to quote `$', `\' and ``'. Commands which are substituted have all blanks, tabs, and newlines preserved, except for the final newline which is dropped. The resultant text is placed in an anonymous temporary file which is given to the command as standard input. > name >! name >& name >&! name The file name is used as standard output. If the file does not exist then it is created; if the file exists, it is truncated, its previous contents being lost. If the shell variable noclobber is set, then the file must not exist or be a character special file (e.g., a terminal or `/dev/null') or an error results. This helps prevent accidental destruction of files. In this case the `!' forms can be used to suppress this check. If notempty is given in noclobber, `>' is allowed on empty files; if ask is set, an interacive confirmation is presented, rather than an error. The forms involving `&' route the diagnostic output into the specified file as well as the standard output. name is expanded in the same way as `<' input filenames are. >> name >>& name >>! name >>&! name Like `>', but appends output to the end of name. If the shell variable noclobber is set, then it is an error for the file not to exist, unless one of the `!' forms is given. A command receives the environment in which the shell was invoked as modified by the input-output parameters and the presence of the command in a pipeline. Thus, unlike some previous shells, commands run from a file of shell commands have no access to the text of the commands by default; rather they receive the original standard input of the shell. The `<<' mechanism should be used to present inline data. This permits shell command scripts to function as components of pipelines and allows the shell to block read its input. Note that the default standard input for a command run detached is not the empty file /dev/null, but the original standard input of the shell. If this is a terminal and if the process attempts to read from the terminal, then the process will block and the user will be notified (see Jobs). Diagnostic output may be directed through a pipe with the standard output. Simply use the form `|&' rather than just `|'. The shell cannot presently redirect diagnostic output without also redirecting standard output, but `(command > output-file) >& error- file' is often an acceptable workaround. Either output-file or error- file may be `/dev/tty' to send output to the terminal. Features Having described how the shell accepts, parses and executes command lines, we now turn to a variety of its useful features. Control flow The shell contains a number of commands which can be used to regulate the flow of control in command files (shell scripts) and (in limited but useful ways) from terminal input. These commands all operate by forcing the shell to reread or skip in its input and, due to the implementation, restrict the placement of some of the commands. The foreach, switch, and while statements, as well as the if-then-else form of the if statement, require that the major keywords appear in a single simple command on an input line as shown below. If the shell's input is not seekable, the shell buffers up input whenever a loop is being read and performs seeks in this internal buffer to accomplish the rereading implied by the loop. (To the extent that this allows, backward gotos will succeed on non-seekable inputs.) Expressions The if, while and exit builtin commands use expressions with a common syntax. The expressions can include any of the operators described in the next three sections. Note that the @ builtin command (q.v.) has its own separate syntax. Logical, arithmetical and comparison operators These operators are similar to those of C and have the same precedence. They include || && | ^ & == != =~ !~ <= >= < > << >> + - * / % ! ~ ( ) Here the precedence increases to the right, `==' `!=' `=~' and `!~', `<=' `>=' `<' and `>', `<<' and `>>', `+' and `-', `*' `/' and `%' being, in groups, at the same level. The `==' `!=' `=~' and `!~' operators compare their arguments as strings; all others operate on numbers. The operators `=~' and `!~' are like `!=' and `==' except that the right hand side is a glob-pattern (see Filename substitution) against which the left hand operand is matched. This reduces the need for use of the switch builtin command in shell scripts when all that is really needed is pattern matching. Null or missing arguments are considered `0'. The results of all expressions are strings, which represent decimal numbers. It is important to note that no two components of an expression can appear in the same word; except when adjacent to components of expressions which are syntactically significant to the parser (`&' `|' `<' `>' `(' `)') they should be surrounded by spaces. Command exit status Commands can be executed in expressions and their exit status returned by enclosing them in braces (`{}'). Remember that the braces should be separated from the words of the command by spaces. Command executions succeed, returning true, i.e., `1', if the command exits with status 0, otherwise they fail, returning false, i.e., `0'. If more detailed status information is required then the command should be executed outside of an expression and the status shell variable examined. File inquiry operators Some of these operators perform true/false tests on files and related objects. They are of the form -op file, where op is one of r Read access w Write access x Execute access X Executable in the path or shell builtin, e.g., `-X ls' and `-X ls-F' are generally true, but `-X /bin/ls' is not (+) e Existence o Ownership z Zero size s Non-zero size (+) f Plain file d Directory l Symbolic link (+) * b Block special file (+) c Character special file (+) p Named pipe (fifo) (+) * S Socket special file (+) * u Set-user-ID bit is set (+) g Set-group-ID bit is set (+) k Sticky bit is set (+) t file (which must be a digit) is an open file descriptor for a terminal device (+) R Has been migrated (Convex only) (+) L Applies subsequent operators in a multiple-operator test to a symbolic link rather than to the file to which the link points (+) * file is command and filename expanded and then tested to see if it has the specified relationship to the real user. If file does not exist or is inaccessible or, for the operators indicated by `*', if the specified file type does not exist on the current system, then all inquiries return false, i.e., `0'. These operators may be combined for conciseness: `-xy file' is equivalent to `-x file && -y file'. (+) For example, `-fx' is true (returns `1') for plain executable files, but not for directories. L may be used in a multiple-operator test to apply subsequent operators to a symbolic link rather than to the file to which the link points. For example, `-lLo' is true for links owned by the invoking user. Lr, Lw and Lx are always true for links and false for non-links. L has a different meaning when it is the last operator in a multiple-operator test; see below. It is possible but not useful, and sometimes misleading, to combine operators which expect file to be a file with operators which do not (e.g., X and t). Following L with a non-file operator can lead to particularly strange results. Other operators return other information, i.e., not just `0' or `1'. (+) They have the same format as before; op may be one of A Last file access time, as the number of seconds since the epoch A: Like A, but in timestamp format, e.g., `Fri May 14 16:36:10 1993' M Last file modification time M: Like M, but in timestamp format C Last inode modification time C: Like C, but in timestamp format D Device number I Inode number F Composite file identifier, in the form device:inode L The name of the file pointed to by a symbolic link N Number of (hard) links P Permissions, in octal, without leading zero P: Like P, with leading zero Pmode Equivalent to `-P file & mode', e.g., `-P22 file' returns `22' if file is writable by group and other, `20' if by group only, and `0' if by neither Pmode: Like Pmode, with leading zero U Numeric userid U: Username, or the numeric userid if the username is unknown G Numeric groupid G: Groupname, or the numeric groupid if the groupname is unknown Z Size, in bytes Only one of these operators may appear in a multiple-operator test, and it must be the last. Note that L has a different meaning at the end of and elsewhere in a multiple-operator test. Because `0' is a valid return value for many of these operators, they do not return `0' when they fail: most return `-1', and F returns `:'. If the shell is compiled with POSIX defined (see the version shell variable), the result of a file inquiry is based on the permission bits of the file and not on the result of the access(2) system call. For example, if one tests a file with -w whose permissions would ordinarily allow writing but which is on a file system mounted read-only, the test will succeed in a POSIX shell but fail in a non-POSIX shell. File inquiry operators can also be evaluated with the filetest builtin command (q.v.) (+). Jobs The 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 (top-level) process, whose process id was 1234. If you are running a job and wish to do something else you may hit the suspend key (usually `^Z'), which sends a STOP signal to the current job. The shell will then normally indicate that the job has been `Suspended' and print another prompt. If the listjobs shell variable is set, all jobs will be listed like the jobs builtin command; if it is set to `long' the listing will be in long format, like `jobs -l'. You can then manipulate the state of the suspended job. You can put it in the ``background'' with the bg command or run some other commands and eventually bring the job back into the ``foreground'' with fg. (See also the run-fg-editor editor command.) A `^Z' takes effect immediately and is like an interrupt in that pending output and unread input are discarded when it is typed. The wait builtin command causes the shell to wait for all background jobs to complete. The `^]' key sends a delayed suspend signal, which does not generate a STOP signal until a program attempts to read(2) it, to the current job. This can usefully be typed ahead when you have prepared some commands for a job which you wish to stop after it has read them. The `^Y' key performs this function in csh(1); in tcsh, `^Y' is an editing command. (+) A job being run in the background stops 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 stop when they try to produce output like they do when they try to read input. There are several ways to refer to jobs in the shell. The character `%' introduces a job name. If you wish to refer to job number 1, you can name it as `%1'. Just naming a job brings it to the foreground; thus `%1' is a synonym for `fg %1', bringing job 1 back into the foreground. Similarly, saying `%1 &' resumes job 1 in the background, just like `bg %1'. A job can also be named by an unambiguous prefix of the string typed in to start it: `%ex' would normally restart a suspended ex(1) job, if there were only one suspended job whose name began with the string `ex'. It is also possible to say `%?string' to specify a job whose text contains string, if there is only one such job. The shell maintains a notion of the current and previous jobs. In output pertaining to jobs, the current job is marked with a `+' and the previous job with a `-'. The abbreviations `%+', `%', and (by analogy with the syntax of the history mechanism) `%%' all refer to the current job, and `%-' refers to the previous job. The job control mechanism requires that the stty(1) option `new' be set on some systems. It is an artifact from a `new' implementation of the tty driver which allows generation of interrupt characters from the keyboard to tell jobs to stop. See stty(1) and the setty builtin command for details on setting options in the new tty driver. Status reporting 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, but only right before it prints a prompt. This is done so that it does not otherwise disturb your work. If, however, you set the shell variable notify, the shell will notify you immediately of changes of status in background jobs. There is also a shell command notify which marks a single process so that its status changes will be immediately reported. By default notify marks the current process; simply say `notify' after starting a background job to mark it. When you try to leave the shell while jobs are stopped, you will be warned that `There are suspended 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, and the suspended jobs will be terminated. Automatic, periodic and timed events (+) There are various ways to run commands and take other actions automatically at various times in the ``life cycle'' of the shell. They are summarized here, and described in detail under the appropriate Builtin commands, Special shell variables and Special aliases. The sched builtin command puts commands in a scheduled-event list, to be executed by the shell at a given time. The beepcmd, cwdcmd, periodic, precmd, postcmd, and jobcmd Special aliases can be set, respectively, to execute commands when the shell wants to ring the bell, when the working directory changes, every tperiod minutes, before each prompt, before each command gets executed, after each command gets executed, and when a job is started or is brought into the foreground. The autologout shell variable can be set to log out or lock the shell after a given number of minutes of inactivity. The mail shell variable can be set to check for new mail periodically. The printexitvalue shell variable can be set to print the exit status of commands which exit with a status other than zero. The rmstar shell variable can be set to ask the user, when `rm *' is typed, if that is really what was meant. The time shell variable can be set to execute the time builtin command after the completion of any process that takes more than a given number of CPU seconds. The watch and who shell variables can be set to report when selected users log in or out, and the log builtin command reports on those users at any time. Native Language System support (+) The shell is eight bit clean (if so compiled; see the version shell variable) and thus supports character sets needing this capability. NLS support differs depending on whether or not the shell was compiled to use the system's NLS (again, see version). In either case, 7-bit ASCII is the default character code (e.g., the classification of which characters are printable) and sorting, and changing the LANG or LC_CTYPE environment variables causes a check for possible changes in these respects. When using the system's NLS, the setlocale(3) function is called to determine appropriate character code/classification and sorting (e.g., a 'en_CA.UTF-8' would yield "UTF-8" as a character code). This function typically examines the LANG and LC_CTYPE environment variables; refer to the system documentation for further details. When not using the system's NLS, the shell simulates it by assuming that the ISO 8859-1 character set is used whenever either of the LANG and LC_CTYPE variables are set, regardless of their values. Sorting is not affected for the simulated NLS. In addition, with both real and simulated NLS, all printable characters in the range \200-\377, i.e., those that have M-char bindings, are automatically rebound to self-insert-command. The corresponding binding for the escape-char sequence, if any, is left alone. These characters are not rebound if the NOREBIND environment variable is set. This may be useful for the simulated NLS or a primitive real NLS which assumes full ISO 8859-1. Otherwise, all M-char bindings in the range \240-\377 are effectively undone. Explicitly rebinding the relevant keys with bindkey is of course still possible. Unknown characters (i.e., those that are neither printable nor control characters) are printed in the format \nnn. If the tty is not in 8 bit mode, other 8 bit characters are printed by converting them to ASCII and using standout mode. The shell never changes the 7/8 bit mode of the tty and tracks user-initiated changes of 7/8 bit mode. NLS users (or, for that matter, those who want to use a meta key) may need to explicitly set the tty in 8 bit mode through the appropriate stty(1) command in, e.g., the ~/.login file. OS variant support (+) A number of new builtin commands are provided to support features in particular operating systems. All are described in detail in the Builtin commands section. On systems that support TCF (aix-ibm370, aix-ps2), getspath and setspath get and set the system execution path, getxvers and setxvers get and set the experimental version prefix and migrate migrates processes between sites. The jobs builtin prints the site on which each job is executing. Under BS2000, bs2cmd executes commands of the underlying BS2000/OSD operating system. Under Domain/OS, inlib adds shared libraries to the current environment, rootnode changes the rootnode and ver changes the systype. Under Mach, setpath is equivalent to Mach's setpath(1). Under Masscomp/RTU and Harris CX/UX, universe sets the universe. Under Harris CX/UX, ucb or att runs a command under the specified universe. Under Convex/OS, warp prints or sets the universe. The VENDOR, OSTYPE and MACHTYPE environment variables indicate respectively the vendor, operating system and machine type (microprocessor class or machine model) of the system on which the shell thinks it is running. These are particularly useful when sharing one's home directory between several types of machines; one can, for example, set path = (~/bin.$MACHTYPE /usr/ucb /bin /usr/bin .) in one's ~/.login and put executables compiled for each machine in the appropriate directory. The version shell variable indicates what options were chosen when the shell was compiled. Note also the newgrp builtin, the afsuser and echo_style shell variables and the system-dependent locations of the shell's input files (see FILES). Signal handling Login shells ignore interrupts when reading the file ~/.logout. The shell ignores quit signals unless started with -q. Login shells catch the terminate signal, but non-login shells inherit the terminate behavior from their parents. Other signals have the values which the shell inherited from its parent. In shell scripts, the shell's handling of interrupt and terminate signals can be controlled with onintr, and its handling of hangups can be controlled with hup and nohup. The shell exits on a hangup (see also the logout shell variable). By default, the shell's children do too, but the shell does not send them a hangup when it exits. hup arranges for the shell to send a hangup to a child when it exits, and nohup sets a child to ignore hangups. Terminal management (+) The shell uses three different sets of terminal (``tty'') modes: `edit', used when editing, `quote', used when quoting literal characters, and `execute', used when executing commands. The shell holds some settings in each mode constant, so commands which leave the tty in a confused state do not interfere with the shell. The shell also matches changes in the speed and padding of the tty. The list of tty modes that are kept constant can be examined and modified with the setty builtin. Note that although the editor uses CBREAK mode (or its equivalent), it takes typed-ahead characters anyway. The echotc, settc and telltc commands can be used to manipulate and debug terminal capabilities from the command line. On systems that support SIGWINCH or SIGWINDOW, the shell adapts to window resizing automatically and adjusts the environment variables LINES and COLUMNS if set. If the environment variable TERMCAP contains li# and co# fields, the shell adjusts them to reflect the new window size. REFERENCE The next sections of this manual describe all of the available Builtin commands, Special aliases and Special shell variables. Builtin commands %job A synonym for the fg builtin command. %job & A synonym for the bg builtin command. : Does nothing, successfully. @ @ name = expr @ name[index] = expr @ name++|-- @ name[index]++|-- The first form prints the values of all shell variables. The second form assigns the value of expr to name. The third form assigns the value of expr to the index'th component of name; both name and its index'th component must already exist. expr may contain the operators `*', `+', etc., as in C. If expr contains `<', `>', `&' or `' then at least that part of expr must be placed within `()'. Note that the syntax of expr has nothing to do with that described under Expressions. The fourth and fifth forms increment (`++') or decrement (`--') name or its index'th component. The space between `@' and name is required. The spaces between name and `=' and between `=' and expr are optional. Components of expr must be separated by spaces. alias [name [wordlist]] Without arguments, prints all aliases. With name, prints the alias for name. With name and wordlist, assigns wordlist as the alias of name. wordlist is command and filename substituted. name may not be `alias' or `unalias'. See also the unalias builtin command. alloc Shows the amount of dynamic memory acquired, broken down into used and free memory. With an argument shows the number of free and used blocks in each size category. The categories start at size 8 and double at each step. This command's output may vary across system types, because systems other than the VAX may use a different memory allocator. bg [%job ...] Puts the specified jobs (or, without arguments, the current job) into the background, continuing each if it is stopped. job may be a number, a string, `', `%', `+' or `-' as described under Jobs. bindkey [-l|-d|-e|-v|-u] (+) bindkey [-a] [-b] [-k] [-r] [--] key (+) bindkey [-a] [-b] [-k] [-c|-s] [--] key command (+) Without options, the first form lists all bound keys and the editor command to which each is bound, the second form lists the editor command to which key is bound and the third form binds the editor command command to key. Options include: -l Lists all editor commands and a short description of each. -d Binds all keys to the standard bindings for the default editor, as per -e and -v below. -e Binds all keys to emacs(1)-style bindings. Unsets vimode. -v Binds all keys to vi(1)-style bindings. Sets vimode. -a Lists or changes key-bindings in the alternative key map. This is the key map used in vimode command mode. -b key is interpreted as a control character written ^character (e.g., `^A') or C-character (e.g., `C-A'), a meta character written M-character (e.g., `M-A'), a function key written F-string (e.g., `F-string'), or an extended prefix key written X-character (e.g., `X-A'). -k key is interpreted as a symbolic arrow key name, which may be one of `down', `up', `left' or `right'. -r Removes key's binding. Be careful: `bindkey -r' does not bind key to self-insert-command (q.v.), it unbinds key completely. -c command is interpreted as a builtin or external command instead of an editor command. -s command is taken as a literal string and treated as terminal input when key is typed. Bound keys in command are themselves reinterpreted, and this continues for ten levels of interpretation. -- Forces a break from option processing, so the next word is taken as key even if it begins with '-'. -u (or any invalid option) Prints a usage message. key may be a single character or a string. If a command is bound to a string, the first character of the string is bound to sequence-lead-in and the entire string is bound to the command. Control characters in key can be literal (they can be typed by preceding them with the editor command quoted-insert, normally bound to `^V') or written caret-character style, e.g., `^A'. Delete is written `^?' (caret-question mark). key and command can contain backslashed escape sequences (in the style of System V echo(1)) as follows: \a Bell \b Backspace \e Escape \f Form feed \n Newline \r Carriage return \t Horizontal tab \v Vertical tab \nnn The ASCII character corresponding to the octal number nnn `\' nullifies the special meaning of the following character, if it has any, notably `\' and `^'. bs2cmd bs2000-command (+) Passes bs2000-command to the BS2000 command interpreter for execution. Only non-interactive commands can be executed, and it is not possible to execute any command that would overlay the image of the current process, like /EXECUTE or /CALL- PROCEDURE. (BS2000 only) break Causes execution to resume after the end of the nearest enclosing foreach or while. The remaining commands on the current line are executed. Multi-level breaks are thus possible by writing them all on one line. breaksw Causes a break from a switch, resuming after the endsw. builtins (+) Prints the names of all builtin commands. bye (+) A synonym for the logout builtin command. Available only if the shell was so compiled; see the version shell variable. case label: A label in a switch statement as discussed below. cd [-p] [-l] [-n|-v] [I--] [name] If a directory name is given, changes the shell's working directory to name. If not, changes to home, unless the cdtohome variable is not set, in which case a name is required. If name is `-' it is interpreted as the previous working directory (see Other substitutions). (+) If name is not a subdirectory of the current directory (and does not begin with `/', `./' or `../'), each component of the variable cdpath is checked to see if it has a subdirectory name. Finally, if all else fails but name is a shell variable whose value begins with `/' or '.', then this is tried to see if it is a directory, and the -p option is implied. With -p, prints the final directory stack, just like dirs. The -l, -n and -v flags have the same effect on cd as on dirs, and they imply -p. (+) Using -- forces a break from option processing so the next word is taken as the directory name even if it begins with '-'. (+) See also the implicitcd and cdtohome shell variables. chdir A synonym for the cd builtin command. complete [command [word/pattern/list[:select]/[[suffix]/] ...]] (+) Without arguments, lists all completions. With command, lists completions for command. With command and word etc., defines completions. command may be a full command name or a glob-pattern (see Filename substitution). It can begin with `-' to indicate that completion should be used only when command is ambiguous. word specifies which word relative to the current word is to be completed, and may be one of the following: c Current-word completion. pattern is a glob-pattern which must match the beginning of the current word on the command line. pattern is ignored when completing the current word. C Like c, but includes pattern when completing the current word. n Next-word completion. pattern is a glob-pattern which must match the beginning of the previous word on the command line. N Like n, but must match the beginning of the word two before the current word. p Position-dependent completion. pattern is a numeric range, with the same syntax used to index shell variables, which must include the current word. list, the list of possible completions, may be one of the following: a Aliases b Bindings (editor commands) c Commands (builtin or external commands) C External commands which begin with the supplied path prefix d Directories D Directories which begin with the supplied path prefix e Environment variables f Filenames F Filenames which begin with the supplied path prefix g Groupnames j Jobs l Limits n Nothing s Shell variables S Signals t Plain (``text'') files T Plain (``text'') files which begin with the supplied path prefix v Any variables u Usernames x Like n, but prints select when list-choices is used. X Completions $var Words from the variable var (...) Words from the given list `...` Words from the output of command select is an optional glob-pattern. If given, words from only list that match select are considered and the fignore shell variable is ignored. The last three types of completion may not have a select pattern, and x uses select as an explanatory message when the list-choices editor command is used. suffix is a single character to be appended to a successful completion. If null, no character is appended. If omitted (in which case the fourth delimiter can also be omitted), a slash is appended to directories and a space to other words. command invoked from `...` version has additional environment variable set, the variable name is COMMAND_LINE and contains (as its name indicates) contents of the current (already typed in) command line. One can examine and use contents of the COMMAND_LINE variable in her custom script to build more sophisticated completions (see completion for svn(1) included in this package). Now for some examples. Some commands take only directories as arguments, so there's no point completing plain files. > complete cd 'p/1/d/' completes only the first word following `cd' (`p/1') with a directory. p-type completion can also be used to narrow down command completion: > co[^D] complete compress > complete -co* 'p/0/(compress)/' > co[^D] > compress This completion completes commands (words in position 0, `p/0') which begin with `co' (thus matching `co*') to `compress' (the only word in the list). The leading `-' indicates that this completion is to be used with only ambiguous commands. > complete find 'n/-user/u/' is an example of n-type completion. Any word following `find' and immediately following `-user' is completed from the list of users. > complete cc 'c/-I/d/' demonstrates c-type completion. Any word following `cc' and beginning with `-I' is completed as a directory. `-I' is not taken as part of the directory because we used lowercase c. Different lists are useful with different commands. > complete alias 'p/1/a/' > complete man 'p/*/c/' > complete set 'p/1/s/' > complete true 'p/1/x:Truth has no options./' These complete words following `alias' with aliases, `man' with commands, and `set' with shell variables. `true' doesn't have any options, so x does nothing when completion is attempted and prints `Truth has no options.' when completion choices are listed. Note that the man example, and several other examples below, could just as well have used 'c/*' or 'n/*' as 'p/*'. Words can be completed from a variable evaluated at completion time, > complete ftp 'p/1/$hostnames/' > set hostnames = (rtfm.mit.edu tesla.ee.cornell.edu) > ftp [^D] rtfm.mit.edu tesla.ee.cornell.edu > ftp [^C] > set hostnames = (rtfm.mit.edu tesla.ee.cornell.edu uunet.uu.net) > ftp [^D] rtfm.mit.edu tesla.ee.cornell.edu uunet.uu.net or from a command run at completion time: > complete kill 'p/*/`ps | awk \{print\ \$1\}`/' > kill -9 [^D] 23113 23377 23380 23406 23429 23529 23530 PID Note that the complete command does not itself quote its arguments, so the braces, space and `$' in `{print $1}' must be quoted explicitly. One command can have multiple completions: > complete dbx 'p/2/(core)/' 'p/*/c/' completes the second argument to `dbx' with the word `core' and all other arguments with commands. Note that the positional completion is specified before the next-word completion. Because completions are evaluated from left to right, if the next-word completion were specified first it would always match and the positional completion would never be executed. This is a common mistake when defining a completion. The select pattern is useful when a command takes files with only particular forms as arguments. For example, > complete cc 'p/*/f:*.[cao]/' completes `cc' arguments to files ending in only `.c', `.a', or `.o'. select can also exclude files, using negation of a glob- pattern as described under Filename substitution. One might use > complete rm 'p/*/f:^*.{c,h,cc,C,tex,1,man,l,y}/' to exclude precious source code from `rm' completion. Of course, one could still type excluded names manually or override the completion mechanism using the complete-word-raw or list-choices-raw editor commands (q.v.). The `C', `D', `F' and `T' lists are like `c', `d', `f' and `t' respectively, but they use the select argument in a different way: to restrict completion to files beginning with a particular path prefix. For example, the Elm mail program uses `=' as an abbreviation for one's mail directory. One might use > complete elm c@=@F:$HOME/Mail/@ to complete `elm -f =' as if it were `elm -f ~/Mail/'. Note that we used `@' instead of `/' to avoid confusion with the select argument, and we used `$HOME' instead of `~' because home directory substitution works at only the beginning of a word. suffix is used to add a nonstandard suffix (not space or `/' for directories) to completed words. > complete finger 'c/*@/$hostnames/' 'p/1/u/@' completes arguments to `finger' from the list of users, appends an `@', and then completes after the `@' from the `hostnames' variable. Note again the order in which the completions are specified. Finally, here's a complex example for inspiration: > complete find \ 'n/-name/f/' 'n/-newer/f/' 'n/-{,n}cpio/f/' \ ´n/-exec/c/' 'n/-ok/c/' 'n/-user/u/' \ 'n/-group/g/' 'n/-fstype/(nfs 4.2)/' \ 'n/-type/(b c d f l p s)/' \ ´c/-/(name newer cpio ncpio exec ok user \ group fstype type atime ctime depth inum \ ls mtime nogroup nouser perm print prune \ size xdev)/' \ 'p/*/d/' This completes words following `-name', `-newer', `-cpio' or `ncpio' (note the pattern which matches both) to files, words following `-exec' or `-ok' to commands, words following `user' and `group' to users and groups respectively and words following `-fstype' or `-type' to members of the given lists. It also completes the switches themselves from the given list (note the use of c-type completion) and completes anything not otherwise completed to a directory. Whew. Remember that programmed completions are ignored if the word being completed is a tilde substitution (beginning with `~') or a variable (beginning with `$'). See also the uncomplete builtin command. continue Continues execution of the nearest enclosing while or foreach. The rest of the commands on the current line are executed. default: Labels the default case in a switch statement. It should come after all case labels. dirs [-l] [-n|-v] dirs -S|-L [filename] (+) dirs -c (+) The first form prints the directory stack. The top of the stack is at the left and the first directory in the stack is the current directory. With -l, `~' or `~name' in the output is expanded explicitly to home or the pathname of the home directory for user name. (+) With -n, entries are wrapped before they reach the edge of the screen. (+) With -v, entries are printed one per line, preceded by their stack positions. (+) If more than one of -n or -v is given, -v takes precedence. -p is accepted but does nothing. With -S, the second form saves the directory stack to filename as a series of cd and pushd commands. With -L, the shell sources filename, which is presumably a directory stack file saved by the -S option or the savedirs mechanism. In either case, dirsfile is used if filename is not given and ~/.cshdirs is used if dirsfile is unset. Note that login shells do the equivalent of `dirs -L' on startup and, if savedirs is set, `dirs -S' before exiting. Because only ~/.tcshrc is normally sourced before ~/.cshdirs, dirsfile should be set in ~/.tcshrc rather than ~/.login. The last form clears the directory stack. echo [-n] word ... Writes each word to the shell's standard output, separated by spaces and terminated with a newline. The echo_style shell variable may be set to emulate (or not) the flags and escape sequences of the BSD and/or System V versions of echo; see echo(1). echotc [-sv] arg ... (+) Exercises the terminal capabilities (see termcap(5)) in args. For example, 'echotc home' sends the cursor to the home position, 'echotc cm 3 10' sends it to column 3 and row 10, and 'echotc ts 0; echo "This is a test."; echotc fs' prints "This is a test." in the status line. If arg is 'baud', 'cols', 'lines', 'meta' or 'tabs', prints the value of that capability ("yes" or "no" indicating that the terminal does or does not have that capability). One might use this to make the output from a shell script less verbose on slow terminals, or limit command output to the number of lines on the screen: > set history=`echotc lines` > @ history-- Termcap strings may contain wildcards which will not echo correctly. One should use double quotes when setting a shell variable to a terminal capability string, as in the following example that places the date in the status line: > set tosl="`echotc ts 0`" > set frsl="`echotc fs`" > echo -n "$tosl";date; echo -n "$frsl" With -s, nonexistent capabilities return the empty string rather than causing an error. With -v, messages are verbose. else end endif endsw See the description of the foreach, if, switch, and while statements below. eval arg ... Treats the arguments as input to the shell and executes the resulting command(s) in the context of the current shell. This is usually used to execute commands generated as the result of command or variable substitution, because parsing occurs before these substitutions. See tset(1) for a sample use of eval. exec command Executes the specified command in place of the current shell. exit [expr] The shell exits either with the value of the specified expr (an expression, as described under Expressions) or, without expr, with the value 0. fg [%job ...] Brings the specified jobs (or, without arguments, the current job) into the foreground, continuing each if it is stopped. job may be a number, a string, `', `%', `+' or `-' as described under Jobs. See also the run-fg-editor editor command. filetest -op file ... (+) Applies op (which is a file inquiry operator as described under File inquiry operators) to each file and returns the results as a space-separated list. foreach name (wordlist) ... end Successively sets the variable name to each member of wordlist and executes the sequence of commands between this command and the matching end. (Both foreach and end must appear alone on separate lines.) The builtin command continue may be used to continue the loop prematurely and the builtin command break to terminate it prematurely. When this command is read from the terminal, the loop is read once prompting with `foreach? ' (or prompt2) before any statements in the loop are executed. If you make a mistake typing in a loop at the terminal you can rub it out. getspath (+) Prints the system execution path. (TCF only) getxvers (+) Prints the experimental version prefix. (TCF only) glob wordlist Like echo, but the `-n' parameter is not recognized and words are delimited by null characters in the output. Useful for programs which wish to use the shell to filename expand a list of words. goto word word is filename and command-substituted to yield a string of the form `label'. The shell rewinds its input as much as possible, searches for a line of the form `label:', possibly preceded by blanks or tabs, and continues execution after that line. hashstat Prints a statistics line indicating how effective the internal hash table has been at locating commands (and avoiding exec's). An exec is attempted for each component of the path where the hash function indicates a possible hit, and in each component which does not begin with a `/'. On machines without vfork(2), prints only the number and size of hash buckets. history [-hTr] [n] history -S|-L|-M [filename] (+) history -c (+) The first form prints the history event list. If n is given only the n most recent events are printed or saved. With -h, the history list is printed without leading numbers. If -T is specified, timestamps are printed also in comment form. (This can be used to produce files suitable for loading with 'history -L' or 'source -h'.) With -r, the order of printing is most recent first rather than oldest first. With -S, the second form saves the history list to filename. If the first word of the savehist shell variable is set to a number, at most that many lines are saved. If the second word of savehist is set to `merge', the history list is merged with the existing history file instead of replacing it (if there is one) and sorted by time stamp. (+) Merging is intended for an environment like the X Window System with several shells in simultaneous use. If the second word of savehist is `merge' and the third word is set to `lock', the history file update will be serialized with other shell sessions that would possibly like to merge history at exactly the same time. With -L, the shell appends filename, which is presumably a history list saved by the -S option or the savehist mechanism, to the history list. -M is like -L, but the contents of filename are merged into the history list and sorted by timestamp. In either case, histfile is used if filename is not given and ~/.history is used if histfile is unset. `history -L' is exactly like 'source -h' except that it does not require a filename. Note that login shells do the equivalent of `history -L' on startup and, if savehist is set, `history -S' before exiting. Because only ~/.tcshrc is normally sourced before ~/.history, histfile should be set in ~/.tcshrc rather than ~/.login. If histlit is set, the first and second forms print and save the literal (unexpanded) form of the history list. The last form clears the history list. hup [command] (+) With command, runs command such that it will exit on a hangup signal and arranges for the shell to send it a hangup signal when the shell exits. Note that commands may set their own response to hangups, overriding hup. Without an argument, causes the non-interactive shell only to exit on a hangup for the remainder of the script. See also Signal handling and the nohup builtin command. if (expr) command If expr (an expression, as described under Expressions) evaluates true, then command is executed. Variable substitution on command happens early, at the same time it does for the rest of the if command. command must be a simple command, not an alias, a pipeline, a command list or a parenthesized command list, but it may have arguments. Input/output redirection occurs even if expr is false and command is thus not executed; this is a bug. if (expr) then ... else if (expr2) then ... else ... endif If the specified expr is true then the commands to the first else are executed; otherwise if expr2 is true then the commands to the second else are executed, etc. Any number of else-if pairs are possible; only one endif is needed. The else part is likewise optional. (The words else and endif must appear at the beginning of input lines; the if must appear alone on its input line or after an else.) inlib shared-library ... (+) Adds each shared-library to the current environment. There is no way to remove a shared library. (Domain/OS only) jobs [-l] Lists the active jobs. With -l, lists process IDs in addition to the normal information. On TCF systems, prints the site on which each job is executing. kill [-s signal] %job|pid ... kill -l The first and second forms sends the specified signal (or, if none is given, the TERM (terminate) signal) to the specified jobs or processes. job may be a number, a string, `', `%', `+' or `-' as described under Jobs. Signals are either given by number or by name (as given in /usr/include/signal.h, stripped of the prefix `SIG'). There is no default job; saying just `kill' does not send a signal to the current job. If the signal being sent is TERM (terminate) or HUP (hangup), then the job or process is sent a CONT (continue) signal as well. The third form lists the signal names. limit [-h] [resource [maximum-use]] Limits the consumption by the current process and each process it creates to not individually exceed maximum-use on the specified resource. If no maximum-use is given, then the current limit is printed; if no resource is given, then all limitations are given. If the -h flag is given, the hard limits are used instead of the current limits. The hard limits impose a ceiling on the values of the current limits. Only the super-user may raise the hard limits, but a user may lower or raise the current limits within the legal range. Controllable resources currently include (if supported by the OS): cputime the maximum number of cpu-seconds to be used by each process filesize the largest single file which can be created datasize the maximum growth of the data+stack region via sbrk(2) beyond the end of the program text stacksize the maximum size of the automatically-extended stack region coredumpsize the size of the largest core dump that will be created memoryuse the maximum amount of physical memory a process may have allocated to it at a given time vmemoryuse the maximum amount of virtual memory a process may have allocated to it at a given time (address space) vmemoryuse the maximum amount of virtual memory a process may have allocated to it at a given time heapsize the maximum amount of memory a process may allocate per brk() system call descriptors or openfiles the maximum number of open files for this process pseudoterminals the maximum number of pseudo-terminals for this user kqueues the maximum number of kqueues allocated for this process concurrency the maximum number of threads for this process memorylocked the maximum size which a process may lock into memory using mlock(2) maxproc the maximum number of simultaneous processes for this user id maxthread the maximum number of simultaneous threads (lightweight processes) for this user id threads the maximum number of threads for this process sbsize the maximum size of socket buffer usage for this user swapsize the maximum amount of swap space reserved or used for this user maxlocks the maximum number of locks for this user posixlocks the maximum number of POSIX advisory locks for this user maxsignal the maximum number of pending signals for this user maxmessage the maximum number of bytes in POSIX mqueues for this user maxnice the maximum nice priority the user is allowed to raise mapped from [19...-20] to [0...39] for this user maxrtprio the maximum realtime priority for this user maxrttime the timeout for RT tasks in microseconds for this user. maximum-use may be given as a (floating point or integer) number followed by a scale factor. For all limits other than cputime the default scale is `k' or `kilobytes' (1024 bytes); a scale factor of `m' or `megabytes' or `g' or `gigabytes' may also be used. For cputime the default scaling is `seconds', while `m' for minutes or `h' for hours, or a time of the form `mm:ss' giving minutes and seconds may be used. If maximum-use is `unlimited', then the limitation on the specified resource is removed (this is equivalent to the unlimit builtin command). For both resource names and scale factors, unambiguous prefixes of the names suffice. log (+) Prints the watch shell variable and reports on each user indicated in watch who is logged in, regardless of when they last logged in. See also watchlog. login Terminates a login shell, replacing it with an instance of /bin/login. This is one way to log off, included for compatibility with sh(1). logout Terminates a login shell. Especially useful if ignoreeof is set. ls-F [-switch ...] [file ...] (+) Lists files like `ls -F', but much faster. It identifies each type of special file in the listing with a special character: / Directory * Executable # Block device % Character device | Named pipe (systems with named pipes only) = Socket (systems with sockets only) @ Symbolic link (systems with symbolic links only) + Hidden directory (AIX only) or context dependent (HP/UX only) : Network special (HP/UX only) If the listlinks shell variable is set, symbolic links are identified in more detail (on only systems that have them, of course): @ Symbolic link to a non-directory > Symbolic link to a directory & Symbolic link to nowhere listlinks also slows down ls-F and causes partitions holding files pointed to by symbolic links to be mounted. If the listflags shell variable is set to `x', `a' or `A', or any combination thereof (e.g., `xA'), they are used as flags to ls-F, making it act like `ls -xF', `ls -Fa', `ls -FA' or a combination (e.g., `ls -FxA'). On machines where `ls -C' is not the default, ls-F acts like `ls -CF', unless listflags contains an `x', in which case it acts like `ls -xF'. ls-F passes its arguments to ls(1) if it is given any switches, so `alias ls ls-F' generally does the right thing. The ls-F builtin can list files using different colors depending on the filetype or extension. See the color shell variable and the LS_COLORS environment variable. migrate [-site] pid|%jobid ... (+) migrate -site (+) The first form migrates the process or job to the site specified or the default site determined by the system path. The second form is equivalent to `migrate -site $$': it migrates the current process to the specified site. Migrating the shell itself can cause unexpected behavior, because the shell does not like to lose its tty. (TCF only) newgrp [-] [group] (+) Equivalent to `exec newgrp'; see newgrp(1). Available only if the shell was so compiled; see the version shell variable. nice [+number] [command] Sets the scheduling priority for the shell to number, or, without number, to 4. With command, runs command at the appropriate priority. The greater the number, the less cpu the process gets. The super-user may specify negative priority by using `nice -number ...'. Command is always executed in a sub- shell, and the restrictions placed on commands in simple if statements apply. nohup [command] With command, runs command such that it will ignore hangup signals. Note that commands may set their own response to hangups, overriding nohup. Without an argument, causes the non-interactive shell only to ignore hangups for the remainder of the script. See also Signal handling and the hup builtin command. notify [%job ...] Causes the shell to notify the user asynchronously when the status of any of the specified jobs (or, without %job, the current job) changes, instead of waiting until the next prompt as is usual. job may be a number, a string, `', `%', `+' or `-' as described under Jobs. See also the notify shell variable. onintr [-|label] Controls the action of the shell on interrupts. Without arguments, restores the default action of the shell on interrupts, which is to terminate shell scripts or to return to the terminal command input level. With `-', causes all interrupts to be ignored. With label, causes the shell to execute a `goto label' when an interrupt is received or a child process terminates because it was interrupted. onintr is ignored if the shell is running detached and in system startup files (see FILES), where interrupts are disabled anyway. popd [-p] [-l] [-n|-v] [+n] Without arguments, pops the directory stack and returns to the new top directory. With a number `+n', discards the n'th entry in the stack. Finally, all forms of popd print the final directory stack, just like dirs. The pushdsilent shell variable can be set to prevent this and the -p flag can be given to override pushdsilent. The -l, -n and -v flags have the same effect on popd as on dirs. (+) printenv [name] (+) Prints the names and values of all environment variables or, with name, the value of the environment variable name. pushd [-p] [-l] [-n|-v] [name|+n] Without arguments, exchanges the top two elements of the directory stack. If pushdtohome is set, pushd without arguments does `pushd ~', like cd. (+) With name, pushes the current working directory onto the directory stack and changes to name. If name is `-' it is interpreted as the previous working directory (see Filename substitution). (+) If dunique is set, pushd removes any instances of name from the stack before pushing it onto the stack. (+) With a number `+n', rotates the nth element of the directory stack around to be the top element and changes to it. If dextract is set, however, `pushd +n' extracts the nth directory, pushes it onto the top of the stack and changes to it. (+) Finally, all forms of pushd print the final directory stack, just like dirs. The pushdsilent shell variable can be set to prevent this and the -p flag can be given to override pushdsilent. The -l, -n and -v flags have the same effect on pushd as on dirs. (+) rehash Causes the internal hash table of the contents of the directories in the path variable to be recomputed. This is needed if the autorehash shell variable is not set and new commands are added to directories in path while you are logged in. With autorehash, a new command will be found automatically, except in the special case where another command of the same name which is located in a different directory already exists in the hash table. Also flushes the cache of home directories built by tilde expansion. repeat count command The specified command, which is subject to the same restrictions as the command in the one line if statement above, is executed count times. I/O redirections occur exactly once, even if count is 0. rootnode //nodename (+) Changes the rootnode to //nodename, so that `/' will be interpreted as `//nodename'. (Domain/OS only) sched (+) sched [+]hh:mm command (+) sched -n (+) The first form prints the scheduled-event list. The sched shell variable may be set to define the format in which the scheduled-event list is printed. The second form adds command to the scheduled-event list. For example, > sched 11:00 echo It\'s eleven o\'clock. causes the shell to echo `It's eleven o'clock.' at 11 AM. The time may be in 12-hour AM/PM format > sched 5pm set prompt='[%h] It\'s after 5; go home: >' or may be relative to the current time: > sched +2:15 /usr/lib/uucp/uucico -r1 -sother A relative time specification may not use AM/PM format. The third form removes item n from the event list: > sched 1 Wed Apr 4 15:42 /usr/lib/uucp/uucico -r1 -sother 2 Wed Apr 4 17:00 set prompt=[%h] It's after 5; go home: > > sched -2 > sched 1 Wed Apr 4 15:42 /usr/lib/uucp/uucico -r1 -sother A command in the scheduled-event list is executed just before the first prompt is printed after the time when the command is scheduled. It is possible to miss the exact time when the command is to be run, but an overdue command will execute at the next prompt. A command which comes due while the shell is waiting for user input is executed immediately. However, normal operation of an already-running command will not be interrupted so that a scheduled-event list element may be run. This mechanism is similar to, but not the same as, the at(1) command on some Unix systems. Its major disadvantage is that it may not run a command at exactly the specified time. Its major advantage is that because sched runs directly from the shell, it has access to shell variables and other structures. This provides a mechanism for changing one's working environment based on the time of day. set set name ... set name=word ... set [-r] [-f|-l] name=(wordlist) ... (+) set name[index]=word ... set -r (+) set -r name ... (+) set -r name=word ... (+) The first form of the command prints the value of all shell variables. Variables which contain more than a single word print as a parenthesized word list. The second form sets name to the null string. The third form sets name to the single word. The fourth form sets name to the list of words in wordlist. In all cases the value is command and filename expanded. If -r is specified, the value is set read-only. If -f or -l are specified, set only unique words keeping their order. -f prefers the first occurrence of a word, and -l the last. The fifth form sets the index'th component of name to word; this component must already exist. The sixth form lists only the names of all shell variables that are read-only. The seventh form makes name read-only, whether or not it has a value. The eighth form is the same as the third form, but make name read-only at the same time. These arguments can be repeated to set and/or make read-only multiple variables in a single set command. Note, however, that variable expansion happens for all arguments before any setting occurs. Note also that `=' can be adjacent to both name and word or separated from both by whitespace, but cannot be adjacent to only one or the other. See also the unset builtin command. setenv [name [value]] Without arguments, prints the names and values of all environment variables. Given name, sets the environment variable name to value or, without value, to the null string. setpath path (+) Equivalent to setpath(1). (Mach only) setspath LOCAL|site|cpu ... (+) Sets the system execution path. (TCF only) settc cap value (+) Tells the shell to believe that the terminal capability cap (as defined in termcap(5)) has the value value. No sanity checking is done. Concept terminal users may have to `settc xn no' to get proper wrapping at the rightmost column. setty [-d|-q|-x] [-a] [[+|-]mode] (+) Controls which tty modes (see Terminal management) the shell does not allow to change. -d, -q or -x tells setty to act on the `edit', `quote' or `execute' set of tty modes respectively; without -d, -q or -x, `execute' is used. Without other arguments, setty lists the modes in the chosen set which are fixed on (`+mode') or off (`-mode'). The available modes, and thus the display, vary from system to system. With -a, lists all tty modes in the chosen set whether or not they are fixed. With +mode, -mode or mode, fixes mode on or off or removes control from mode in the chosen set. For example, `setty +echok echoe' fixes `echok' mode on and allows commands to turn `echoe' mode on or off, both when the shell is executing commands. setxvers [string] (+) Set the experimental version prefix to string, or removes it if string is omitted. (TCF only) shift [variable] Without arguments, discards argv[1] and shifts the members of argv to the left. It is an error for argv not to be set or to have less than one word as value. With variable, performs the same function on variable. source [-h] name [args ...] The shell reads and executes commands from name. The commands are not placed on the history list. If any args are given, they are placed in argv. (+) source commands may be nested; if they are nested too deeply the shell may run out of file descriptors. An error in a source at any level terminates all nested source commands. With -h, commands are placed on the history list instead of being executed, much like `history -L'. stop %job|pid ... Stops the specified jobs or processes which are executing in the background. job may be a number, a string, `', `%', `+' or `-' as described under Jobs. There is no default job; saying just `stop' does not stop the current job. suspend Causes the shell to stop in its tracks, much as if it had been sent a stop signal with ^Z. This is most often used to stop shells started by su(1). switch (string) case str1: ... breaksw ... default: ... breaksw endsw Each case label is successively matched, against the specified string which is first command and filename expanded. The file metacharacters `*', `?' and `[...]' may be used in the case labels, which are variable expanded. If none of the labels match before a `default' label is found, then the execution begins after the default label. Each case label and the default label must appear at the beginning of a line. The command breaksw causes execution to continue after the endsw. Otherwise control may fall through case labels and default labels as in C. If no label matches and there is no default, execution continues after the endsw. telltc (+) Lists the values of all terminal capabilities (see termcap(5)). termname [terminal type] (+) Tests if terminal type (or the current value of TERM if no terminal type is given) has an entry in the hosts termcap(5) or terminfo(5) database. Prints the terminal type to stdout and returns 0 if an entry is present otherwise returns 1. time [command] Executes command (which must be a simple command, not an alias, a pipeline, a command list or a parenthesized command list) and prints a time summary as described under the time variable. If necessary, an extra shell is created to print the time statistic when the command completes. Without command, prints a time summary for the current shell and its children. umask [value] Sets the file creation mask to value, which is given in octal. Common values for the mask are 002, giving all access to the group and read and execute access to others, and 022, giving read and execute access to the group and others. Without value, prints the current file creation mask. unalias pattern Removes all aliases whose names match pattern. `unalias *' thus removes all aliases. It is not an error for nothing to be unaliased. uncomplete pattern (+) Removes all completions whose names match pattern. `uncomplete *' thus removes all completions. It is not an error for nothing to be uncompleted. unhash Disables use of the internal hash table to speed location of executed programs. universe universe (+) Sets the universe to universe. (Masscomp/RTU only) unlimit [-hf] [resource] Removes the limitation on resource or, if no resource is specified, all resource limitations. With -h, the corresponding hard limits are removed. Only the super-user may do this. Note that unlimit may not exit successful, since most systems do not allow descriptors to be unlimited. With -f errors are ignored. unset pattern Removes all variables whose names match pattern, unless they are read-only. `unset *' thus removes all variables unless they are read-only; this is a bad idea. It is not an error for nothing to be unset. unsetenv pattern Removes all environment variables whose names match pattern. `unsetenv *' thus removes all environment variables; this is a bad idea. It is not an error for nothing to be unsetenved. ver [systype [command]] (+) Without arguments, prints SYSTYPE. With systype, sets SYSTYPE to systype. With systype and command, executes command under systype. systype may be `bsd4.3' or `sys5.3'. (Domain/OS only) wait The shell waits for all background jobs. If the shell is interactive, an interrupt will disrupt the wait and cause the shell to print the names and job numbers of all outstanding jobs. warp universe (+) Sets the universe to universe. (Convex/OS only) watchlog (+) An alternate name for the log builtin command (q.v.). Available only if the shell was so compiled; see the version shell variable. where command (+) Reports all known instances of command, including aliases, builtins and executables in path. which command (+) Displays the command that will be executed by the shell after substitutions, path searching, etc. The builtin command is just like which(1), but it correctly reports tcsh aliases and builtins and is 10 to 100 times faster. See also the which- command editor command. while (expr) ... end Executes the commands between the while and the matching end while expr (an expression, as described under Expressions) evaluates non-zero. while and end must appear alone on their input lines. break and continue may be used to terminate or continue the loop prematurely. If the input is a terminal, the user is prompted the first time through the loop as with foreach. Special aliases (+) If set, each of these aliases executes automatically at the indicated time. They are all initially undefined. beepcmd Runs when the shell wants to ring the terminal bell. cwdcmd Runs after every change of working directory. For example, if the user is working on an X window system using xterm(1) and a re-parenting window manager that supports title bars such as twm(1) and does > alias cwdcmd 'echo -n "^[]2;${HOST}:$cwd ^G"' then the shell will change the title of the running xterm(1) to be the name of the host, a colon, and the full current working directory. A fancier way to do that is > alias cwdcmd 'echo -n "^[]2;${HOST}:$cwd^G^[]1;${HOST}^G"' This will put the hostname and working directory on the title bar but only the hostname in the icon manager menu. Note that putting a cd, pushd or popd in cwdcmd may cause an infinite loop. It is the author's opinion that anyone doing so will get what they deserve. jobcmd Runs before each command gets executed, or when the command changes state. This is similar to postcmd, but it does not print builtins. > alias jobcmd 'echo -n "^[]2\;\!#:q^G"' then executing vi foo.c will put the command string in the xterm title bar. helpcommand Invoked by the run-help editor command. The command name for which help is sought is passed as sole argument. For example, if one does > alias helpcommand '\!:1 --help' then the help display of the command itself will be invoked, using the GNU help calling convention. Currently there is no easy way to account for various calling conventions (e.g., the customary Unix `-h'), except by using a table of many commands. periodic Runs every tperiod minutes. This provides a convenient means for checking on common but infrequent changes such as new mail. For example, if one does > set tperiod = 30 > alias periodic checknews then the checknews(1) program runs every 30 minutes. If periodic is set but tperiod is unset or set to 0, periodic behaves like precmd. precmd Runs just before each prompt is printed. For example, if one does > alias precmd date then date(1) runs just before the shell prompts for each command. There are no limits on what precmd can be set to do, but discretion should be used. postcmd Runs before each command gets executed. > alias postcmd 'echo -n "^[]2\;\!#:q^G"' then executing vi foo.c will put the command string in the xterm title bar. shell Specifies the interpreter for executable scripts which do not themselves specify an interpreter. The first word should be a full path name to the desired interpreter (e.g., `/bin/csh' or `/usr/local/bin/tcsh'). Special shell variables The variables described in this section have special meaning to the shell. The shell sets addsuffix, argv, autologout, csubstnonl, command, echo_style, edit, gid, group, home, loginsh, oid, path, prompt, prompt2, prompt3, shell, shlvl, tcsh, term, tty, uid, user and version at startup; they do not change thereafter unless changed by the user. The shell updates cwd, dirstack, owd and status when necessary, and sets logout on logout. The shell synchronizes group, home, path, shlvl, term and user with the environment variables of the same names: whenever the environment variable changes the shell changes the corresponding shell variable to match (unless the shell variable is read-only) and vice versa. Note that although cwd and PWD have identical meanings, they are not synchronized in this manner, and that the shell automatically converts between the different formats of path and PATH. addsuffix (+) If set, filename completion adds `/' to the end of directories and a space to the end of normal files when they are matched exactly. Set by default. afsuser (+) If set, autologout's autolock feature uses its value instead of the local username for kerberos authentication. ampm (+) If set, all times are shown in 12-hour AM/PM format. anyerror (+) This variable selects what is propagated to the value of the status variable. For more information see the description of the status variable below. argv The arguments to the shell. Positional parameters are taken from argv, i.e., `$1' is replaced by `$argv[1]', etc. Set by default, but usually empty in interactive shells. autocorrect (+) If set, the spell-word editor command is invoked automatically before each completion attempt. autoexpand (+) If set, the expand-history editor command is invoked automatically before each completion attempt. If this is set to onlyhistory, then only history will be expanded and a second completion will expand filenames. autolist (+) If set, possibilities are listed after an ambiguous completion. If set to `ambiguous', possibilities are listed only when no new characters are added by completion. autologout (+) The first word is the number of minutes of inactivity before automatic logout. The optional second word is the number of minutes of inactivity before automatic locking. When the shell automatically logs out, it prints `auto-logout', sets the variable logout to `automatic' and exits. When the shell automatically locks, the user is required to enter his password to continue working. Five incorrect attempts result in automatic logout. Set to `60' (automatic logout after 60 minutes, and no locking) by default in login and superuser shells, but not if the shell thinks it is running under a window system (i.e., the DISPLAY environment variable is set), the tty is a pseudo-tty (pty) or the shell was not so compiled (see the version shell variable). See also the afsuser and logout shell variables. autorehash (+) If set, the internal hash table of the contents of the directories in the path variable will be recomputed if a command is not found in the hash table. In addition, the list of available commands will be rebuilt for each command completion or spelling correction attempt if set to `complete' or `correct' respectively; if set to `always', this will be done for both cases. backslash_quote (+) If set, backslashes (`\') always quote `\', `'', and `"'. This may make complex quoting tasks easier, but it can cause syntax errors in csh(1) scripts. catalog The file name of the message catalog. If set, tcsh use `tcsh.${catalog}' as a message catalog instead of default `tcsh'. cdpath A list of directories in which cd should search for subdirectories if they aren't found in the current directory. cdtohome (+) If not set, cd requires a directory name, and will not go to the home directory if it's omitted. This is set by default. color If set, it enables color display for the builtin ls-F and it passes --color=auto to ls. Alternatively, it can be set to only ls-F or only ls to enable color to only one command. Setting it to nothing is equivalent to setting it to (ls-F ls). colorcat If set, it enables color escape sequence for NLS message files. And display colorful NLS messages. command (+) If set, the command which was passed to the shell with the -c flag (q.v.). compat_expr (+) If set, the shell will evaluate expressions right to left, like the original csh. complete (+) If set to `igncase', the completion becomes case insensitive. If set to `enhance', completion ignores case and considers hyphens and underscores to be equivalent; it will also treat periods, hyphens and underscores (`.', `-' and `_') as word separators. If set to `Enhance', completion matches uppercase and underscore characters explicitly and matches lowercase and hyphens in a case-insensitive manner; it will treat periods, hyphens and underscores as word separators. continue (+) If set to a list of commands, the shell will continue the listed commands, instead of starting a new one. continue_args (+) Same as continue, but the shell will execute: echo `pwd` $argv > ~/.<cmd>_pause; %<cmd> correct (+) If set to `cmd', commands are automatically spelling-corrected. If set to `complete', commands are automatically completed. If set to `all', the entire command line is corrected. csubstnonl (+) If set, newlines and carriage returns in command substitution are replaced by spaces. Set by default. cwd The full pathname of the current directory. See also the dirstack and owd shell variables. dextract (+) If set, `pushd +n' extracts the nth directory from the directory stack rather than rotating it to the top. dirsfile (+) The default location in which `dirs -S' and `dirs -L' look for a history file. If unset, ~/.cshdirs is used. Because only ~/.tcshrc is normally sourced before ~/.cshdirs, dirsfile should be set in ~/.tcshrc rather than ~/.login. dirstack (+) An array of all the directories on the directory stack. `$dirstack[1]' is the current working directory, `$dirstack[2]' the first directory on the stack, etc. Note that the current working directory is `$dirstack[1]' but `=0' in directory stack substitutions, etc. One can change the stack arbitrarily by setting dirstack, but the first element (the current working directory) is always correct. See also the cwd and owd shell variables. dspmbyte (+) Has an effect iff 'dspm' is listed as part of the version shell variable. If set to `euc', it enables display and editing EUC- kanji(Japanese) code. If set to `sjis', it enables display and editing Shift-JIS(Japanese) code. If set to `big5', it enables display and editing Big5(Chinese) code. If set to `utf8', it enables display and editing Utf8(Unicode) code. If set to the following format, it enables display and editing of original multi-byte code format: > set dspmbyte = 0000....(256 bytes)....0000 The table requires just 256 bytes. Each character of 256 characters corresponds (from left to right) to the ASCII codes 0x00, 0x01, ... 0xff. Each character is set to number 0,1,2 and 3. Each number has the following meaning: 0 ... not used for multi-byte characters. 1 ... used for the first byte of a multi-byte character. 2 ... used for the second byte of a multi-byte character. 3 ... used for both the first byte and second byte of a multi-byte character. Example: If set to `001322', the first character (means 0x00 of the ASCII code) and second character (means 0x01 of ASCII code) are set to `0'. Then, it is not used for multi-byte characters. The 3rd character (0x02) is set to '1', indicating that it is used for the first byte of a multi-byte character. The 4th character(0x03) is set '3'. It is used for both the first byte and the second byte of a multi-byte character. The 5th and 6th characters (0x04,0x05) are set to '2', indicating that they are used for the second byte of a multi-byte character. The GNU fileutils version of ls cannot display multi-byte filenames without the -N ( --literal ) option. If you are using this version, set the second word of dspmbyte to "ls". If not, for example, "ls-F -l" cannot display multi-byte filenames. Note: This variable can only be used if KANJI and DSPMBYTE has been defined at compile time. dunique (+) If set, pushd removes any instances of name from the stack before pushing it onto the stack. echo If set, each command with its arguments is echoed just before it is executed. For non-builtin commands all expansions occur before echoing. Builtin commands are echoed before command and filename substitution, because these substitutions are then done selectively. Set by the -x command line option. echo_style (+) The style of the echo builtin. May be set to bsd Don't echo a newline if the first argument is `-n'; the default for csh. sysv Recognize backslashed escape sequences in echo strings. both Recognize both the `-n' flag and backslashed escape sequences; the default for tcsh. none Recognize neither. Set by default to the local system default. The BSD and System V options are described in the echo(1) man pages on the appropriate systems. edit (+) If set, the command-line editor is used. Set by default in interactive shells. editors (+) A list of command names for the run-fg-editor editor command to match. If not set, the EDITOR (`ed' if unset) and VISUAL (`vi' if unset) environment variables will be used instead. ellipsis (+) If set, the `%c'/`%.' and `%C' prompt sequences (see the prompt shell variable) indicate skipped directories with an ellipsis (`...') instead of `/<skipped>'. euid (+) The user's effective user ID. euser (+) The first matching passwd entry name corresponding to the effective user ID. fignore (+) Lists file name suffixes to be ignored by completion. filec In tcsh, completion is always used and this variable is ignored by default. If edit is unset, then the traditional csh completion is used. If set in csh, filename completion is used. gid (+) The user's real group ID. globdot (+) If set, wild-card glob patterns will match files and directories beginning with `.' except for `.' and `..' globstar (+) If set, the `**' and `***' file glob patterns will match any string of characters including `/' traversing any existing sub- directories. (e.g. `ls **.c' will list all the .c files in the current directory tree). If used by itself, it will match zero or more sub-directories (e.g. `ls /usr/include/**/time.h' will list any file named `time.h' in the /usr/include directory tree; whereas `ls /usr/include/**time.h' will match any file in the /usr/include directory tree ending in `time.h'). To prevent problems with recursion, the `**' glob-pattern will not descend into a symbolic link containing a directory. To override this, use `***' group (+) The user's group name. highlight If set, the incremental search match (in i-search-back and i- search-fwd) and the region between the mark and the cursor are highlighted in reverse video. Highlighting requires more frequent terminal writes, which introduces extra overhead. If you care about terminal performance, you may want to leave this unset. histchars A string value determining the characters used in History substitution (q.v.). The first character of its value is used as the history substitution character, replacing the default character `!'. The second character of its value replaces the character `^' in quick substitutions. histdup (+) Controls handling of duplicate entries in the history list. If set to `all' only unique history events are entered in the history list. If set to `prev' and the last history event is the same as the current command, then the current command is not entered in the history. If set to `erase' and the same event is found in the history list, that old event gets erased and the current one gets inserted. Note that the `prev' and `all' options renumber history events so there are no gaps. histfile (+) The default location in which `history -S' and `history -L' look for a history file. If unset, ~/.history is used. histfile is useful when sharing the same home directory between different machines, or when saving separate histories on different terminals. Because only ~/.tcshrc is normally sourced before ~/.history, histfile should be set in ~/.tcshrc rather than ~/.login. histlit (+) If set, builtin and editor commands and the savehist mechanism use the literal (unexpanded) form of lines in the history list. See also the toggle-literal-history editor command. history The first word indicates the number of history events to save. The optional second word (+) indicates the format in which history is printed; if not given, `%h\t%T\t%R\n' is used. The format sequences are described below under prompt; note the variable meaning of `%R'. Set to `100' by default. home Initialized to the home directory of the invoker. The filename expansion of `~' refers to this variable. ignoreeof If set to the empty string or `0' and the input device is a terminal, the end-of-file command (usually generated by the user by typing `^D' on an empty line) causes the shell to print `Use "exit" to leave tcsh.' instead of exiting. This prevents the shell from accidentally being killed. Historically this setting exited after 26 successive EOF's to avoid infinite loops. If set to a number n, the shell ignores n - 1 consecutive end-of-files and exits on the nth. (+) If unset, `1' is used, i.e., the shell exits on a single `^D'. implicitcd (+) If set, the shell treats a directory name typed as a command as though it were a request to change to that directory. If set to verbose, the change of directory is echoed to the standard output. This behavior is inhibited in non-interactive shell scripts, or for command strings with more than one word. Changing directory takes precedence over executing a like-named command, but it is done after alias substitutions. Tilde and variable expansions work as expected. inputmode (+) If set to `insert' or `overwrite', puts the editor into that input mode at the beginning of each line. killdup (+) Controls handling of duplicate entries in the kill ring. If set to `all' only unique strings are entered in the kill ring. If set to `prev' and the last killed string is the same as the current killed string, then the current string is not entered in the ring. If set to `erase' and the same string is found in the kill ring, the old string is erased and the current one is inserted. killring (+) Indicates the number of killed strings to keep in memory. Set to `30' by default. If unset or set to less than `2', the shell will only keep the most recently killed string. Strings are put in the killring by the editor commands that delete (kill) strings of text, e.g. backward-delete-word, kill-line, etc, as well as the copy-region-as-kill command. The yank editor command will yank the most recently killed string into the command-line, while yank-pop (see Editor commands) can be used to yank earlier killed strings. listflags (+) If set to `x', `a' or `A', or any combination thereof (e.g., `xA'), they are used as flags to ls-F, making it act like `ls -xF', `ls -Fa', `ls -FA' or a combination (e.g., `ls -FxA'): `a' shows all files (even if they start with a `.'), `A' shows all files but `.' and `..', and `x' sorts across instead of down. If the second word of listflags is set, it is used as the path to `ls(1)'. listjobs (+) If set, all jobs are listed when a job is suspended. If set to `long', the listing is in long format. listlinks (+) If set, the ls-F builtin command shows the type of file to which each symbolic link points. listmax (+) The maximum number of items which the list-choices editor command will list without asking first. listmaxrows (+) The maximum number of rows of items which the list-choices editor command will list without asking first. loginsh (+) Set by the shell if it is a login shell. Setting or unsetting it within a shell has no effect. See also shlvl. logout (+) Set by the shell to `normal' before a normal logout, `automatic' before an automatic logout, and `hangup' if the shell was killed by a hangup signal (see Signal handling). See also the autologout shell variable. mail A list of files and directories to check for incoming mail, optionally preceded by a numeric word. Before each prompt, if 10 minutes have passed since the last check, the shell checks each file and says `You have new mail.' (or, if mail contains multiple files, `You have new mail in name.') if the filesize is greater than zero in size and has a modification time greater than its access time. If you are in a login shell, then no mail file is reported unless it has been modified after the time the shell has started up, to prevent redundant notifications. Most login programs will tell you whether or not you have mail when you log in. If a file specified in mail is a directory, the shell will count each file within that directory as a separate message, and will report `You have n mails.' or `You have n mails in name.' as appropriate. This functionality is provided primarily for those systems which store mail in this manner, such as the Andrew Mail System. If the first word of mail is numeric it is taken as a different mail checking interval, in seconds. Under very rare circumstances, the shell may report `You have mail.' instead of `You have new mail.' matchbeep (+) If set to `never', completion never beeps. If set to `nomatch', it beeps only when there is no match. If set to `ambiguous', it beeps when there are multiple matches. If set to `notunique', it beeps when there is one exact and other longer matches. If unset, `ambiguous' is used. nobeep (+) If set, beeping is completely disabled. See also visiblebell. noclobber If set, restrictions are placed on output redirection to insure that files are not accidentally destroyed and that `>>' redirections refer to existing files, as described in the Input/output section. noding If set, disable the printing of `DING!' in the prompt time specifiers at the change of hour. noglob If set, Filename substitution and Directory stack substitution (q.v.) are inhibited. This is most useful in shell scripts which do not deal with filenames, or after a list of filenames has been obtained and further expansions are not desirable. nokanji (+) If set and the shell supports Kanji (see the version shell variable), it is disabled so that the meta key can be used. nonomatch If set, a Filename substitution or Directory stack substitution (q.v.) which does not match any existing files is left untouched rather than causing an error. It is still an error for the substitution to be malformed, e.g., `echo [' still gives an error. nostat (+) A list of directories (or glob-patterns which match directories; see Filename substitution) that should not be stat(2)ed during a completion operation. This is usually used to exclude directories which take too much time to stat(2), for example /afs. notify If set, the shell announces job completions asynchronously. The default is to present job completions just before printing a prompt. oid (+) The user's real organization ID. (Domain/OS only) owd (+) The old working directory, equivalent to the `-' used by cd and pushd. See also the cwd and dirstack shell variables. padhour If set, enable the printing of padding '0' for hours, in 24 and 12 hour formats. E.G.: 07:45:42 vs. 7:45:42. parseoctal To retain compatibily with older versions numeric variables starting with 0 are not interpreted as octal. Setting this variable enables proper octal parsing. path A list of directories in which to look for executable commands. A null word specifies the current directory. If there is no path variable then only full path names will execute. path is set by the shell at startup from the PATH environment variable or, if PATH does not exist, to a system-dependent default something like `(/usr/local/bin /usr/bsd /bin /usr/bin .)'. The shell may put `.' first or last in path or omit it entirely depending on how it was compiled; see the version shell variable. A shell which is given neither the -c nor the -t option hashes the contents of the directories in path after reading ~/.tcshrc and each time path is reset. If one adds a new command to a directory in path while the shell is active, one may need to do a rehash for the shell to find it. printexitvalue (+) If set and an interactive program exits with a non-zero status, the shell prints `Exit status'. prompt The string which is printed before reading each command from the terminal. prompt may include any of the following formatting sequences (+), which are replaced by the given information: %/ The current working directory. %~ The current working directory, but with one's home directory represented by `~' and other users' home directories represented by `~user' as per Filename substitution. `~user' substitution happens only if the shell has already used `~user' in a pathname in the current session. %c[[0]n], %.[[0]n] The trailing component of the current working directory, or n trailing components if a digit n is given. If n begins with `0', the number of skipped components precede the trailing component(s) in the format `/<skipped>trailing'. If the ellipsis shell variable is set, skipped components are represented by an ellipsis so the whole becomes `...trailing'. `~' substitution is done as in `%~' above, but the `~' component is ignored when counting trailing components. %C Like %c, but without `~' substitution. %h, %!, ! The current history event number. %M The full hostname. %m The hostname up to the first `.'. %S (%s) Start (stop) standout mode. %B (%b) Start (stop) boldfacing mode. %U (%u) Start (stop) underline mode. %t, %@ The time of day in 12-hour AM/PM format. %T Like `%t', but in 24-hour format (but see the ampm shell variable). %p The `precise' time of day in 12-hour AM/PM format, with seconds. %P Like `%p', but in 24-hour format (but see the ampm shell variable). \c c is parsed as in bindkey. ^c c is parsed as in bindkey. %% A single `%'. %n The user name. %N The effective user name. %j The number of jobs. %d The weekday in `Day' format. %D The day in `dd' format. %w The month in `Mon' format. %W The month in `mm' format. %y The year in `yy' format. %Y The year in `yyyy' format. %l The shell's tty. %L Clears from the end of the prompt to end of the display or the end of the line. %$ Expands the shell or environment variable name immediately after the `$'. %# `>' (or the first character of the promptchars shell variable) for normal users, `#' (or the second character of promptchars) for the superuser. %{string%} Includes string as a literal escape sequence. It should be used only to change terminal attributes and should not move the cursor location. This cannot be the last sequence in prompt. %? The return code of the command executed just before the prompt. %R In prompt2, the status of the parser. In prompt3, the corrected string. In history, the history string. `%B', `%S', `%U' and `%{string%}' are available in only eight- bit-clean shells; see the version shell variable. The bold, standout and underline sequences are often used to distinguish a superuser shell. For example, > set prompt = "%m [%h] %B[%@]%b [%/] you rang? " tut [37] [2:54pm] [/usr/accts/sys] you rang? _ If `%t', `%@', `%T', `%p', or `%P' is used, and noding is not set, then print `DING!' on the change of hour (i.e, `:00' minutes) instead of the actual time. Set by default to `%# ' in interactive shells. prompt2 (+) The string with which to prompt in while and foreach loops and after lines ending in `\'. The same format sequences may be used as in prompt (q.v.); note the variable meaning of `%R'. Set by default to `%R? ' in interactive shells. prompt3 (+) The string with which to prompt when confirming automatic spelling correction. The same format sequences may be used as in prompt (q.v.); note the variable meaning of `%R'. Set by default to `CORRECT>%R (y|n|e|a)? ' in interactive shells. promptchars (+) If set (to a two-character string), the `%#' formatting sequence in the prompt shell variable is replaced with the first character for normal users and the second character for the superuser. pushdtohome (+) If set, pushd without arguments does `pushd ~', like cd. pushdsilent (+) If set, pushd and popd do not print the directory stack. recexact (+) If set, completion completes on an exact match even if a longer match is possible. recognize_only_executables (+) If set, command listing displays only files in the path that are executable. Slow. rmstar (+) If set, the user is prompted before `rm *' is executed. rprompt (+) The string to print on the right-hand side of the screen (after the command input) when the prompt is being displayed on the left. It recognizes the same formatting characters as prompt. It will automatically disappear and reappear as necessary, to ensure that command input isn't obscured, and will appear only if the prompt, command input, and itself will fit together on the first line. If edit isn't set, then rprompt will be printed after the prompt and before the command input. savedirs (+) If set, the shell does `dirs -S' before exiting. If the first word is set to a number, at most that many directory stack entries are saved. savehist If set, the shell does `history -S' before exiting. If the first word is set to a number, at most that many lines are saved. (The number should be less than or equal to the number history entries; if it is set to greater than the number of history settings, only history entries will be saved) If the second word is set to `merge', the history list is merged with the existing history file instead of replacing it (if there is one) and sorted by time stamp and the most recent events are retained. If the second word of savehist is `merge' and the third word is set to `lock', the history file update will be serialized with other shell sessions that would possibly like to merge history at exactly the same time. (+) sched (+) The format in which the sched builtin command prints scheduled events; if not given, `%h\t%T\t%R\n' is used. The format sequences are described above under prompt; note the variable meaning of `%R'. shell The file in which the shell resides. This is used in forking shells to interpret files which have execute bits set, but which are not executable by the system. (See the description of Builtin and non-builtin command execution.) Initialized to the (system-dependent) home of the shell. shlvl (+) The number of nested shells. Reset to 1 in login shells. See also loginsh. status The exit status from the last command or backquote expansion, or any command in a pipeline is propagated to status. (This is also the default csh behavior.) This default does not match what POSIX mandates (to return the status of the last command only). To match the POSIX behavior, you need to unset anyerror. If the anyerror variable is unset, the exit status of a pipeline is determined only from the last command in the pipeline, and the exit status of a backquote expansion is not propagated to status. If a command terminated abnormally, then 0200 is added to the status. Builtin commands which fail return exit status `1', all other builtin commands return status `0'. symlinks (+) Can be set to several different values to control symbolic link (`symlink') resolution: If set to `chase', whenever the current directory changes to a directory containing a symbolic link, it is expanded to the real name of the directory to which the link points. This does not work for the user's home directory; this is a bug. If set to `ignore', the shell tries to construct a current directory relative to the current directory before the link was crossed. This means that cding through a symbolic link and then `cd ..'ing returns one to the original directory. This affects only builtin commands and filename completion. If set to `expand', the shell tries to fix symbolic links by actually expanding arguments which look like path names. This affects any command, not just builtins. Unfortunately, this does not work for hard-to-recognize filenames, such as those embedded in command options. Expansion may be prevented by quoting. While this setting is usually the most convenient, it is sometimes misleading and sometimes confusing when it fails to recognize an argument which should be expanded. A compromise is to use `ignore' and use the editor command normalize-path (bound by default to ^X-n) when necessary. Some examples are in order. First, let's set up some play directories: > cd /tmp > mkdir from from/src to > ln -s from/src to/dst Here's the behavior with symlinks unset, > cd /tmp/to/dst; echo $cwd /tmp/to/dst > cd ..; echo $cwd /tmp/from here's the behavior with symlinks set to `chase', > cd /tmp/to/dst; echo $cwd /tmp/from/src > cd ..; echo $cwd /tmp/from here's the behavior with symlinks set to `ignore', > cd /tmp/to/dst; echo $cwd /tmp/to/dst > cd ..; echo $cwd /tmp/to and here's the behavior with symlinks set to `expand'. > cd /tmp/to/dst; echo $cwd /tmp/to/dst > cd ..; echo $cwd /tmp/to > cd /tmp/to/dst; echo $cwd /tmp/to/dst > cd ".."; echo $cwd /tmp/from > /bin/echo .. /tmp/to > /bin/echo ".." .. Note that `expand' expansion 1) works just like `ignore' for builtins like cd, 2) is prevented by quoting, and 3) happens before filenames are passed to non-builtin commands. tcsh (+) The version number of the shell in the format `R.VV.PP', where `R' is the major release number, `VV' the current version and `PP' the patchlevel. term The terminal type. Usually set in ~/.login as described under Startup and shutdown. time If set to a number, then the time builtin (q.v.) executes automatically after each command which takes more than that many CPU seconds. If there is a second word, it is used as a format string for the output of the time builtin. (u) The following sequences may be used in the format string: %U The time the process spent in user mode in cpu seconds. %S The time the process spent in kernel mode in cpu seconds. %E The elapsed (wall clock) time in seconds. %P The CPU percentage computed as (%U + %S) / %E. %W Number of times the process was swapped. %X The average amount in (shared) text space used in Kbytes. %D The average amount in (unshared) data/stack space used in Kbytes. %K The total space used (%X + %D) in Kbytes. %M The maximum memory the process had in use at any time in Kbytes. %F The number of major page faults (page needed to be brought from disk). %R The number of minor page faults. %I The number of input operations. %O The number of output operations. %r The number of socket messages received. %s The number of socket messages sent. %k The number of signals received. %w The number of voluntary context switches (waits). %c The number of involuntary context switches. Only the first four sequences are supported on systems without BSD resource limit functions. The default time format is `%Uu %Ss %E %P %X+%Dk %I+%Oio %Fpf+%Ww' for systems that support resource usage reporting and `%Uu %Ss %E %P' for systems that do not. Under Sequent's DYNIX/ptx, %X, %D, %K, %r and %s are not available, but the following additional sequences are: %Y The number of system calls performed. %Z The number of pages which are zero-filled on demand. %i The number of times a process's resident set size was increased by the kernel. %d The number of times a process's resident set size was decreased by the kernel. %l The number of read system calls performed. %m The number of write system calls performed. %p The number of reads from raw disk devices. %q The number of writes to raw disk devices. and the default time format is `%Uu %Ss %E %P %I+%Oio %Fpf+%Ww'. Note that the CPU percentage can be higher than 100% on multi-processors. tperiod (+) The period, in minutes, between executions of the periodic special alias. tty (+) The name of the tty, or empty if not attached to one. uid (+) The user's real user ID. user The user's login name. verbose If set, causes the words of each command to be printed, after history substitution (if any). Set by the -v command line option. version (+) The version ID stamp. It contains the shell's version number (see tcsh), origin, release date, vendor, operating system and machine (see VENDOR, OSTYPE and MACHTYPE) and a comma-separated list of options which were set at compile time. Options which are set by default in the distribution are noted. 8b The shell is eight bit clean; default 7b The shell is not eight bit clean wide The shell is multibyte encoding clean (like UTF-8) nls The system's NLS is used; default for systems with NLS lf Login shells execute /etc/csh.login before instead of after /etc/csh.cshrc and ~/.login before instead of after ~/.tcshrc and ~/.history. dl `.' is put last in path for security; default nd `.' is omitted from path for security vi vi(1)-style editing is the default rather than emacs(1)-style dtr Login shells drop DTR when exiting bye bye is a synonym for logout and log is an alternate name for watchlog al autologout is enabled; default kan Kanji is used if appropriate according to locale settings, unless the nokanji shell variable is set sm The system's malloc(3) is used hb The `#!<program> <args>' convention is emulated when executing shell scripts ng The newgrp builtin is available rh The shell attempts to set the REMOTEHOST environment variable afs The shell verifies your password with the kerberos server if local authentication fails. The afsuser shell variable or the AFSUSER environment variable override your local username if set. An administrator may enter additional strings to indicate differences in the local version. vimode (+) If unset, various key bindings change behavior to be more emacs(1)-style: word boundaries are determined by wordchars versus other characters. If set, various key bindings change behavior to be more vi(1)-style: word boundaries are determined by wordchars versus whitespace versus other characters; cursor behavior depends upon current vi mode (command, delete, insert, replace). This variable is unset by bindkey -e and set by bindkey -v. vimode may be explicitly set or unset by the user after those bindkey operations if required. visiblebell (+) If set, a screen flash is used rather than the audible bell. See also nobeep. watch (+) A list of user/terminal pairs to watch for logins and logouts. If either the user is `any' all terminals are watched for the given user and vice versa. Setting watch to `(any any)' watches all users and terminals. For example, set watch = (george ttyd1 any console $user any) reports activity of the user `george' on ttyd1, any user on the console, and oneself (or a trespasser) on any terminal. Logins and logouts are checked every 10 minutes by default, but the first word of watch can be set to a number to check every so many minutes. For example, set watch = (1 any any) reports any login/logout once every minute. For the impatient, the log builtin command triggers a watch report at any time. All current logins are reported (as with the log builtin) when watch is first set. The who shell variable controls the format of watch reports. who (+) The format string for watch messages. The following sequences are replaced by the given information: %n The name of the user who logged in/out. %a The observed action, i.e., `logged on', `logged off' or `replaced olduser on'. %l The terminal (tty) on which the user logged in/out. %M The full hostname of the remote host, or `local' if the login/logout was from the local host. %m The hostname of the remote host up to the first `.'. The full name is printed if it is an IP address or an X Window System display. %M and %m are available on only systems that store the remote hostname in /etc/utmp. If unset, `%n has %a %l from %m.' is used, or `%n has %a %l.' on systems which don't store the remote hostname. wordchars (+) A list of non-alphanumeric characters to be considered part of a word by the forward-word, backward-word etc., editor commands. If unset, the default value is determined based on the state of vimode: if vimode is unset, `*?_-.[]~=' is used as the default; if vimode is set, `_' is used as the default. ENVIRONMENT AFSUSER (+) Equivalent to the afsuser shell variable. COLUMNS The number of columns in the terminal. See Terminal management. DISPLAY Used by X Window System (see X(1)). If set, the shell does not set autologout (q.v.). EDITOR The pathname to a default editor. Used by the run-fg-editor editor command if the the editors shell variable is unset. See also the VISUAL environment variable. GROUP (+) Equivalent to the group shell variable. HOME Equivalent to the home shell variable. HOST (+) Initialized to the name of the machine on which the shell is running, as determined by the gethostname(2) system call. HOSTTYPE (+) Initialized to the type of machine on which the shell is running, as determined at compile time. This variable is obsolete and will be removed in a future version. HPATH (+) A colon-separated list of directories in which the run-help editor command looks for command documentation. LANG Gives the preferred character environment. See Native Language System support. LC_CTYPE If set, only ctype character handling is changed. See Native Language System support. LINES The number of lines in the terminal. See Terminal management. LS_COLORS The format of this variable is reminiscent of the termcap(5) file format; a colon-separated list of expressions of the form "xx=string", where "xx" is a two-character variable name. The variables with their associated defaults are: no 0 Normal (non-filename) text fi 0 Regular file di 01;34 Directory ln 01;36 Symbolic link pi 33 Named pipe (FIFO) so 01;35 Socket do 01;35 Door bd 01;33 Block device cd 01;32 Character device ex 01;32 Executable file mi (none) Missing file (defaults to fi) or (none) Orphaned symbolic link (defaults to ln) lc ^[[ Left code rc m Right code ec (none) End code (replaces lc+no+rc) You need to include only the variables you want to change from the default. File names can also be colorized based on filename extension. This is specified in the LS_COLORS variable using the syntax "*ext=string". For example, using ISO 6429 codes, to color all C-language source files blue you would specify "*.c=34". This would color all files ending in .c in blue (34) color. Control characters can be written either in C-style-escaped notation, or in stty-like ^-notation. The C-style notation adds ^[ for Escape, _ for a normal space character, and ? for Delete. In addition, the ^[ escape character can be used to override the default interpretation of ^[, ^, : and =. Each file will be written as <lc> <color-code> <rc> <filename> <ec>. If the <ec> code is undefined, the sequence <lc> <no> <rc> will be used instead. This is generally more convenient to use, but less general. The left, right and end codes are provided so you don't have to type common parts over and over again and to support weird terminals; you will generally not need to change them at all unless your terminal does not use ISO 6429 color sequences but a different system. If your terminal does use ISO 6429 color codes, you can compose the type codes (i.e., all except the lc, rc, and ec codes) from numerical commands separated by semicolons. The most common commands are: 0 to restore default color 1 for brighter colors 4 for underlined text 5 for flashing text 30 for black foreground 31 for red foreground 32 for green foreground 33 for yellow (or brown) foreground 34 for blue foreground 35 for purple foreground 36 for cyan foreground 37 for white (or gray) foreground 40 for black background 41 for red background 42 for green background 43 for yellow (or brown) background 44 for blue background 45 for purple background 46 for cyan background 47 for white (or gray) background Not all commands will work on all systems or display devices. A few terminal programs do not recognize the default end code properly. If all text gets colorized after you do a directory listing, try changing the no and fi codes from 0 to the numerical codes for your standard fore- and background colors. MACHTYPE (+) The machine type (microprocessor class or machine model), as determined at compile time. NOREBIND (+) If set, printable characters are not rebound to self-insert- command. See Native Language System support. OSTYPE (+) The operating system, as determined at compile time. PATH A colon-separated list of directories in which to look for executables. Equivalent to the path shell variable, but in a different format. PWD (+) Equivalent to the cwd shell variable, but not synchronized to it; updated only after an actual directory change. REMOTEHOST (+) The host from which the user has logged in remotely, if this is the case and the shell is able to determine it. Set only if the shell was so compiled; see the version shell variable. SHLVL (+) Equivalent to the shlvl shell variable. SYSTYPE (+) The current system type. (Domain/OS only) TERM Equivalent to the term shell variable. TERMCAP The terminal capability string. See Terminal management. USER Equivalent to the user shell variable. VENDOR (+) The vendor, as determined at compile time. VISUAL The pathname to a default full-screen editor. Used by the run- fg-editor editor command if the the editors shell variable is unset. See also the EDITOR environment variable. FILES /etc/csh.cshrc Read first by every shell. ConvexOS, Stellix and Intel use /etc/cshrc and NeXTs use /etc/cshrc.std. A/UX, AMIX, Cray and IRIX have no equivalent in csh(1), but read this file in tcsh anyway. Solaris 2.x does not have it either, but tcsh reads /etc/.cshrc. (+) /etc/csh.login Read by login shells after /etc/csh.cshrc. ConvexOS, Stellix and Intel use /etc/login, NeXTs use /etc/login.std, Solaris 2.x uses /etc/.login and A/UX, AMIX, Cray and IRIX use /etc/cshrc. ~/.tcshrc (+) Read by every shell after /etc/csh.cshrc or its equivalent. ~/.cshrc Read by every shell, if ~/.tcshrc doesn't exist, after /etc/csh.cshrc or its equivalent. This manual uses `~/.tcshrc' to mean `~/.tcshrc or, if ~/.tcshrc is not found, ~/.cshrc'. ~/.history Read by login shells after ~/.tcshrc if savehist is set, but see also histfile. ~/.login Read by login shells after ~/.tcshrc or ~/.history. The shell may be compiled to read ~/.login before instead of after ~/.tcshrc and ~/.history; see the version shell variable. ~/.cshdirs (+) Read by login shells after ~/.login if savedirs is set, but see also dirsfile. /etc/csh.logout Read by login shells at logout. ConvexOS, Stellix and Intel use /etc/logout and NeXTs use /etc/logout.std. A/UX, AMIX, Cray and IRIX have no equivalent in csh(1), but read this file in tcsh anyway. Solaris 2.x does not have it either, but tcsh reads /etc/.logout. (+) ~/.logout Read by login shells at logout after /etc/csh.logout or its equivalent. /bin/sh Used to interpret shell scripts not starting with a `#'. /tmp/sh* Temporary file for `<<'. /etc/passwd Source of home directories for `~name' substitutions. The order in which startup files are read may differ if the shell was so compiled; see Startup and shutdown and the version shell variable. NEW FEATURES (+) This manual describes tcsh as a single entity, but experienced csh(1) users will want to pay special attention to tcsh's new features. A command-line editor, which supports emacs(1)-style or vi(1)-style key bindings. See The command-line editor and Editor commands. Programmable, interactive word completion and listing. See Completion and listing and the complete and uncomplete builtin commands. Spelling correction (q.v.) of filenames, commands and variables. Editor commands (q.v.) which perform other useful functions in the middle of typed commands, including documentation lookup (run-help), quick editor restarting (run-fg-editor) and command resolution (which- command). An enhanced history mechanism. Events in the history list are time- stamped. See also the history command and its associated shell variables, the previously undocumented `#' event specifier and new modifiers under History substitution, the *-history, history-search-*, i-search-*, vi-search-* and toggle-literal-history editor commands and the histlit shell variable. Enhanced directory parsing and directory stack handling. See the cd, pushd, popd and dirs commands and their associated shell variables, the description of Directory stack substitution, the dirstack, owd and symlinks shell variables and the normalize-command and normalize-path editor commands. Negation in glob-patterns. See Filename substitution. New File inquiry operators (q.v.) and a filetest builtin which uses them. A variety of Automatic, periodic and timed events (q.v.) including scheduled events, special aliases, automatic logout and terminal locking, command timing and watching for logins and logouts. Support for the Native Language System (see Native Language System support), OS variant features (see OS variant support and the echo_style shell variable) and system-dependent file locations (see FILES). Extensive terminal-management capabilities. See Terminal management. New builtin commands including builtins, hup, ls-F, newgrp, printenv, which and where (q.v.). New variables that make useful information easily available to the shell. See the gid, loginsh, oid, shlvl, tcsh, tty, uid and version shell variables and the HOST, REMOTEHOST, VENDOR, OSTYPE and MACHTYPE environment variables. A new syntax for including useful information in the prompt string (see prompt), and special prompts for loops and spelling correction (see prompt2 and prompt3). Read-only variables. See Variable substitution. BUGS When a suspended command is restarted, the shell prints the directory it started in if this is different from the current directory. This can be misleading (i.e., wrong) as the job may have changed directories internally. Shell builtin functions are not stoppable/restartable. Command sequences of the form `a ; b ; c' are also not handled gracefully when stopping is attempted. If you suspend `b', the shell will then immediately execute `c'. This is especially noticeable if this expansion results from an alias. It suffices to place the sequence of commands in ()'s to force it to a subshell, i.e., `( a ; b ; c )'. Control over tty output after processes are started is primitive; perhaps this will inspire someone to work on a good virtual terminal interface. In a virtual terminal interface much more interesting things could be done with output control. Alias substitution is most often used to clumsily simulate shell procedures; shell procedures should be provided rather than aliases. Control structures should be parsed rather than being recognized as built-in commands. This would allow control commands to be placed anywhere, to be combined with `|', and to be used with `&' and `;' metasyntax. foreach doesn't ignore here documents when looking for its end. It should be possible to use the `:' modifiers on the output of command substitutions. The screen update for lines longer than the screen width is very poor if the terminal cannot move the cursor up (i.e., terminal type `dumb'). HPATH and NOREBIND don't need to be environment variables. Glob-patterns which do not use `?', `*' or `[]' or which use `{}' or `~' are not negated correctly. The single-command form of if does output redirection even if the expression is false and the command is not executed. ls-F includes file identification characters when sorting filenames and does not handle control characters in filenames well. It cannot be interrupted. Command substitution supports multiple commands and conditions, but not cycles or backward gotos. Report bugs at https://bugs.astron.com/, preferably with fixes. If you want to help maintain and test tcsh, add yourself to the mailing list in https://mailman.astron.com/. THE T IN TCSH In 1964, DEC produced the PDP-6. The PDP-10 was a later re- implementation. It was re-christened the DECsystem-10 in 1970 or so when DEC brought out the second model, the KI10. TENEX was created at Bolt, Beranek & Newman (a Cambridge, Massachusetts think tank) in 1972 as an experiment in demand-paged virtual memory operating systems. They built a new pager for the DEC PDP-10 and created the OS to go with it. It was extremely successful in academia. In 1975, DEC brought out a new model of the PDP-10, the KL10; they intended to have only a version of TENEX, which they had licensed from BBN, for the new box. They called their version TOPS-20 (their capitalization is trademarked). A lot of TOPS-10 users (`The OPerating System for PDP-10') objected; thus DEC found themselves supporting two incompatible systems on the same hardware--but then there were 6 on the PDP-11! TENEX, and TOPS-20 to version 3, had command completion via a user- code-level subroutine library called ULTCMD. With version 3, DEC moved all that capability and more into the monitor (`kernel' for you Unix types), accessed by the COMND% JSYS (`Jump to SYStem' instruction, the supervisor call mechanism [are my IBM roots also showing?]). The creator of tcsh was impressed by this feature and several others of TENEX and TOPS-20, and created a version of csh which mimicked them. LIMITATIONS The system limits argument lists to ARG_MAX characters. The number of arguments to a command which involves filename expansion is limited to 1/6th the number of characters allowed in an argument list. Command substitutions may substitute no more characters than are allowed in an argument list. To detect looping, the shell restricts the number of alias substitutions on a single line to 20. SEE ALSO csh(1), emacs(1), ls(1), newgrp(1), sh(1), setpath(1), stty(1), su(1), tset(1), vi(1), x(1), access(2), execve(2), fork(2), killpg(2), pipe(2), setrlimit(2), sigvec(2), stat(2), umask(2), vfork(2), wait(2), malloc(3), setlocale(3), tty(4), a.out(5), termcap(5), environ(7), termio(7), Introduction to the C Shell VERSION This manual documents tcsh 6.21.00 (Astron) 2019-05-08. AUTHORS William Joy Original author of csh(1) J.E. Kulp, IIASA, Laxenburg, Austria Job control and directory stack features Ken Greer, HP Labs, 1981 File name completion Mike Ellis, Fairchild, 1983 Command name recognition/completion Paul Placeway, Ohio State CIS Dept., 1983-1993 Command line editor, prompt routines, new glob syntax and numerous fixes and speedups Karl Kleinpaste, CCI 1983-4 Special aliases, directory stack extraction stuff, login/logout watch, scheduled events, and the idea of the new prompt format Rayan Zachariassen, University of Toronto, 1984 ls-F and which builtins and numerous bug fixes, modifications and speedups Chris Kingsley, Caltech Fast storage allocator routines Chris Grevstad, TRW, 1987 Incorporated 4.3BSD csh into tcsh Christos S. Zoulas, Cornell U. EE Dept., 1987-94 Ports to HPUX, SVR2 and SVR3, a SysV version of getwd.c, SHORT_STRINGS support and a new version of sh.glob.c James J Dempsey, BBN, and Paul Placeway, OSU, 1988 A/UX port Daniel Long, NNSC, 1988 wordchars Patrick Wolfe, Kuck and Associates, Inc., 1988 vi mode cleanup David C Lawrence, Rensselaer Polytechnic Institute, 1989 autolist and ambiguous completion listing Alec Wolman, DEC, 1989 Newlines in the prompt Matt Landau, BBN, 1989 ~/.tcshrc Ray Moody, Purdue Physics, 1989 Magic space bar history expansion Mordechai ????, Intel, 1989 printprompt() fixes and additions Kazuhiro Honda, Dept. of Computer Science, Keio University, 1989 Automatic spelling correction and prompt3 Per Hedeland, Ellemtel, Sweden, 1990- Various bugfixes, improvements and manual updates Hans J. Albertsson (Sun Sweden) ampm, settc and telltc Michael Bloom Interrupt handling fixes Michael Fine, Digital Equipment Corp Extended key support Eric Schnoebelen, Convex, 1990 Convex support, lots of csh bug fixes, save and restore of directory stack Ron Flax, Apple, 1990 A/UX 2.0 (re)port Dan Oscarsson, LTH Sweden, 1990 NLS support and simulated NLS support for non NLS sites, fixes Johan Widen, SICS Sweden, 1990 shlvl, Mach support, correct-line, 8-bit printing Matt Day, Sanyo Icon, 1990 POSIX termio support, SysV limit fixes Jaap Vermeulen, Sequent, 1990-91 Vi mode fixes, expand-line, window change fixes, Symmetry port Martin Boyer, Institut de recherche d'Hydro-Quebec, 1991 autolist beeping options, modified the history search to search for the whole string from the beginning of the line to the cursor. Scott Krotz, Motorola, 1991 Minix port David Dawes, Sydney U. Australia, Physics Dept., 1991 SVR4 job control fixes Jose Sousa, Interactive Systems Corp., 1991 Extended vi fixes and vi delete command Marc Horowitz, MIT, 1991 ANSIfication fixes, new exec hashing code, imake fixes, where Bruce Sterling Woodcock, sterling@netcom.com, 1991-1995 ETA and Pyramid port, Makefile and lint fixes, ignoreeof=n addition, and various other portability changes and bug fixes Jeff Fink, 1992 complete-word-fwd and complete-word-back Harry C. Pulley, 1992 Coherent port Andy Phillips, Mullard Space Science Lab U.K., 1992 VMS-POSIX port Beto Appleton, IBM Corp., 1992 Walking process group fixes, csh bug fixes, POSIX file tests, POSIX SIGHUP Scott Bolte, Cray Computer Corp., 1992 CSOS port Kaveh R. Ghazi, Rutgers University, 1992 Tek, m88k, Titan and Masscomp ports and fixes. Added autoconf support. Mark Linderman, Cornell University, 1992 OS/2 port Mika Liljeberg, liljeber@kruuna.Helsinki.FI, 1992 Linux port Tim P. Starrin, NASA Langley Research Center Operations, 1993 Read-only variables Dave Schweisguth, Yale University, 1993-4 New man page and tcsh.man2html Larry Schwimmer, Stanford University, 1993 AFS and HESIOD patches Luke Mewburn, RMIT University, 1994-6 Enhanced directory printing in prompt, added ellipsis and rprompt. Edward Hutchins, Silicon Graphics Inc., 1996 Added implicit cd. Martin Kraemer, 1997 Ported to Siemens Nixdorf EBCDIC machine Amol Deshpande, Microsoft, 1997 Ported to WIN32 (Windows/95 and Windows/NT); wrote all the missing library and message catalog code to interface to Windows. Taga Nayuta, 1998 Color ls additions. THANKS TO Bryan Dunlap, Clayton Elwell, Karl Kleinpaste, Bob Manson, Steve Romig, Diana Smetters, Bob Sutterfield, Mark Verber, Elizabeth Zwicky and all the other people at Ohio State for suggestions and encouragement All the people on the net, for putting up with, reporting bugs in, and suggesting new additions to each and every version Richard M. Alderson III, for writing the `T in tcsh' section Astron 6.21.00 8 May 2019 TCSH(1)
tcsh - C shell with file name completion and command line editing
tcsh [-bcdefFimnqstvVxX] [-Dname[=value]] [arg ...] tcsh -l
null
null
wait4path
The wait4path program simply checks to see if the given path exists, and if so, it exits. Otherwise, it sleeps until the mount table is updated and checks again. The program will loop indefinitely until the path shows up in the file system namespace. Darwin December 14, 2013 Darwin
wait4path – wait for given path to show up in the namespace
wait4path ⟨path⟩
null
null
unlink
The rm utility attempts to remove the non-directory type files specified on the command line. If the permissions of the file do not permit writing, and the standard input device is a terminal, the user is prompted (on the standard error output) for confirmation. The options are as follows: -d Attempt to remove directories as well as other types of files. -f Attempt to remove the files without prompting for confirmation, regardless of the file's permissions. If the file does not exist, do not display a diagnostic message or modify the exit status to reflect an error. The -f option overrides any previous -i options. -i Request confirmation before attempting to remove each file, regardless of the file's permissions, or whether or not the standard input device is a terminal. The -i option overrides any previous -f options. -I Request confirmation once if more than three files are being removed or if a directory is being recursively removed. This is a far less intrusive option than -i yet provides almost the same level of protection against mistakes. -P This flag has no effect. It is kept only for backwards compatibility with 4.4BSD-Lite2. -R Attempt to remove the file hierarchy rooted in each file argument. The -R option implies the -d option. If the -i option is specified, the user is prompted for confirmation before each directory's contents are processed (as well as before the attempt is made to remove the directory). If the user does not respond affirmatively, the file hierarchy rooted in that directory is skipped. -r Equivalent to -R. -v Be verbose when deleting files, showing them as they are removed. -W Attempt to undelete the named files. Currently, this option can only be used to recover files covered by whiteouts in a union file system (see undelete(2)). -x When removing a hierarchy, do not cross mount points. The rm utility removes symbolic links, not the files referenced by the links. It is an error to attempt to remove the files /, . or ... When the utility is called as unlink, only one argument, which must not be a directory, may be supplied. No options may be supplied in this simple mode of operation, which performs an unlink(2) operation on the passed argument. However, the usual option-end delimiter, --, may optionally precede the argument. EXIT STATUS The rm utility exits 0 if all of the named files or file hierarchies were removed, or if the -f option was specified and all of the existing files or file hierarchies were removed. If an error occurs, rm exits with a value >0. NOTES The rm command uses getopt(3) to parse its arguments, which allows it to accept the ‘--’ option which will cause it to stop processing flag options at that point. This will allow the removal of file names that begin with a dash (‘-’). For example: rm -- -filename The same behavior can be obtained by using an absolute or relative path reference. For example: rm /home/user/-filename rm ./-filename
rm, unlink – remove directory entries
rm [-f | -i] [-dIRrvWx] file ... unlink [--] file
null
Recursively remove all files contained within the foobar directory hierarchy: $ rm -rf foobar Any of these commands will remove the file -f: $ rm -- -f $ rm ./-f $ unlink -f COMPATIBILITY The rm utility differs from historical implementations in that the -f option only masks attempts to remove non-existent files instead of masking a large variety of errors. The -v option is non-standard and its use in scripts is not recommended. Also, historical BSD implementations prompted on the standard output, not the standard error output. The -P option does not have any effect as of FreeBSD 13 and may be removed in the future. SEE ALSO chflags(1), rmdir(1), undelete(2), unlink(2), fts(3), getopt(3), symlink(7) STANDARDS The rm command conforms to. The simplified unlink command conforms to Version 2 of the Single UNIX Specification (“SUSv2”). HISTORY A rm command appeared in Version 1 AT&T UNIX. BUGS The -P option assumes that the underlying file system is a fixed-block file system. In addition, only regular files are overwritten, other types of files are not. macOS 14.5 November 10, 2018 macOS 14.5
sleep
The sleep command suspends execution for a minimum of seconds. If the sleep command receives a signal, it takes the standard action. When the SIGINFO signal is received, the estimate of the amount of seconds left to sleep is printed on the standard output. IMPLEMENTATION NOTES The SIGALRM signal is not handled specially by this implementation. The sleep command allows and honors a non-integer number of seconds to sleep in any form acceptable by strtod(3). This is a non-portable extension, but is also implemented in GNU sh-utils since version 2.0a (released in 2002). EXIT STATUS The sleep utility exits 0 on success, and >0 if an error occurs.
sleep – suspend execution for an interval of time
sleep seconds
null
To schedule the execution of a command for x number seconds later (with csh(1)): (sleep 1800; sh command_file >& errors)& This incantation would wait a half hour before running the script command_file. (See the at(1) utility.) To reiteratively run a command (with the csh(1)): while (1) if (! -r zzz.rawdata) then sleep 300 else foreach i (`ls *.rawdata`) sleep 70 awk -f collapse_data $i >> results end break endif end The scenario for a script such as this might be: a program currently running is taking longer than expected to process a series of files, and it would be nice to have another program start processing the files created by the first program as soon as it is finished (when zzz.rawdata is created). The script checks every five minutes for the file zzz.rawdata, when the file is found, then another portion processing is done courteously by sleeping for 70 seconds in between each awk job. SEE ALSO nanosleep(2), sleep(3) STANDARDS The sleep command is expected to be IEEE Std 1003.2 (“POSIX.2”) compatible. HISTORY A sleep command appeared in Version 4 AT&T UNIX. macOS 14.5 December 31, 2020 macOS 14.5
stty
The stty utility sets or reports on terminal characteristics for the device that is its standard input. If no options or arguments are specified, it reports the settings of a subset of characteristics as well as additional ones if they differ from their default values. Otherwise it modifies the terminal state according to the specified arguments. Some combinations of arguments are mutually exclusive on some terminal types. The following options are available: -a Display all the current settings for the terminal to standard output as per IEEE Std 1003.2 (“POSIX.2”). -e Display all the current settings for the terminal to standard output in the traditional BSD ``all'' and ``everything'' formats. -f Open and use the terminal named by file rather than using standard input. The file is opened using the O_NONBLOCK flag of open(), making it possible to set or display settings on a terminal that might otherwise block on the open. -g Display all the current settings for the terminal to standard output in a form that may be used as an argument to a subsequent invocation of stty to restore the current terminal state as per IEEE Std 1003.2 (“POSIX.2”). The following arguments are available to set the terminal characteristics: Control Modes: Control mode flags affect hardware characteristics associated with the terminal. This corresponds to the c_cflag in the termios structure. number Set terminal baud rate to the number given, if possible. If the baud rate is set to zero, modem control is no longer asserted. clocal (-clocal) Assume a line without (with) modem control. cread (-cread) Enable (disable) the receiver. crtscts (-crtscts) Enable (disable) RTS/CTS flow control. cs5 cs6 cs7 cs8 Select character size, if possible. cstopb (-cstopb) Use two (one) stop bits per character. hup (-hup) Same as hupcl (-hupcl). hupcl (-hupcl) Stop asserting modem control (do not stop asserting modem control) on last close. ispeed number Set terminal input baud rate to the number given, if possible. If the input baud rate is set to zero, the input baud rate is set to the value of the output baud rate. ospeed number Set terminal output baud rate to the number given, if possible. If the output baud rate is set to zero, modem control is no longer asserted. parenb (-parenb) Enable (disable) parity generation and detection. parodd (-parodd) Select odd (even) parity. speed number This sets both ispeed and ospeed to number. Input Modes: This corresponds to the c_iflag in the termios structure. brkint (-brkint) Signal (do not signal) INTR on break. icrnl (-icrnl) Map (do not map) CR to NL on input. ignbrk (-ignbrk) Ignore (do not ignore) break on input. igncr (-igncr) Ignore (do not ignore) CR on input. ignpar (-ignpar) Ignore (do not ignore) characters with parity errors. imaxbel (-imaxbel) The system imposes a limit of MAX_INPUT (currently 255) characters in the input queue. If imaxbel is set and the input queue limit has been reached, subsequent input causes the system to send an ASCII BEL character to the output queue (the terminal beeps at you). Otherwise, if imaxbel is unset and the input queue is full, the next input character causes the entire input and output queues to be discarded. inlcr (-inlcr) Map (do not map) NL to CR on input. inpck (-inpck) Enable (disable) input parity checking. istrip (-istrip) Strip (do not strip) input characters to seven bits. iutf8 (-iutf8) Assume input characters are UTF-8 encoded. ixany (-ixany) Allow any character (allow only START) to restart output. ixoff (-ixoff) Request that the system send (not send) START/STOP characters when the input queue is nearly empty/full. ixon (-ixon) Enable (disable) START/STOP output control. Output from the system is stopped when the system receives STOP and started when the system receives START, or if ixany is set, any character restarts output. parmrk (-parmrk) Mark (do not mark) characters with parity errors. Output Modes: This corresponds to the c_oflag of the termios structure. bs0 bs1 Select the style of delay for backspaces (e.g., set BSDLY to BS0). cr0 cr1 cr2 cr3 Select the style of delay for carriage returns (e.g., set CRDLY to CR0). ff0 ff1 Select the style of delay for form feeds (e.g., set FFDLY to FF0). nl0 nl1 Select the style of delay for newlines (e.g., set NLDLY to NL0). ocrnl (-ocrnl) Map (do not map) carriage return to newline on output. ofdel (-odell) Use DELs (NULs) as fill characters. ofill (-ofill) Use fill characters (use timing) for delays. onlcr (-onlcr) Map (do not map) NL to CR-NL on output. onlret (-onlret) On the terminal, NL performs (does not perform) the CR function. onocr (-onocr) Do not (do) output CRs at column zero. opost (-opost) Post-process output (do not post-process output; ignore all other output modes). oxtabs (-oxtabs) Expand (do not expand) tabs to spaces on output. tab0 tab1 tab2 tab3 Select the style of delay for horizontal tabs (e.g., set TABDLY to TAB0). tabs (-tabs) Same as tab0 (tab3). vt0 vt1 Select the style of delay for vertical tabs (e.g., set VTDLY to VT0). Local Modes: Local mode flags (lflags) affect various and sundry characteristics of terminal processing. Historically the term "local" pertained to new job control features implemented by Jim Kulp on a Pdp 11/70 at IIASA. Later, the driver ran on the first VAX at Evans Hall, UC Berkeley, where the job control details were greatly modified, but the structure definitions and names remained essentially unchanged. The second interpretation of the 'l' in lflag is ``line discipline flag'', which corresponds to the c_lflag of the termios structure. altwerase (-altwerase) Use (do not use) an alternate word erase algorithm when processing WERASE characters. This alternate algorithm considers sequences of alphanumeric/underscores as words. It also skips the first preceding character in its classification (as a convenience, since the one preceding character could have been erased with simply an ERASE character.) echo (-echo) Echo back (do not echo back) every character typed. echoctl (-echoctl) If echoctl is set, echo control characters as ^X. Otherwise, control characters echo as themselves. echoe (-echoe) The ERASE character shall (shall not) visually erase the last character in the current line from the display, if possible. echok (-echok) Echo (do not echo) NL after KILL character. echoke (-echoke) The KILL character shall (shall not) visually erase the current line from the display, if possible. echonl (-echonl) Echo (do not echo) NL, even if echo is disabled. echoprt (-echoprt) For printing terminals. If set, echo erased characters backwards within ``\'' and ``/''. Otherwise, disable this feature. flusho (-flusho) Indicates output is (is not) being discarded. icanon (-icanon) Enable (disable) canonical input (ERASE and KILL processing). iexten (-iexten) Enable (disable) any implementation-defined special control characters that are not currently controlled by icanon, isig, ixoff, or ixon. isig (-isig) Enable (disable) the checking of characters against the special control characters INTR, QUIT, and SUSP. mdmbuf (-mdmbuf) If set, flow control output based on condition of Carrier Detect. Otherwise, writes return an error if Carrier Detect is low (and Carrier is not being ignored with the CLOCAL flag.) noflsh (-noflsh) Disable (enable) flush after INTR, QUIT, or SUSP. pendin (-pendin) Indicates input is (is not) pending after a switch from non- canonical to canonical mode and will be re-input when a read becomes pending or more input arrives. tostop (-tostop) Send (do not send) SIGTTOU for background output. This causes background jobs to stop if they attempt terminal output. Control Characters: control-character string Set control-character to string. If string is a single character, the control character is set to that character. If string is the two character sequence "^-" or the string "undef" the control character is disabled (i.e., set to {_POSIX_VDISABLE}.) Recognized control-characters: control- character Subscript Description _________ _________ _______________ eof VEOF EOF character eol VEOL EOL character eol2 VEOL2 EOL2 character erase VERASE ERASE character erase2 VERASE2 ERASE2 character werase VWERASE WERASE character intr VINTR INTR character kill VKILL KILL character quit VQUIT QUIT character susp VSUSP SUSP character start VSTART START character stop VSTOP STOP character dsusp VDSUSP DSUSP character lnext VLNEXT LNEXT character reprint VREPRINT REPRINT character status VSTATUS STATUS character min number time number Set the value of min or time to number. MIN and TIME are used in Non-Canonical mode input processing (-icanon). Combination Modes: saved settings Set the current terminal characteristics to the saved settings produced by the -g option. cols number Same as columns. columns number The terminal size is recorded as having number columns. crt (-crt) Set (disable) all modes suitable for a CRT display device. dec Set modes suitable for users of Digital Equipment Corporation systems (ERASE, KILL, and INTR characters are set to ^?, ^U, and ^C; ixany is disabled, and crt is enabled.) ek Reset ERASE, ERASE2, and KILL characters back to system defaults. -evenp Same as -oddp and -parity. evenp Enable parenb and cs7; disable parodd. extproc (-extproc) If set, this flag indicates that some amount of terminal processing is being performed by either the terminal hardware or by the remote side connected to a pty. kerninfo (-kerninfo) Enable (disable) the system generated status line associated with processing a STATUS character (usually set to ^T). The status line consists of the system load average, the current command name, its process ID, the event the process is waiting on (or the status of the process), the user and system times, percent cpu, and current memory usage. nl (-nl) Enable (disable) icrnl. In addition, -nl unsets inlcr and igncr. -oddp Same as -evenp and -parity. oddp Enable parenb, cs7, and parodd. -parity Disable parenb; set cs8. parity Same as evenp. raw (-raw) If set, change the modes of the terminal so that no input or output processing is performed. If unset, change the modes of the terminal to some reasonable state that performs input and output processing. Note that since the terminal driver no longer has a single RAW bit, it is not possible to intuit what flags were set prior to setting raw. This means that unsetting raw may not put back all the setting that were previously in effect. To set the terminal into a raw state and then accurately restore it, the following shell code is recommended: save_state=$(stty -g) stty raw ... stty "$save_state" rows number The terminal size is recorded as having number rows. sane Resets all modes to reasonable values for interactive terminal use. size The size of the terminal is printed as two numbers on a single line, first rows, then columns. tty Set the line discipline to the standard terminal line discipline TTYDISC. Compatibility Modes: These modes remain for compatibility with the previous version of the stty command. all Reports all the terminal modes as with stty -a except that the control characters are printed in a columnar format. brk value Same as the control character eol. cbreak If set, enables brkint, ixon, imaxbel, opost, isig, iexten, and -icanon. If unset, same as sane. cooked Same as sane. crtbs (-crtbs) Same as echoe. crterase (-crterase) Same as echoe. crtkill (-crtkill) Same as echoke. ctlecho (-ctlecho) Same as echoctl. decctlq (-decctlq) The converse of ixany. everything Same as all. flush value Same as the control character discard. litout (-litout) The converse of opost. new Same as tty. newcrt (-newcrt) Same as crt. old Same as tty. oxtabs (-oxtabs) Expand(do not expand) tabs to spaces on output. pass8 The converse of parity. prterase (-prterase) Same as echoprt. rprnt value Same as the control character reprint. tabs (-tabs) The converse of oxtabs. tandem (-tandem) Same as ixoff. EXIT STATUS The stty utility exits 0 on success, and >0 if an error occurs. LEGACY DESCRIPTION In legacy operation, the bs[01], cr[0-3], ff[01], nl[01], tab[0-3], and vt[01] control modes are not accepted, nor are ocrnl (-ocrnl), ofdel (-ofdel), ofill (-ofill), onlret (-onlret), and onocr (-onocr). For more information about legacy mode, see compat(5). SEE ALSO termios(4), compat(5) STANDARDS The stty utility is expected to be IEEE Std 1003.2 (“POSIX.2”) compatible. The flags -e and -f are extensions to the standard. HISTORY A stty command appeared in Version 2 AT&T UNIX. macOS 14.5 October 20, 2018 macOS 14.5
stty – set the options for a terminal device interface
stty [-a | -e | -g] [-f file] [arguments]
null
null
date
When invoked without arguments, the date utility displays the current date and time. Otherwise, depending on the options specified, date will set the date and time or print it in a user-defined way. The date utility displays the date and time read from the kernel clock. When used to set the date and time, both the kernel clock and the hardware clock are updated. Only the superuser may set the date, and if the system securelevel (see securelevel(7)) is greater than 1, the time may not be changed by more than 1 second. The options are as follows: -f input_fmt Use input_fmt as the format string to parse the new_date provided rather than using the default [[[mm]dd]HH]MM[[cc]yy][.SS] format. Parsing is done using strptime(3). -I[FMT] Use ISO 8601 output format. FMT may be omitted, in which case the default is date. Valid FMT values are date, hours, minutes, and seconds. The date and time is formatted to the specified precision. When FMT is hours (or the more precise minutes or seconds), the ISO 8601 format includes the timezone. -j Do not try to set the date. This allows you to use the -f flag in addition to the + option to convert one date format to another. Note that any date or time components unspecified by the -f format string take their values from the current time. -n Obsolete flag, accepted and ignored for compatibility. -R Use RFC 2822 date and time output format. This is equivalent to using “%a, %d %b %Y %T %z” as output_fmt while LC_TIME is set to the “C” locale . -r seconds Print the date and time represented by seconds, where seconds is the number of seconds since the Epoch (00:00:00 UTC, January 1, 1970; see time(3)), and can be specified in decimal, octal, or hex. -r filename Print the date and time of the last modification of filename. -u Display or set the date in UTC (Coordinated Universal) time. By default date displays the time in the time zone described by /etc/localtime or the TZ environment variable. -v [+|-]val[y|m|w|d|H|M|S] Adjust (i.e., take the current date and display the result of the adjustment; not actually set the date) the second, minute, hour, month day, week day, month or year according to val. If val is preceded with a plus or minus sign, the date is adjusted forwards or backwards according to the remaining string, otherwise the relevant part of the date is set. The date can be adjusted as many times as required using these flags. Flags are processed in the order given. When setting values (rather than adjusting them), seconds are in the range 0-59, minutes are in the range 0-59, hours are in the range 0-23, month days are in the range 1-31, week days are in the range 0-6 (Sun-Sat), months are in the range 1-12 (Jan-Dec) and years are in a limited range depending on the platform. On i386, years are in the range 69-38 representing 1969-2038. On every other platform, years 0-68 are accepted and represent 2000-2068, and 69-99 are accepted and represent 1969-1999. In both cases, years between 100 and 1900 (both included) are accepted and interpreted as relative to 1900 of the Gregorian calendar with a limit of 138 on i386 and a much higher limit on every other platform. Years starting at 1901 are also accepted, and are interpreted as absolute years. If val is numeric, one of either y, m, w, d, H, M or S must be used to specify which part of the date is to be adjusted. The week day or month may be specified using a name rather than a number. If a name is used with the plus (or minus) sign, the date will be put forwards (or backwards) to the next (previous) date that matches the given week day or month. This will not adjust the date, if the given week day or month is the same as the current one. When a date is adjusted to a specific value or in units greater than hours, daylight savings time considerations are ignored. Adjustments in units of hours or less honor daylight saving time. So, assuming the current date is March 26, 0:30 and that the DST adjustment means that the clock goes forward at 01:00 to 02:00, using -v +1H will adjust the date to March 26, 2:30. Likewise, if the date is October 29, 0:30 and the DST adjustment means that the clock goes back at 02:00 to 01:00, using -v +3H will be necessary to reach October 29, 2:30. When the date is adjusted to a specific value that does not actually exist (for example March 26, 1:30 BST 2000 in the Europe/London timezone), the date will be silently adjusted forwards in units of one hour until it reaches a valid time. When the date is adjusted to a specific value that occurs twice (for example October 29, 1:30 2000), the resulting timezone will be set so that the date matches the earlier of the two times. It is not possible to adjust a date to an invalid absolute day, so using the switches -v 31d -v 12m will simply fail five months of the year. It is therefore usual to set the month before setting the day; using -v 12m -v 31d always works. Adjusting the date by months is inherently ambiguous because a month is a unit of variable length depending on the current date. This kind of date adjustment is applied in the most intuitive way. First of all, date tries to preserve the day of the month. If it is impossible because the target month is shorter than the present one, the last day of the target month will be the result. For example, using -v +1m on May 31 will adjust the date to June 30, while using the same option on January 30 will result in the date adjusted to the last day of February. This approach is also believed to make the most sense for shell scripting. Nevertheless, be aware that going forth and back by the same number of months may take you to a different date. Refer to the examples below for further details. An operand with a leading plus (‘+’) sign signals a user-defined format string which specifies the format in which to display the date and time. The format string may contain any of the conversion specifications described in the strftime(3) manual page, as well as any arbitrary text. A newline (‘\n’) character is always output after the characters specified by the format string. The format string for the default display is “+%+”. If an operand does not have a leading plus sign, it is interpreted as a value for setting the system's notion of the current date and time. The canonical representation for setting the date and time is: cc Century (either 19 or 20) prepended to the abbreviated year. yy Year in abbreviated form (e.g., 89 for 1989, 06 for 2006). mm Numeric month, a number from 1 to 12. dd Day, a number from 1 to 31. HH Hour, a number from 0 to 23. MM Minutes, a number from 0 to 59. SS Seconds, a number from 0 to 60 (59 plus a potential leap second). Everything but the minutes is optional. date understands the time zone definitions from the IANA Time Zone Database, tzdata, located in /usr/share/zoneinfo. Time changes for Daylight Saving Time, standard time, leap seconds and leap years are handled automatically. There are two ways to specify the time zone: If the file or symlink /etc/localtime exists, it is interpreted as a time zone definition file, usually in the directory hierarchy /usr/share/zoneinfo, which contains the time zone definitions from tzdata. If the environment variable TZ is set, its value is interpreted as the name of a time zone definition file, either an absolute path or a relative path to a time zone definition in /usr/share/zoneinfo. The TZ variable overrides /etc/localtime. If the time zone definition file is invalid, date silently reverts to UTC. Previous versions of date included the -d (set daylight saving time flag) and -t (set negative time zone offset) options, but these details are now handled automatically by tzdata. Modern offsets are positive for time zones ahead of UTC and negative for time zones behind UTC, but like the obsolete -t option, the tzdata files in the subdirectory /usr/share/zoneinfo/Etc still use an older convention where times ahead of UTC are considered negative. ENVIRONMENT The following environment variable affects the execution of date: TZ The timezone to use when displaying dates. The normal format is a pathname relative to /usr/share/zoneinfo. For example, the command “TZ=America/Los_Angeles date” displays the current time in California. The variable can also specify an absolute path. See environ(7) for more information. FILES /etc/localtime Time zone information file for default system time zone. May be omitted, in which case the default time zone is UTC. /usr/share/zoneinfo Directory containing time zone information files. /var/log/messages Record of the user setting the time. EXIT STATUS The date utility exits 0 on success, 1 if unable to set the date, and 2 if able to set the local date, but unable to set it globally.
date – display or set date and time
date [-nRu] [-I[FMT]] [-r filename] [-r seconds] [-v[+|-]val[y|m|w|d|H|M|S]] [+output_fmt] date [-jnRu] [-I[FMT]] [-v[+|-]val[y|m|w|d|H|M|S]] [[[mm]dd]HH]MM[[cc]yy][.SS] [+output_fmt] date [-jnRu] [-I[FMT]] [-v[+|-]val[y|m|w|d|H|M|S]] -f input_fmt new_date [+output_fmt]
null
The command: date "+DATE: %Y-%m-%d%nTIME: %H:%M:%S" will display: DATE: 1987-11-21 TIME: 13:36:16 In the Europe/London timezone, the command: date -v1m -v+1y will display: Sun Jan 4 04:15:24 GMT 1998 where it is currently Mon Aug 4 04:15:24 BST 1997. The command: date -v1d -v3m -v0y -v-1d will display the last day of February in the year 2000: Tue Feb 29 03:18:00 GMT 2000 So will the command: date -v3m -v30d -v0y -v-1m because there is no such date as the 30th of February. The command: date -v1d -v+1m -v-1d -v-fri will display the last Friday of the month: Fri Aug 29 04:31:11 BST 1997 where it is currently Mon Aug 4 04:31:11 BST 1997. The command: date 0613162785 sets the date to “June 13, 1985, 4:27 PM”. date "+%m%d%H%M%Y.%S" may be used on one machine to print out the date suitable for setting on another. The command: date 1432 sets the time to 2:32 PM, without modifying the date. The command TZ=America/Los_Angeles date -Iseconds -r 1533415339 will display 2018-08-04T13:42:19-07:00 Finally the command: date -j -f "%a %b %d %T %Z %Y" "`LC_ALL=C date`" "+%s" can be used to parse the output from date and express it in Epoch time. DIAGNOSTICS It is invalid to combine the -I flag with either -R or an output format (“+...”) operand. If this occurs, date prints: ‘multiple output formats specified’ and exits with status 1. LEGACY SYNOPSIS As above, except for the second line, which is: date [-jnu] [[[[[cc]yy]mm]dd]HH]MM[.SS] For more information about legacy mode, see compat(5). SEE ALSO locale(1), gettimeofday(2), getutxent(3), strftime(3), strptime(3), tzset(3) R. Gusella and S. Zatti, TSP: The Time Synchronization Protocol for UNIX 4.3BSD. Time Zone Database, https://iana.org/time-zones. STANDARDS The date utility is expected to be compatible with IEEE Std 1003.2 (“POSIX.2”). With the exception of the -u option, all options are extensions to the standard. The format selected by the -I flag is compatible with ISO 8601. HISTORY A date command appeared in Version 1 AT&T UNIX. A number of options were added and then removed again, including the -d (set DST flag) and -t (set negative time zone offset). Time zones are now handled by code bundled with tzdata. The -I flag was added in FreeBSD 12.0. macOS 14.5 July 28, 2022 macOS 14.5
realpath
The realpath utility uses the realpath(3) function to resolve all symbolic links, extra ‘/’ characters and references to /./ and /../ in path. If path is absent, the current working directory (‘.’) is assumed. If -q is specified, warnings will not be printed when realpath(3) fails. EXIT STATUS The realpath utility exits 0 on success, and >0 if an error occurs.
realpath – return resolved physical path
realpath [-q] [path ...]
null
Show the physical path of the /dev/log directory silencing warnings if any: $ realpath -q /dev/log /var/run/log SEE ALSO realpath(3) HISTORY The realpath utility first appeared in FreeBSD 4.3. macOS 14.5 June 21, 2011 macOS 14.5
ed
The ed utility is a line-oriented text editor. It is used to create, display, modify and otherwise manipulate text files. When invoked as red, the editor runs in "restricted" mode, in which the only difference is that the editor restricts the use of filenames which start with ‘!’ (interpreted as shell commands by ed) or contain a ‘/’. Note that editing outside of the current directory is only prohibited if the user does not have write access to the current directory. If a user has write access to the current directory, then symbolic links can be created in the current directory, in which case red will not stop the user from editing the file that the symbolic link points to. If invoked with a file argument, then a copy of file is read into the editor's buffer. Changes are made to this copy and not directly to file itself. Upon quitting ed, any changes not explicitly saved with a w command are lost. Editing is done in two distinct modes: command and input. When first invoked, ed is in command mode. In this mode commands are read from the standard input and executed to manipulate the contents of the editor buffer. A typical command might look like: ,s/old/new/g which replaces all occurrences of the string old with new. When an input command, such as a (append), i (insert) or c (change), is given, ed enters input mode. This is the primary means of adding text to a file. In this mode, no commands are available; instead, the standard input is written directly to the editor buffer. Lines consist of text up to and including a newline character. Input mode is terminated by entering a single period (.) on a line. All ed commands operate on whole lines or ranges of lines; e.g., the d command deletes lines; the m command moves lines, and so on. It is possible to modify only a portion of a line by means of replacement, as in the example above. However even here, the s command is applied to whole lines at a time. In general, ed commands consist of zero or more line addresses, followed by a single character command and possibly additional parameters; i.e., commands have the structure: [address[,address]]command[parameters] The address(es) indicate the line or range of lines to be affected by the command. If fewer addresses are given than the command accepts, then default addresses are supplied.
ed, red – text editor
ed [-] [-s] [-p string] [file] red [-] [-s] [-p string] [file]
The following options are available: -s Suppress diagnostics. This should be used if ed's standard input is from a script. -p string Specify a command prompt. This may be toggled on and off with the P command. file Specify the name of a file to read. If file is prefixed with a bang (!), then it is interpreted as a shell command. In this case, what is read is the standard output of file executed via sh(1). To read a file whose name begins with a bang, prefix the name with a backslash (\). The default filename is set to file only if it is not prefixed with a bang. LINE ADDRESSING An address represents the number of a line in the buffer. The ed utility maintains a current address which is typically supplied to commands as the default address when none is specified. When a file is first read, the current address is set to the last line of the file. In general, the current address is set to the last line affected by a command. A line address is constructed from one of the bases in the list below, optionally followed by a numeric offset. The offset may include any combination of digits, operators (i.e., +, - and ^) and whitespace. Addresses are read from left to right, and their values are computed relative to the current address. One exception to the rule that addresses represent line numbers is the address 0 (zero). This means "before the first line," and is legal wherever it makes sense. An address range is two addresses separated either by a comma or semi- colon. The value of the first address in a range cannot exceed the value of the second. If only one address is given in a range, then the second address is set to the given address. If an n-tuple of addresses is given where n_>_2, then the corresponding range is determined by the last two addresses in the n-tuple. If only one address is expected, then the last address is used. Each address in a comma-delimited range is interpreted relative to the current address. In a semi-colon-delimited range, the first address is used to set the current address, and the second address is interpreted relative to the first. The following address symbols are recognized: . The current line (address) in the buffer. $ The last line in the buffer. n The nth line in the buffer where n is a number in the range [0,$]. - or ^ The previous line. This is equivalent to -1 and may be repeated with cumulative effect. -n or ^n The nth previous line, where n is a non-negative number. + The next line. This is equivalent to +1 and may be repeated with cumulative effect. +n The nth next line, where n is a non-negative number. , or % The first through last lines in the buffer. This is equivalent to the address range 1,$. ; The current through last lines in the buffer. This is equivalent to the address range .,$. /re/ The next line containing the regular expression re. The search wraps to the beginning of the buffer and continues down to the current line, if necessary. // repeats the last search. ?re? The previous line containing the regular expression re. The search wraps to the end of the buffer and continues up to the current line, if necessary. ?? repeats the last search. 'lc The line previously marked by a k (mark) command, where lc is a lower case letter. REGULAR EXPRESSIONS Regular expressions are patterns used in selecting text. For example, the command: g/string/ prints all lines containing string. Regular expressions are also used by the s command for selecting old text to be replaced with new. In addition to a specifying string literals, regular expressions can represent classes of strings. Strings thus represented are said to be matched by the corresponding regular expression. If it is possible for a regular expression to match several strings in a line, then the left-most longest match is the one selected. The following symbols are used in constructing regular expressions: c Any character c not listed below, including ‘{’, ‘}’, ‘(’, ‘)’, ‘<’ and ‘>’, matches itself. \c Any backslash-escaped character c, except for ‘{’, ‘}’, ‘(’, ‘)’, ‘<’ and ‘>’, matches itself. . Match any single character. [char-class] Match any single character in char-class. To include a ‘]’ in char-class, it must be the first character. A range of characters may be specified by separating the end characters of the range with a ‘-’, e.g., ‘a-z’ specifies the lower case characters. The following literal expressions can also be used in char-class to specify sets of characters: [:alnum:] [:cntrl:] [:lower:] [:space:] [:alpha:] [:digit:] [:print:] [:upper:] [:blank:] [:graph:] [:punct:] [:xdigit:] If ‘-’ appears as the first or last character of char-class, then it matches itself. All other characters in char-class match themselves. Patterns in char-class of the form: [.col-elm.] or, [=col-elm=] where col-elm is a collating element are interpreted according to the current locale settings (not currently supported). See regex(3) and re_format(7) for an explanation of these constructs. [^char-class] Match any single character, other than newline, not in char-class. Char-class is defined as above. ^ If ^ is the first character of a regular expression, then it anchors the regular expression to the beginning of a line. Otherwise, it matches itself. $ If $ is the last character of a regular expression, it anchors the regular expression to the end of a line. Otherwise, it matches itself. \< Anchor the single character regular expression or subexpression immediately following it to the beginning of a word. (This may not be available) \> Anchor the single character regular expression or subexpression immediately following it to the end of a word. (This may not be available) \(re\) Define a subexpression re. Subexpressions may be nested. A subsequent backreference of the form \n, where n is a number in the range [1,9], expands to the text matched by the nth subexpression. For example, the regular expression ‘\(.*\)\1’ matches any string consisting of identical adjacent substrings. Subexpressions are ordered relative to their left delimiter. * Match the single character regular expression or subexpression immediately preceding it zero or more times. If * is the first character of a regular expression or subexpression, then it matches itself. The * operator sometimes yields unexpected results. For example, the regular expression ‘b*’ matches the beginning of the string ‘abbb’ (as opposed to the substring ‘bbb’), since a null match is the only left-most match. \{n,m\} or \{n,\} or \{n\} Match the single character regular expression or subexpression immediately preceding it at least n and at most m times. If m is omitted, then it matches at least n times. If the comma is also omitted, then it matches exactly n times. Additional regular expression operators may be defined depending on the particular regex(3) implementation. COMMANDS All ed commands are single characters, though some require additional parameters. If a command's parameters extend over several lines, then each line except for the last must be terminated with a backslash (\). In general, at most one command is allowed per line. However, most commands accept a print suffix, which is any of p (print), l (list), or n (enumerate), to print the last line affected by the command. An interrupt (typically ^C) has the effect of aborting the current command and returning the editor to command mode. The ed utility recognizes the following commands. The commands are shown together with the default address or address range supplied if none is specified (in parenthesis). (.)a Append text to the buffer after the addressed line. Text is entered in input mode. The current address is set to last line entered. (.,.)c Change lines in the buffer. The addressed lines are deleted from the buffer, and text is appended in their place. Text is entered in input mode. The current address is set to last line entered. (.,.)d Delete the addressed lines from the buffer. If there is a line after the deleted range, then the current address is set to this line. Otherwise the current address is set to the line before the deleted range. e file Edit file, and sets the default filename. If file is not specified, then the default filename is used. Any lines in the buffer are deleted before the new file is read. The current address is set to the last line read. e !command Edit the standard output of !command, (see !command below). The default filename is unchanged. Any lines in the buffer are deleted before the output of command is read. The current address is set to the last line read. E file Edit file unconditionally. This is similar to the e command, except that unwritten changes are discarded without warning. The current address is set to the last line read. f file Set the default filename to file. If file is not specified, then the default unescaped filename is printed. (1,$)g/re/command-list Apply command-list to each of the addressed lines matching a regular expression re. The current address is set to the line currently matched before command-list is executed. At the end of the g command, the current address is set to the last line affected by command-list. Each command in command-list must be on a separate line, and every line except for the last must be terminated by a backslash (\). Any commands are allowed, except for g, G, v, and V. A newline alone in command-list is equivalent to a p command. (1,$)G/re/ Interactively edit the addressed lines matching a regular expression re. For each matching line, the line is printed, the current address is set, and the user is prompted to enter a command-list. At the end of the G command, the current address is set to the last line affected by (the last) command-list. The format of command-list is the same as that of the g command. A newline alone acts as a null command list. A single ‘&’ repeats the last non-null command list. H Toggle the printing of error explanations. By default, explanations are not printed. It is recommended that ed scripts begin with this command to aid in debugging. h Print an explanation of the last error. (.)i Insert text in the buffer before the current line. Text is entered in input mode. The current address is set to the last line entered. (.,.+1)j Join the addressed lines. The addressed lines are deleted from the buffer and replaced by a single line containing their joined text. The current address is set to the resultant line. (.)klc Mark a line with a lower case letter lc. The line can then be addressed as 'lc (i.e., a single quote followed by lc) in subsequent commands. The mark is not cleared until the line is deleted or otherwise modified. (.,.)l Print the addressed lines unambiguously. If a single line fills more than one screen (as might be the case when viewing a binary file, for instance), a “--More--” prompt is printed on the last line. The ed utility waits until the RETURN key is pressed before displaying the next screen. The current address is set to the last line printed. (.,.)m(.) Move lines in the buffer. The addressed lines are moved to after the right-hand destination address, which may be the address 0 (zero). The current address is set to the last line moved. (.,.)n Print the addressed lines along with their line numbers. The current address is set to the last line printed. (.,.)p Print the addressed lines. The current address is set to the last line printed. P Toggle the command prompt on and off. Unless a prompt was specified by with command-line option -p string, the command prompt is by default turned off. q Quit ed. Q Quit ed unconditionally. This is similar to the q command, except that unwritten changes are discarded without warning. ($)r file Read file to after the addressed line. If file is not specified, then the default filename is used. If there was no default filename prior to the command, then the default filename is set to file. Otherwise, the default filename is unchanged. The current address is set to the last line read. ($)r !command Read to after the addressed line the standard output of !command, (see the !command below). The default filename is unchanged. The current address is set to the last line read. (.,.)s/re/replacement/ (.,.)s/re/replacement/g (.,.)s/re/replacement/n Replace text in the addressed lines matching a regular expression re with replacement. By default, only the first match in each line is replaced. If the g (global) suffix is given, then every match to be replaced. The n suffix, where n is a positive number, causes only the nth match to be replaced. It is an error if no substitutions are performed on any of the addressed lines. The current address is set the last line affected. Re and replacement may be delimited by any character other than space and newline (see the s command below). If one or two of the last delimiters is omitted, then the last line affected is printed as though the print suffix p were specified. An unescaped ‘&’ in replacement is replaced by the currently matched text. The character sequence \m, where m is a number in the range [1,9], is replaced by the m th backreference expression of the matched text. If replacement consists of a single ‘%’, then replacement from the last substitution is used. Newlines may be embedded in replacement if they are escaped with a backslash (\). (.,.)s Repeat the last substitution. This form of the s command accepts a count suffix n, or any combination of the characters r, g, and p. If a count suffix n is given, then only the nth match is replaced. The r suffix causes the regular expression of the last search to be used instead of the that of the last substitution. The g suffix toggles the global suffix of the last substitution. The p suffix toggles the print suffix of the last substitution The current address is set to the last line affected. (.,.)t(.) Copy (i.e., transfer) the addressed lines to after the right-hand destination address, which may be the address 0 (zero). The current address is set to the last line copied. u Undo the last command and restores the current address to what it was before the command. The global commands g, G, v, and V. are treated as a single command by undo. u is its own inverse. (1,$)v/re/command-list Apply command-list to each of the addressed lines not matching a regular expression re. This is similar to the g command. (1,$)V/re/ Interactively edit the addressed lines not matching a regular expression re. This is similar to the G command. (1,$)w file Write the addressed lines to file. Any previous contents of file is lost without warning. If there is no default filename, then the default filename is set to file, otherwise it is unchanged. If no filename is specified, then the default filename is used. The current address is unchanged. (1,$)wq file Write the addressed lines to file, and then executes a q command. (1,$)w !command Write the addressed lines to the standard input of !command, (see the !command below). The default filename and current address are unchanged. (1,$)W file Append the addressed lines to the end of file. This is similar to the w command, expect that the previous contents of file is not clobbered. The current address is unchanged. (.+1)zn Scroll n lines at a time starting at addressed line. If n is not specified, then the current window size is used. The current address is set to the last line printed. !command Execute command via sh(1). If the first character of command is ‘!’, then it is replaced by text of the previous !command. The ed utility does not process command for backslash (\) escapes. However, an unescaped % is replaced by the default filename. When the shell returns from execution, a ‘!’ is printed to the standard output. The current line is unchanged. ($)= Print the line number of the addressed line. (.+1)newline Print the addressed line, and sets the current address to that line. FILES /tmp/ed.* buffer file ed.hup the file to which ed attempts to write the buffer if the terminal hangs up DIAGNOSTICS When an error occurs, ed prints a ‘?’ and either returns to command mode or exits if its input is from a script. An explanation of the last error can be printed with the h (help) command. Since the g (global) command masks any errors from failed searches and substitutions, it can be used to perform conditional operations in scripts; e.g., g/old/s//new/ replaces any occurrences of old with new. If the u (undo) command occurs in a global command list, then the command list is executed only once. If diagnostics are not disabled, attempting to quit ed or edit another file before writing a modified buffer results in an error. If the command is entered a second time, it succeeds, but any changes to the buffer are lost. SEE ALSO sed(1), sh(1), vi(1), regex(3), compat(5) USD:12-13 B. W. Kernighan and P. J. Plauger, Software Tools in Pascal, 1981, Addison-Wesley. B. W. Kernighan, A Tutorial Introduction to the UNIX Text Editor. B. W. Kernighan, Advanced Editing on UNIX. LIMITATIONS The ed utility processes file arguments for backslash escapes, i.e., in a filename, any characters preceded by a backslash (\) are interpreted literally. If a text (non-binary) file is not terminated by a newline character, then ed appends one on reading/writing it. In the case of a binary file, ed does not append a newline on reading/writing. per line overhead: 4 ints HISTORY An ed command appeared in Version 1 AT&T UNIX. BUGS The ed utility does not recognize multibyte characters. macOS 14.5 April 9, 2021 macOS 14.5
null
expr
The expr utility evaluates expression and writes the result on standard output. All operators and operands must be passed as separate arguments. Several of the operators have special meaning to command interpreters and must therefore be quoted appropriately. All integer operands are interpreted in base 10 and must consist of only an optional leading minus sign followed by one or more digits. Arithmetic operations are performed using signed integer math with a range according to the C intmax_t data type (the largest signed integral type available). All conversions and operations are checked for overflow. Overflow results in program termination with an error message on stdout and with an error status. Operators are listed below in order of increasing precedence; all are left-associative. Operators with equal precedence are grouped within symbols ‘{’ and ‘}’. expr1 | expr2 Return the evaluation of expr1 if it is neither an empty string nor zero; otherwise, returns the evaluation of expr2 if it is not an empty string; otherwise, returns zero. expr1 & expr2 Return the evaluation of expr1 if neither expression evaluates to an empty string or zero; otherwise, returns zero. expr1 {=, >, >=, <, <=, !=} expr2 Return the results of integer comparison if both arguments are integers; otherwise, returns the results of string comparison using the locale-specific collation sequence. The result of each comparison is 1 if the specified relation is true, or 0 if the relation is false. expr1 {+, -} expr2 Return the results of addition or subtraction of integer-valued arguments. expr1 {*, /, %} expr2 Return the results of multiplication, integer division, or remainder of integer-valued arguments. expr1 : expr2 The “:” operator matches expr1 against expr2, which must be a basic regular expression. The regular expression is anchored to the beginning of the string with an implicit “^”. If the match succeeds and the pattern contains at least one regular expression subexpression “\(...\)”, the string corresponding to “\1” is returned; otherwise the matching operator returns the number of characters matched. If the match fails and the pattern contains a regular expression subexpression the null string is returned; otherwise 0. Parentheses are used for grouping in the usual manner. The expr utility makes no lexical distinction between arguments which may be operators and arguments which may be operands. An operand which is lexically identical to an operator will be considered a syntax error. See the examples below for a work-around. The syntax of the expr command in general is historic and inconvenient. New applications are advised to use shell arithmetic rather than expr. EXIT STATUS The expr utility exits with one of the following values: 0 the expression is neither an empty string nor 0. 1 the expression is an empty string or 0. 2 the expression is invalid.
expr – evaluate expression
expr expression
null
• The following example (in sh(1) syntax) adds one to the variable a: a=$(expr $a + 1) • This will fail if the value of a is a negative number. To protect negative values of a from being interpreted as options to the expr command, one might rearrange the expression: a=$(expr 1 + $a) • More generally, parenthesize possibly-negative values: a=$(expr \( $a \) + 1) • With shell arithmetic, no escaping is required: a=$((a + 1)) • This example prints the filename portion of a pathname stored in variable a. Since a might represent the path /, it is necessary to prevent it from being interpreted as the division operator. The // characters resolve this ambiguity. expr "//$a" : '.*/\(.*\)' • With modern sh(1) syntax, "${a##*/}" expands to the same value. The following examples output the number of characters in variable a. Again, if a might begin with a hyphen, it is necessary to prevent it from being interpreted as an option to expr, and a might be interpreted as an operator. • To deal with all of this, a complicated command is required: expr \( "X$a" : ".*" \) - 1 • With modern sh(1) syntax, this can be done much more easily: ${#a} expands to the required number. SEE ALSO sh(1), test(1) STANDARDS The expr utility conforms to IEEE Std 1003.1-2008 (“POSIX.1”). The extended arithmetic range and overflow checks do not conflict with POSIX's requirement that arithmetic be done using signed longs, since they only make a difference to the result in cases where using signed longs would give undefined behavior. According to the POSIX standard, the use of string arguments length, substr, index, or match produces undefined results. In this version of expr, these arguments are treated just as their respective string values. HISTORY An expr utility first appeared in the Programmer's Workbench (PWB/UNIX). A public domain version of expr written by Pace Willisson <pace@blitz.com> appeared in 386BSD-0.1. AUTHORS Initial implementation by Pace Willisson <pace@blitz.com> was largely rewritten by J.T. Conklin <jtc@FreeBSD.org>. macOS 14.5 October 5, 2016 macOS 14.5
pax
The pax utility will read, write, and list the members of an archive file, and will copy directory hierarchies. These operations are independent of the specific archive format, and support a wide variety of different archive formats. A list of supported archive formats can be found under the description of the -x option. 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. Write to standard output a table of contents of the members of the archive file read from standard input, whose pathnames match the specified patterns. The table of contents contains one filename per line and is written using single line buffering. -r Read. Extract the members of the archive file read from the standard input, with pathnames matching the specified patterns. The archive format and blocking is automatically determined on input. When an extracted file is a directory, the entire file hierarchy rooted at that directory is extracted. Extracted files are created either at absolute paths (those that begin with a / character) or relative to the current file hierarchy unless the -s option is used to remove leading slashes or add a relative path prefix. Files being extracted to absolute paths may overwrite files outside of the current working directory, so care should be taken when extracting untrusted archives. 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. Write an archive containing the file operands to standard output using the specified archive format. When no file operands are specified, a list of files to copy with one per line is read 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. Copy the file operands to the destination directory. When no file operands are specified, a list of files to copy with one per line is read 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). OPERANDS The directory operand specifies a destination directory pathname. If the directory operand does not exist, or it is not writable by the user, or 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. Archive members are selected using the pattern matching notation described by glob(3). When the pattern operand is not supplied, all members of the archive will be selected. When a pattern matches a directory, the entire file hierarchy rooted at that directory will be selected. 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 non-zero 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.
pax – read and write file archives and copy directory hierarchies
pax [-0cdjnvzO] [-f archive] [-s replstr] ... [-U user] ... [-G group] ... [-T [from_date] [,to_date]] ... [pattern ...] pax -r [-0cdijknuvzDOYZ] [-f archive] [-o options] ... [-p string] ... [-s replstr] ... [-E limit] [-U user] ... [-G group] ... [-T [from_date] [,to_date]] ... [pattern ...] pax -w [-0dijtuvzHLOPX] [-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 [-0dijklntuvDHLOPXYZ] [-p string] ... [-s replstr] ... [-U user] ... [-G group] ... [-T [from_date] [,to_date] [/[c][m]]] ... [file ...] directory
The following options are supported: -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. When no file operands are specified, standard input is read for a list of pathnames with one per line without any leading or trailing ⟨blanks⟩. -0 Use the NUL (‘\0’) character as a pathname terminator, instead of newline (‘\n’). This applies only to the pathnames read from standard input in the write and copy modes, and to the pathnames written to standard output in list mode. This option is expected to be used in concert with the -print0 function in find(1) or the -0 flag in xargs(1). -a Append files to the end of an archive that was previously written. If an archive format is not specified with a -x option, the format currently being used in the archive will be selected. Any attempt to append to an archive in a format different from the format already used in the archive will cause pax to exit immediately with a non-zero exit status. The blocking size used in the archive volume where writing starts will continue to be used for the remainder of that 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 When writing an archive, block the output at a positive decimal integer number of bytes per write to the archive file. The blocksize must be a multiple of 512 bytes with a maximum of 64512 bytes. A blocksize larger than 32256 bytes violates the POSIX standard and will not be portable to all systems. A blocksize can end with k or b to specify multiplication by 1024 (1K) or 512, respectively. A pair of blocksizes can be separated by x to indicate a product. A specific archive device may impose additional restrictions on the size of blocking it will support. When blocking is not specified, the default blocksize is dependent 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 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. The pax utility will then read a line from /dev/tty. If this line is blank, the file or archive member is skipped. If this line consists of a single period, the file or archive member is processed with no modification to its name. Otherwise, its name is replaced with the contents of the line. The pax utility 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. -j Use bzip2 to compress (decompress) the archive while writing (reading). The bzip2 utility must be installed separately. Incompatible with -a. -k Do not overwrite existing files. -l Link files. (The letter ell). In the copy mode (-r -w), hard links are made between the source and destination file hierarchies whenever possible. -n Select the first archive member that matches each pattern operand. No more than one archive member is matched for each pattern. When members of type directory are matched, the file hierarchy rooted at that directory is also matched (unless -d is also specified). -o options Information to modify the algorithm for extracting or writing archive files which is specific to the archive format specified by -x. In general, options take the form: name=value The following options are available for the old BSD tar format: nodir write_opt=nodir When writing archives, omit the storage of directories. -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. Multiple characteristics can be concatenated within the same string and multiple -p options can be specified. The meaning of the specification characters are as follows: a Do not preserve file access times. By default, file access times are preserved whenever possible. e ‘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. m Do not preserve file modification times. By default, file modification times are preserved whenever possible. o Preserve the user ID and group ID. p ‘Preserve’ the file mode bits. This is 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. File flags set by chflags(1) are not understood by pax, however tar(1) and dump(8) will preserve these. -r Read an archive file from standard input and extract the specified file operands. 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. -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. file or pattern arguments may be given to restrict the list of archive members to those specified. 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). Multiple -s expressions can be specified. The expressions are applied in the order they are specified 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 read or accessed by pax to be the same as they were before being read or accessed by pax. -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), pathnames are written and flushed 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. The pax utility currently supports the following formats: cpio The extended cpio interchange format specified in the IEEE Std 1003.2 (“POSIX.2”) standard. The default blocksize for this format is 5120 bytes. Inode and device information about a file (used for detecting file hard links by this format) which may be truncated by this format is detected by pax and is repaired. bcpio The old binary cpio format. The default blocksize for this format is 5120 bytes. This format is not very portable and should not be used when other formats are available. Inode and device information about a file (used for detecting file hard links by this format), which may be truncated by this format, is detected by pax and is repaired. sv4cpio The System V release 4 cpio. The default blocksize for this format is 5120 bytes. Inode and device information about a file (used for detecting file hard links by this format), which may be truncated by this format, is detected by pax and is repaired. sv4crc The System V release 4 cpio with file crc checksums. The default blocksize for this format is 5120 bytes. Inode and device information about a file (used for detecting file hard links by this format), which may be truncated by this format, is detected by pax and is repaired. tar The old BSD tar format as found in 4.3BSD. 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 Std 1003.2 (“POSIX.2”) standard. The default blocksize for this format is 10240 bytes. Pathnames stored by this format must be 255 characters or less in length. The directory part may be at most 155 characters and each path component must be less than 100 characters. The pax utility 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. -z Use gzip(1) to compress (decompress) the archive while writing (reading). Incompatible with -a. -B bytes Limit the number of bytes written to a single archive volume to bytes. 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. Note that the specified size is for the uncompressed pax image itself. If the -z option is also used, the resulting file may contain fewer bytes, according to the compressibility of the archive contents. See zip(1) if compressed volumes of predictable size are required. Warning: Only use this option when writing an archive to a device which supports an end of file read condition based on last (or largest) write offset (such as a regular file or a tape drive). The use of this option with a floppy or hard disk is not recommended. -D This option is the same as the -u option, except that the file inode change time is checked instead of the file modification time. The file inode change time can be used to select files whose inode information (e.g., 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 archives to limit. 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 the first read error is detected 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: Using this option with NONE should be used with extreme caution as 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. A '\' can be used to escape the #. Multiple -G options may be supplied and 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. -O Force the archive to be one volume. If a volume ends prematurely, pax will not prompt for a new volume. This option can be useful for automated tasks where error recovery cannot be performed by a human. -P Do not follow symbolic links, perform a physical file system traversal. This is the default mode. -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 only a from_date is supplied, all files with a modification or inode change time equal to or younger are selected. If only a to_date is supplied, all files with a modification or inode change time equal to or older will be selected. When the from_date is equal to the to_date, only files with a modification or inode change time of exactly that time will be selected. When pax is in the write or copy mode, the optional trailing field [c][m] can be used to determine which file time (inode change, file modification or both) are used in the comparison. If neither is specified, the default is to use file modification time only. The m specifies the comparison of file modification time (the time when the file was last written). The c specifies the comparison of inode change time (the time when the file inode was last changed; e.g., a change of owner, group, mode, etc). When c and m are both specified, then the modification and inode change times are both compared. The inode change time comparison is useful in selecting files whose attributes were recently changed or selecting files which were recently created and had their modification time reset to an older time (as what happens when a file is extracted from an archive and the modification time is preserved). Time comparisons using both file times is useful when pax is used 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 and each field must contain two digits. The format is: [[[[[cc]yy]mm]dd]HH]MM[.SS] Where cc is the first two digits of the year (the century), 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), 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, cc. 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. Multiple -T time range can be supplied and 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 #. Multiple -U options may be supplied and 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 ID's. -Y This option is the same as the -D option, except that the inode change time is checked using the pathname created after all the file name modifications have completed. -Z This option is the same as the -u option, except that the modification time is checked using the pathname created after all the file name modifications have completed. --insecure Normally pax ignores filenames or symbolic links that contain “..” as a path component. With this option, files that contain “..” can be processed. The options that operate on the names of files or archive members (-c, -i, -j, -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 only applies 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 resulting from these modifications. When one or both of the -u or -D options are specified along with the -n option, a file is not considered selected unless it is newer than the file to which it is compared. ENVIRONMENT TMPDIR Path in which to store temporary files. EXIT STATUS The pax utility will exit with one of the following values: 0 All files were processed successfully. 1 An error occurred.
The command: pax -w -f /dev/sa0 . copies the contents of the current directory to the device /dev/sa0. The command: pax -v -f filename gives the verbose table of contents for an archive stored in filename. The following commands: mkdir /tmp/to cd /tmp/from pax -rw . /tmp/to will copy the entire /tmp/from directory hierarchy to /tmp/to. 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. 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 which 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 which are older (less recent inode change or file modification times) than files with the same name found in the source file tree home. DIAGNOSTICS 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, a diagnostic message is written to standard error and a non-zero exit status will be returned, but processing will continue. 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, the file is not copied, a diagnostic message is written to standard error and when pax completes it will exit with a non-zero exit status. SEE ALSO cpio(1), tar(1) STANDARDS The pax utility is a superset of the IEEE Std 1003.2 (“POSIX.2”) standard. The options -0, -j, -z, -B, -D, -E, -G, -H, -L, -O, -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. HISTORY The pax utility appeared in 4.4BSD. AUTHORS Keith Muller at the University of California, San Diego BUGS The pax utility does not recognize multibyte characters. File flags set by chflags(1) are not preserved by pax. The BUGS section of chflags(1) has a list of utilities that are unaware of flags. macOS 14.5 October 19, 2022 macOS 14.5
bash
Bash is an sh-compatible command language interpreter that executes commands read from the standard input or from a file. Bash also incorporates useful features from the Korn and C shells (ksh and csh). Bash is intended to be a conformant implementation of the Shell and Utilities portion of the IEEE POSIX specification (IEEE Standard 1003.1). Bash can be configured to be POSIX-conformant by default.
bash - GNU Bourne-Again SHell
bash [options] [file] COPYRIGHT Bash is Copyright (C) 1989-2005 by the Free Software Foundation, Inc.
In addition to the single-character shell options documented in the description of the set builtin command, bash interprets the following options when it is invoked: -c string If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0. -i If the -i option is present, the shell is interactive. -l Make bash act as if it had been invoked as a login shell (see INVOCATION below). -r If the -r option is present, the shell becomes restricted (see RESTRICTED SHELL below). -s If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell. -D A list of all double-quoted strings preceded by $ is printed on the standard output. These are the strings that are subject to language translation when the current locale is not C or POSIX. This implies the -n option; no commands will be executed. [-+]O [shopt_option] shopt_option is one of the shell options accepted by the shopt builtin (see SHELL BUILTIN COMMANDS below). If shopt_option is present, -O sets the value of that option; +O unsets it. If shopt_option is not supplied, the names and values of the shell options accepted by shopt are printed on the standard output. If the invocation option is +O, the output is displayed in a format that may be reused as input. -- A -- signals the end of options and disables further option processing. Any arguments after the -- are treated as filenames and arguments. An argument of - is equivalent to --. Bash also interprets a number of multi-character options. These options must appear on the command line before the single-character options to be recognized. --debugger Arrange for the debugger profile to be executed before the shell starts. Turns on extended debugging mode (see the description of the extdebug option to the shopt builtin below) and shell function tracing (see the description of the -o functrace option to the set builtin below). --dump-po-strings Equivalent to -D, but the output is in the GNU gettext po (portable object) file format. --dump-strings Equivalent to -D. --help Display a usage message on standard output and exit successfully. --init-file file --rcfile file Execute commands from file instead of the standard personal initialization file ~/.bashrc if the shell is interactive (see INVOCATION below). --login Equivalent to -l. --noediting Do not use the GNU readline library to read command lines when the shell is interactive. --noprofile Do not read either the system-wide startup file /etc/profile or any of the personal initialization files ~/.bash_profile, ~/.bash_login, or ~/.profile. By default, bash reads these files when it is invoked as a login shell (see INVOCATION below). --norc Do not read and execute the personal initialization file ~/.bashrc if the shell is interactive. This option is on by default if the shell is invoked as sh. --posix Change the behavior of bash where the default operation differs from the POSIX standard to match the standard (posix mode). --restricted The shell becomes restricted (see RESTRICTED SHELL below). --verbose Equivalent to -v. --version Show version information for this instance of bash on the standard output and exit successfully. ARGUMENTS If arguments remain after option processing, and neither the -c nor the -s option has been supplied, the first argument is assumed to be the name of a file containing shell commands. If bash is invoked in this fashion, $0 is set to the name of the file, and the positional parameters are set to the remaining arguments. Bash reads and executes commands from this file, then exits. Bash's exit status is the exit status of the last command executed in the script. If no commands are executed, the exit status is 0. An attempt is first made to open the file in the current directory, and, if no file is found, then the shell searches the directories in PATH for the script. INVOCATION A login shell is one whose first character of argument zero is a -, or one started with the --login option. An interactive shell is one started without non-option arguments and without the -c option whose standard input and error are both connected to terminals (as determined by isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state. The following paragraphs describe how bash executes its startup files. If any of the files exist but cannot be read, bash reports an error. Tildes are expanded in file names as described below under Tilde Expansion in the EXPANSION section. When bash is invoked as an interactive login shell, or as a non- interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior. When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists. When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc. When bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed: if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi but the value of the PATH variable is not used to search for the file name. If bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well. When invoked as an interactive login shell, or a non-interactive shell with the --login option, it first attempts to read and execute commands from /etc/profile and ~/.profile, in that order. The --noprofile option may be used to inhibit this behavior. When invoked as an interactive shell with the name sh, bash looks for the variable ENV, expands its value if it is defined, and uses the expanded value as the name of a file to read and execute. Since a shell invoked as sh does not attempt to read and execute commands from any other startup files, the --rcfile option has no effect. A non-interactive shell invoked with the name sh does not attempt to read any other startup files. When invoked as sh, bash enters posix mode after the startup files are read. When bash is started in posix mode, as with the --posix command line option, it follows the POSIX standard for startup files. In this mode, interactive shells expand the ENV variable and commands are read and executed from the file whose name is the expanded value. No other startup files are read. Bash attempts to determine when it is being run by the remote shell daemon, usually rshd. If bash determines it is being run by rshd, it reads and executes commands from ~/.bashrc, if that file exists and is readable. It will not do this if invoked as sh. The --norc option may be used to inhibit this behavior, and the --rcfile option may be used to force another file to be read, but rshd does not generally invoke the shell with those options or allow them to be specified. If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, no startup files are read, shell functions are not inherited from the environment, the SHELLOPTS variable, if it appears in the environment, is ignored, and the effective user id is set to the real user id. If the -p option is supplied at invocation, the startup behavior is the same, but the effective user id is not reset. DEFINITIONS The following definitions are used throughout the rest of this document. blank A space or tab. word A sequence of characters considered as a single unit by the shell. Also known as a token. name A word consisting only of alphanumeric characters and underscores, and beginning with an alphabetic character or an underscore. Also referred to as an identifier. metacharacter A character that, when unquoted, separates words. One of the following: | & ; ( ) < > space tab control operator A token that performs a control function. It is one of the following symbols: || & && ; ;; ( ) | <newline> RESERVED WORDS Reserved words are words that have a special meaning to the shell. The following words are recognized as reserved when unquoted and either the first word of a simple command (see SHELL GRAMMAR below) or the third word of a case or for command: ! case do done elif else esac fi for function if in select then until while { } time [[ ]] SHELL GRAMMAR Simple Commands A simple command is a sequence of optional variable assignments followed by blank-separated words and redirections, and terminated by a control operator. The first word specifies the command to be executed, and is passed as argument zero. The remaining words are passed as arguments to the invoked command. The return value of a simple command is its exit status, or 128+n if the command is terminated by signal n. Pipelines A pipeline is a sequence of one or more commands separated by the character |. The format for a pipeline is: [time [-p]] [ ! ] command [ | command2 ... ] The standard output of command is connected via a pipe to the standard input of command2. This connection is performed before any redirections specified by the command (see REDIRECTION below). The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. If pipefail is enabled, the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully. If the reserved word ! precedes a pipeline, the exit status of that pipeline is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value. If the time reserved word precedes a pipeline, the elapsed as well as user and system time consumed by its execution are reported when the pipeline terminates. The -p option changes the output format to that specified by POSIX. The TIMEFORMAT variable may be set to a format string that specifies how the timing information should be displayed; see the description of TIMEFORMAT under Shell Variables below. Each command in a pipeline is executed as a separate process (i.e., in a subshell). Lists A list is a sequence of one or more pipelines separated by one of the operators ;, &, &&, or ⎪⎪, and optionally terminated by one of ;, &, or <newline>. Of these list operators, && and ⎪⎪ have equal precedence, followed by ; and &, which have equal precedence. A sequence of one or more newlines may appear in a list instead of a semicolon to delimit commands. If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0. Commands separated by a ; are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed. The control operators && and ⎪⎪ denote AND lists and OR lists, respectively. An AND list has the form command1 && command2 command2 is executed if, and only if, command1 returns an exit status of zero. An OR list has the form command1 ⎪⎪ command2 command2 is executed if and only if command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list. Compound Commands A compound command is one of the following: (list) list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below). Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list. { list; } list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. This is known as a group command. The return status is the exit status of list. Note that unlike the metacharacters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recognized. Since they do not cause a word break, they must be separated from list by whitespace. ((expression)) The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to let "expression". [[ expression ]] Return a status of 0 or 1 depending on the evaluation of the conditional expression expression. Expressions are composed of the primaries described below under CONDITIONAL EXPRESSIONS. Word splitting and pathname expansion are not performed on the words between the [[ and ]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed. Conditional operators such as -f must be unquoted to be recognized as primaries. When the == and != operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below under Pattern Matching. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. The return value is 0 if the string matches (==) or does not match (!=) the pattern, and 1 otherwise. Any part of the pattern may be quoted to force it to be matched as a string. An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variable BASH_REMATCH. The element of BASH_REMATCH with index 0 is the portion of the string matching the entire regular expression. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression. Expressions may be combined using the following operators, listed in decreasing order of precedence: ( expression ) Returns the value of expression. This may be used to override the normal precedence of operators. ! expression True if expression is false. expression1 && expression2 True if both expression1 and expression2 are true. expression1 || expression2 True if either expression1 or expression2 is true. The && and || operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression. for name [ in word ] ; do list ; done The list of words following in is expanded, generating a list of items. The variable name is set to each element of this list in turn, and list is executed each time. If the in word is omitted, the for command executes list once for each positional parameter that is set (see PARAMETERS below). The return status is the exit status of the last command that executes. If the expansion of the items following in results in an empty list, no commands are executed, and the return status is 0. for (( expr1 ; expr2 ; expr3 )) ; do list ; done First, the arithmetic expression expr1 is evaluated according to the rules described below under ARITHMETIC EVALUATION. The arithmetic expression expr2 is then evaluated repeatedly until it evaluates to zero. Each time expr2 evaluates to a non-zero value, list is executed and the arithmetic expression expr3 is evaluated. If any expression is omitted, it behaves as if it evaluates to 1. The return value is the exit status of the last command in list that is executed, or false if any of the expressions is invalid. select name [ in word ] ; do list ; done The list of words following in is expanded, generating a list of items. The set of expanded words is printed on the standard error, each preceded by a number. If the in word is omitted, the positional parameters are printed (see PARAMETERS below). The PS3 prompt is then displayed and a line read from the standard input. If the line consists of a number corresponding to one of the displayed words, then the value of name is set to that word. If the line is empty, the words and prompt are displayed again. If EOF is read, the command completes. Any other value read causes name to be set to null. The line read is saved in the variable REPLY. The list is executed after each selection until a break command is executed. The exit status of select is the exit status of the last command executed in list, or zero if no commands were executed. case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac A case command first expands word, and tries to match it against each pattern in turn, using the same matching rules as for pathname expansion (see Pathname Expansion below). The word is expanded using tilde expansion, parameter and variable expansion, arithmetic substitution, command substitution, process substitution and quote removal. Each pattern examined is expanded using tilde expansion, parameter and variable expansion, arithmetic substitution, command substitution, and process substitution. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. When a match is found, the corresponding list is executed. After the first match, no subsequent matches are attempted. The exit status is zero if no pattern matches. Otherwise, it is the exit status of the last command executed in list. if list; then list; [ elif list; then list; ] ... [ else list; ] fi The if list is executed. If its exit status is zero, the then list is executed. Otherwise, each elif list is executed in turn, and if its exit status is zero, the corresponding then list is executed and the command completes. Otherwise, the else list is executed, if present. The exit status is the exit status of the last command executed, or zero if no condition tested true. while list; do list; done until list; do list; done The while command continuously executes the do list as long as the last command in list returns an exit status of zero. The until command is identical to the while command, except that the test is negated; the do list is executed as long as the last command in list returns a non-zero exit status. The exit status of the while and until commands is the exit status of the last do list command executed, or zero if none was executed. Shell Function Definitions A shell function is an object that is called like a simple command and executes a compound command with a new set of positional parameters. Shell functions are declared as follows: [ function ] name () compound-command [redirection] This defines a function named name. The reserved word function is optional. If the function reserved word is supplied, the parentheses are optional. The body of the function is the compound command compound-command (see Compound Commands above). That command is usually a list of commands between { and }, but may be any command listed under Compound Commands above. compound-command is executed whenever name is specified as the name of a simple command. Any redirections (see REDIRECTION below) specified when a function is defined are performed when the function is executed. The exit status of a function definition is zero unless a syntax error occurs or a readonly function with the same name already exists. When executed, the exit status of a function is the exit status of the last command executed in the body. (See FUNCTIONS below.) COMMENTS In a non-interactive shell, or an interactive shell in which the interactive_comments option to the shopt builtin is enabled (see SHELL BUILTIN COMMANDS below), a word beginning with # causes that word and all remaining characters on that line to be ignored. An interactive shell without the interactive_comments option enabled does not allow comments. The interactive_comments option is on by default in interactive shells. QUOTING Quoting is used to remove the special meaning of certain characters or words to the shell. Quoting can be used to disable special treatment for special characters, to prevent reserved words from being recognized as such, and to prevent parameter expansion. Each of the metacharacters listed above under DEFINITIONS has special meaning to the shell and must be quoted if it is to represent itself. When the command history expansion facilities are being used (see HISTORY EXPANSION below), the history expansion character, usually !, must be quoted to prevent history expansion. There are three quoting mechanisms: the escape character, single quotes, and double quotes. A non-quoted backslash (\) is the escape character. It preserves the literal value of the next character that follows, with the exception of <newline>. If a \<newline> pair appears, and the backslash is not itself quoted, the \<newline> is treated as a line continuation (that is, it is removed from the input stream and effectively ignored). Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes. The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or <newline>. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed. The special parameters * and @ have special meaning when in double quotes (see PARAMETERS below). Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows: \a alert (bell) \b backspace \e an escape character \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \\ backslash \' single quote \nnn the eight-bit character whose value is the octal value nnn (one to three digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) \cx a control-x character The expanded result is single-quoted, as if the dollar sign had not been present. A double-quoted string preceded by a dollar sign ($) will cause the string to be translated according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored. If the string is translated and replaced, the replacement is double-quoted. PARAMETERS A parameter is an entity that stores values. It can be a name, a number, or one of the special characters listed below under Special Parameters. A variable is a parameter denoted by a name. A variable has a value and zero or more attributes. Attributes are assigned using the declare builtin command (see declare below in SHELL BUILTIN COMMANDS). A parameter is set if it has been assigned a value. The null string is a valid value. Once a variable is set, it may be unset only by using the unset builtin command (see SHELL BUILTIN COMMANDS below). A variable may be assigned to by a statement of the form name=[value] If value is not given, the variable is assigned the null string. All values undergo tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal (see EXPANSION below). If the variable has its integer attribute set, then value is evaluated as an arithmetic expression even if the $((...)) expansion is not used (see Arithmetic Expansion below). Word splitting is not performed, with the exception of "$@" as explained below under Special Parameters. Pathname expansion is not performed. Assignment statements may also appear as arguments to the alias, declare, typeset, export, readonly, and local builtin commands. In the context where an assignment statement is assigning a value to a shell variable or array index, the += operator can be used to append to or add to the variable's previous value. When += is applied to a variable for which the integer attribute has been set, value is evaluated as an arithmetic expression and added to the variable's current value, which is also evaluated. When += is applied to an array variable using compound assignment (see Arrays below), the variable's value is not unset (as it is when using =), and new values are appended to the array beginning at one greater than the array's maximum index. When applied to a string-valued variable, value is expanded and appended to the variable's value. Positional Parameters A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell's arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameters may not be assigned to with assignment statements. The positional parameters are temporarily replaced when a shell function is executed (see FUNCTIONS below). When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces (see EXPANSION below). Special Parameters The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. * Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators. @ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed). # Expands to the number of positional parameters in decimal. ? Expands to the status of the most recently executed foreground pipeline. - Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option). $ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell. ! Expands to the process ID of the most recently executed background (asynchronous) command. 0 Expands to the name of the shell or shell script. This is set at shell initialization. If bash is invoked with a file of commands, $0 is set to the name of that file. If bash is started with the -c option, then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the file name used to invoke bash, as given by argument zero. _ At shell startup, set to the absolute pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous command, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file currently being checked. Shell Variables The following variables are set by the shell: BASH Expands to the full file name used to invoke this instance of bash. BASH_ARGC An array variable whose values are the number of parameters in each frame of the current bash execution call stack. The number of parameters to the current subroutine (shell function or script executed with . or source) is at the top of the stack. When a subroutine is executed, the number of parameters passed is pushed onto BASH_ARGC. The shell sets BASH_ARGC only when in extended debugging mode (see the description of the extdebug option to the shopt builtin below) BASH_ARGV An array variable containing all of the parameters in the current bash execution call stack. The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto BASH_ARGV. The shell sets BASH_ARGV only when in extended debugging mode (see the description of the extdebug option to the shopt builtin below) BASH_COMMAND The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap. BASH_EXECUTION_STRING The command argument to the -c invocation option. BASH_LINENO An array variable whose members are the line numbers in source files corresponding to each member of FUNCNAME. ${BASH_LINENO[$i]} is the line number in the source file where ${FUNCNAME[$ifP]} was called. The corresponding source file name is ${BASH_SOURCE[$i]}. Use LINENO to obtain the current line number. BASH_REMATCH An array variable whose members are assigned by the =~ binary operator to the [[ conditional command. The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the nth parenthesized subexpression. This variable is read-only. BASH_SOURCE An array variable whose members are the source filenames corresponding to the elements in the FUNCNAME array variable. BASH_SUBSHELL Incremented by one each time a subshell or subshell environment is spawned. The initial value is 0. BASH_VERSINFO A readonly array variable whose members hold version information for this instance of bash. The values assigned to the array members are as follows: BASH_VERSINFO[0] The major version number (the release). BASH_VERSINFO[1] The minor version number (the version). BASH_VERSINFO[2] The patch level. BASH_VERSINFO[3] The build version. BASH_VERSINFO[4] The release status (e.g., beta1). BASH_VERSINFO[5] The value of MACHTYPE. BASH_VERSION Expands to a string describing the version of this instance of bash. COMP_CWORD An index into ${COMP_WORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion below). COMP_LINE The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion below). COMP_POINT The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the current command, the value of this variable is equal to ${#COMP_LINE}. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion below). COMP_WORDBREAKS The set of characters that the Readline library treats as word separators when performing word completion. If COMP_WORDBREAKS is unset, it loses its special properties, even if it is subsequently reset. COMP_WORDS An array variable (see Arrays below) consisting of the individual words in the current command line. The words are split on shell metacharacters as the shell parser would separate them. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion below). DIRSTACK An array variable (see Arrays below) containing the current contents of the directory stack. Directories appear in the stack in the order they are displayed by the dirs builtin. Assigning to members of this array variable may be used to modify directories already in the stack, but the pushd and popd builtins must be used to add and remove directories. Assignment to this variable will not change the current directory. If DIRSTACK is unset, it loses its special properties, even if it is subsequently reset. EUID Expands to the effective user ID of the current user, initialized at shell startup. This variable is readonly. FUNCNAME An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element is "main". This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect and return an error status. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset. GROUPS An array variable containing the list of groups of which the current user is a member. Assignments to GROUPS have no effect and return an error status. If GROUPS is unset, it loses its special properties, even if it is subsequently reset. HISTCMD The history number, or index in the history list, of the current command. If HISTCMD is unset, it loses its special properties, even if it is subsequently reset. HOSTNAME Automatically set to the name of the current host. HOSTTYPE Automatically set to a string that uniquely describes the type of machine on which bash is executing. The default is system- dependent. LINENO Each time this parameter is referenced, the shell substitutes a decimal number representing the current sequential line number (starting with 1) within a script or function. When not in a script or function, the value substituted is not guaranteed to be meaningful. If LINENO is unset, it loses its special properties, even if it is subsequently reset. MACHTYPE Automatically set to a string that fully describes the system type on which bash is executing, in the standard GNU cpu- company-system format. The default is system-dependent. OLDPWD The previous working directory as set by the cd command. OPTARG The value of the last option argument processed by the getopts builtin command (see SHELL BUILTIN COMMANDS below). OPTIND The index of the next argument to be processed by the getopts builtin command (see SHELL BUILTIN COMMANDS below). OSTYPE Automatically set to a string that describes the operating system on which bash is executing. The default is system- dependent. PIPESTATUS An array variable (see Arrays below) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command). PPID The process ID of the shell's parent. This variable is readonly. PWD The current working directory as set by the cd command. RANDOM Each time this parameter is referenced, a random integer between 0 and 32767 is generated. The sequence of random numbers may be initialized by assigning a value to RANDOM. If RANDOM is unset, it loses its special properties, even if it is subsequently reset. REPLY Set to the line of input read by the read builtin command when no arguments are supplied. SECONDS Each time this parameter is referenced, the number of seconds since shell invocation is returned. If a value is assigned to SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value assigned. If SECONDS is unset, it loses its special properties, even if it is subsequently reset. SHELLOPTS A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -o option to the set builtin command (see SHELL BUILTIN COMMANDS below). The options appearing in SHELLOPTS are those reported as on by set -o. If this variable is in the environment when bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is read-only. SHLVL Incremented by one each time an instance of bash is started. UID Expands to the user ID of the current user, initialized at shell startup. This variable is readonly. The following variables are used by the shell. In some cases, bash assigns a default value to a variable; these cases are noted below. BASH_ENV If this parameter is set when bash is executing a shell script, its value is interpreted as a filename containing commands to initialize the shell, as in ~/.bashrc. The value of BASH_ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a file name. PATH is not used to search for the resultant file name. CDPATH The search path for the cd command. This is a colon-separated list of directories in which the shell looks for destination directories specified by the cd command. A sample value is ".:~:/usr". COLUMNS Used by the select builtin command to determine the terminal width when printing selection lists. Automatically set upon receipt of a SIGWINCH. COMPREPLY An array variable from which bash reads the possible completions generated by a shell function invoked by the programmable completion facility (see Programmable Completion below). EMACS If bash finds this variable in the environment when the shell starts with value "t", it assumes that the shell is running in an emacs shell buffer and disables line editing. FCEDIT The default editor for the fc builtin command. FIGNORE A colon-separated list of suffixes to ignore when performing filename completion (see READLINE below). A filename whose suffix matches one of the entries in FIGNORE is excluded from the list of matched filenames. A sample value is ".o:~". GLOBIGNORE A colon-separated list of patterns defining the set of filenames to be ignored by pathname expansion. If a filename matched by a pathname expansion pattern also matches one of the patterns in GLOBIGNORE, it is removed from the list of matches. HISTCONTROL A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ignorespace, lines which begin with a space character are not saved in the history list. A value of ignoredups causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A value of erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL. HISTFILE The name of the file in which command history is saved (see HISTORY below). The default value is ~/.bash_history. If unset, the command history is not saved when an interactive shell exits. HISTFILESIZE The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, by removing the oldest entries, to contain no more than that number of lines. The default value is 500. The history file is also truncated to this size after writing it when an interactive shell exits. HISTIGNORE A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must match the complete line (no implicit `*' is appended). Each pattern is tested against the line after the checks specified by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, `&' matches the previous history line. `&' may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE. HISTSIZE The number of commands to remember in the command history (see HISTORY below). The default value is 500. HISTTIMEFORMAT If this variable is set and not null, its value is used as a format string for strftime(3) to print the time stamp associated with each history entry displayed by the history builtin. If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. HOME The home directory of the current user; the default argument for the cd builtin command. The value of this variable is also used when performing tilde expansion. HOSTFILE Contains the name of a file in the same format as /etc/hosts that should be read when the shell needs to complete a hostname. The list of possible hostname completions may be changed while the shell is running; the next time hostname completion is attempted after the value is changed, bash adds the contents of the new file to the existing list. If HOSTFILE is set, but has no value, bash attempts to read /etc/hosts to obtain the list of possible hostname completions. When HOSTFILE is unset, the hostname list is cleared. IFS The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is ``<space><tab><newline>''. IGNOREEOF Controls the action of an interactive shell on receipt of an EOF character as the sole input. If set, the value is the number of consecutive EOF characters which must be typed as the first characters on an input line before bash exits. If the variable exists but does not have a numeric value, or has no value, the default value is 10. If it does not exist, EOF signifies the end of input to the shell. INPUTRC The filename for the readline startup file, overriding the default of ~/.inputrc (see READLINE below). LANG Used to determine the locale category for any category not specifically selected with a variable starting with LC_. LC_ALL This variable overrides the value of LANG and any other LC_ variable specifying a locale category. LC_COLLATE This variable determines the collation order used when sorting the results of pathname expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within pathname expansion and pattern matching. LC_CTYPE This variable determines the interpretation of characters and the behavior of character classes within pathname expansion and pattern matching. LC_MESSAGES This variable determines the locale used to translate double- quoted strings preceded by a $. LC_NUMERIC This variable determines the locale category used for number formatting. LINES Used by the select builtin command to determine the column length for printing selection lists. Automatically set upon receipt of a SIGWINCH. MAIL If this parameter is set to a file name and the MAILPATH variable is not set, bash informs the user of the arrival of mail in the specified file. MAILCHECK Specifies how often (in seconds) bash checks for mail. The default is 60 seconds. When it is time to check for mail, the shell does so before displaying the primary prompt. If this variable is unset, or set to a value that is not a number greater than or equal to zero, the shell disables mail checking. MAILPATH A colon-separated list of file names to be checked for mail. The message to be printed when mail arrives in a particular file may be specified by separating the file name from the message with a `?'. When used in the text of the message, $_ expands to the name of the current mailfile. Example: MAILPATH='/var/mail/bfox?"You have mail":~/shell-mail?"$_ has mail!"' Bash supplies a default value for this variable, but the location of the user mail files that it uses is system dependent (e.g., /var/mail/$USER). OPTERR If set to the value 1, bash displays error messages generated by the getopts builtin command (see SHELL BUILTIN COMMANDS below). OPTERR is initialized to 1 each time the shell is invoked or a shell script is executed. PATH The search path for commands. It is a colon-separated list of directories in which the shell looks for commands (see COMMAND EXECUTION below). A zero-length (null) directory name in the value of PATH indicates the current directory. A null directory name may appear as two adjacent colons, or as an initial or trailing colon. The default path is system-dependent, and is set by the administrator who installs bash. A common value is ``/usr/gnu/bin:/usr/local/bin:/usr/ucb:/bin:/usr/bin''. POSIXLY_CORRECT If this variable is in the environment when bash starts, the shell enters posix mode before reading the startup files, as if the --posix invocation option had been supplied. If it is set while the shell is running, bash enables posix mode, as if the command set -o posix had been executed. PROMPT_COMMAND If set, the value is executed as a command prior to issuing each primary prompt. PS1 The value of this parameter is expanded (see PROMPTING below) and used as the primary prompt string. The default value is ``\s-\v\$ ''. PS2 The value of this parameter is expanded as with PS1 and used as the secondary prompt string. The default is ``> ''. PS3 The value of this parameter is used as the prompt for the select command (see SHELL GRAMMAR above). PS4 The value of this parameter is expanded as with PS1 and the value is printed before each command bash displays during an execution trace. The first character of PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is ``+ ''. SHELL The full pathname to the shell is kept in this environment variable. If it is not set when the shell starts, bash assigns to it the full pathname of the current user's login shell. TIMEFORMAT The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The % character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions. %% A literal %. %[p][l]R The elapsed time in seconds. %[p][l]U The number of CPU seconds spent in user mode. %[p][l]S The number of CPU seconds spent in system mode. %P The CPU percentage, computed as (%U + %S) / %R. The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used. The optional l specifies a longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included. If this variable is not set, bash acts as if it had the value $'\nreal\t%3lR\nuser\t%3lU\nsys%3lS'. If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed. TMOUT If set to a value greater than zero, TMOUT is treated as the default timeout for the read builtin. The select command terminates if input does not arrive after TMOUT seconds when input is coming from a terminal. In an interactive shell, the value is interpreted as the number of seconds to wait for input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if input does not arrive. TMPDIR If set, Bash uses its value as the name of a directory in which Bash creates temporary files for the shell's use. auto_resume This variable controls how the shell interacts with the user and job control. If this variable is set, single word simple commands without redirections are treated as candidates for resumption of an existing stopped job. There is no ambiguity allowed; if there is more than one job beginning with the string typed, the job most recently accessed is selected. The name of a stopped job, in this context, is the command line used to start it. If set to the value exact, the string supplied must match the name of a stopped job exactly; if set to substring, the string supplied needs to match a substring of the name of a stopped job. The substring value provides functionality analogous to the %? job identifier (see JOB CONTROL below). If set to any other value, the supplied string must be a prefix of a stopped job's name; this provides functionality analogous to the %string job identifier. histchars The two or three characters which control history expansion and tokenization (see HISTORY EXPANSION below). The first character is the history expansion character, the character which signals the start of a history expansion, normally `!'. The second character is the quick substitution character, which is used as shorthand for re-running the previous command entered, substituting one string for another in the command. The default is `^'. The optional third character is the character which indicates that the remainder of the line is a comment when found as the first character of a word, normally `#'. The history comment character causes history substitution to be skipped for the remaining words on the line. It does not necessarily cause the shell parser to treat the rest of the line as a comment. Arrays Bash provides one-dimensional array variables. Any variable may be used as an array; the declare builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously. Arrays are indexed using integers and are zero-based. An array is created automatically if any variable is assigned to using the syntax name[subscript]=value. The subscript is treated as an arithmetic expression that must evaluate to a number greater than or equal to zero. To explicitly declare an array, use declare -a name (see SHELL BUILTIN COMMANDS below). declare -a name[subscript] is also accepted; the subscript is ignored. Attributes may be specified for an array variable using the declare and readonly builtins. Each attribute applies to all members of an array. Arrays are assigned to using compound assignments of the form name=(value1 ... valuen), where each value is of the form [subscript]=string. Only string is required. If the optional brackets and subscript are supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. Indexing starts at zero. This syntax is also accepted by the declare builtin. Individual array elements may be assigned to using the name[subscript]=value syntax introduced above. Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with pathname expansion. If subscript is @ or *, the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word. When there are no array members, ${name[@]} expands to nothing. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. This is analogous to the expansion of the special parameters * and @ (see Special Parameters above). ${#name[subscript]} expands to the length of ${name[subscript]}. If subscript is * or @, the expansion is the number of elements in the array. Referencing an array variable without a subscript is equivalent to referencing element zero. The unset builtin is used to destroy arrays. unset name[subscript] destroys the array element at index subscript. Care must be taken to avoid unwanted side effects caused by filename generation. unset name, where name is an array, or unset name[subscript], where subscript is * or @, removes the entire array. The declare, local, and readonly builtins each accept a -a option to specify an array. The read builtin accepts a -a option to assign a list of words read from the standard input to an array. The set and declare builtins display array values in a way that allows them to be reused as assignments. EXPANSION Expansion is performed on the command line after it has been split into words. There are seven kinds of expansion performed: brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, word splitting, and pathname expansion. The order of expansions is: brace expansion, tilde expansion, parameter, variable and arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and pathname expansion. On systems that can support it, there is an additional expansion available: process substitution. Only brace expansion, word splitting, and pathname expansion can change the number of words of the expansion; other expansions expand a single word to a single word. The only exceptions to this are the expansions of "$@" and "${name[@]}" as explained above (see PARAMETERS). Brace Expansion Brace expansion is a mechanism by which arbitrary strings may be generated. This mechanism is similar to pathname expansion, but the filenames generated need not exist. Patterns to be brace expanded take the form of an optional preamble, followed by either a series of comma- separated strings or a sequence expression between a pair of braces, followed by an optional postscript. The preamble is prefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left to right. Brace expansions may be nested. The results of each expanded string are not sorted; left to right order is preserved. For example, a{d,c,b}e expands into `ade ace abe'. A sequence expression takes the form {x..y}, where x and y are either integers or single characters. When integers are supplied, the expression expands to each number between x and y, inclusive. When characters are supplied, the expression expands to each character lexicographically between x and y, inclusive. Note that both x and y must be of the same type. Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces. A correctly-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a valid sequence expression. Any incorrectly formed brace expansion is left unchanged. A { or , may be quoted with a backslash to prevent its being considered part of a brace expression. To avoid conflicts with parameter expansion, the string ${ is not considered eligible for brace expansion. This construct is typically used as shorthand when the common prefix of the strings to be generated is longer than in the above example: mkdir /usr/local/src/bash/{old,new,dist,bugs} or chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}} Brace expansion introduces a slight incompatibility with historical versions of sh. sh does not treat opening or closing braces specially when they appear as part of a word, and preserves them in the output. Bash removes braces from words as a consequence of brace expansion. For example, a word entered to sh as file{1,2} appears identically in the output. The same word is output as file1 file2 after expansion by bash. If strict compatibility with sh is desired, start bash with the +B option or disable brace expansion with the +B option to the set command (see SHELL BUILTIN COMMANDS below). Tilde Expansion If a word begins with an unquoted tilde character (`~'), all of the characters preceding the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name. If this login name is the null string, the tilde is replaced with the value of the shell parameter HOME. If HOME is unset, the home directory of the user executing the shell is substituted instead. Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name. If the tilde-prefix is a `~+', the value of the shell variable PWD replaces the tilde-prefix. If the tilde-prefix is a `~-', the value of the shell variable OLDPWD, if it is set, is substituted. If the characters following the tilde in the tilde-prefix consist of a number N, optionally prefixed by a `+' or a `-', the tilde-prefix is replaced with the corresponding element from the directory stack, as it would be displayed by the dirs builtin invoked with the tilde-prefix as an argument. If the characters following the tilde in the tilde-prefix consist of a number without a leading `+' or `-', `+' is assumed. If the login name is invalid, or the tilde expansion fails, the word is unchanged. Each variable assignment is checked for unquoted tilde-prefixes immediately following a : or the first =. In these cases, tilde expansion is also performed. Consequently, one may use file names with tildes in assignments to PATH, MAILPATH, and CDPATH, and the shell assigns the expanded value. Parameter Expansion The `$' character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name. When braces are used, the matching ending brace is the first `}' not escaped by a backslash or within a quoted string, and not within an embedded arithmetic expansion, command substitution, or parameter expansion. ${parameter} The value of parameter is substituted. The braces are required when parameter is a positional parameter with more than one digit, or when parameter is followed by a character which is not to be interpreted as part of its name. If the first character of parameter is an exclamation point, a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection. In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. When not performing substring expansion, bash tests for a parameter that is unset or null; omitting the colon results in a test only for a parameter that is unset. ${parameter:-word} Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted. ${parameter:=word} Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way. ${parameter:?word} Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted. ${parameter:+word} Use Alternate Value. If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted. ${parameter:offset} ${parameter:offset:length} Substring Expansion. Expands to up to length characters of parameter starting at the character specified by offset. If length is omitted, expands to the substring of parameter starting at the character specified by offset. length and offset are arithmetic expressions (see ARITHMETIC EVALUATION below). length must evaluate to a number greater than or equal to zero. If offset evaluates to a number less than zero, the value is used as an offset from the end of the value of parameter. If parameter is @, the result is length positional parameters beginning at offset. If parameter is an array name indexed by @ or *, the result is the length members of the array beginning with ${parameter[offset]}. A negative offset is taken relative to one greater than the maximum index of the specified array. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the :- expansion. Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1. ${!prefix*} ${!prefix@} Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable. ${!name[@]} ${!name[*]} If name is an array variable, expands to the list of array indices (keys) assigned in name. If name is not an array, expands to 0 if name is set and null otherwise. When @ is used and the expansion appears within double quotes, each key expands to a separate word. ${#parameter} The length in characters of the value of parameter is substituted. If parameter is * or @, the value substituted is the number of positional parameters. If parameter is an array name subscripted by * or @, the value substituted is the number of elements in the array. ${parameter#word} ${parameter##word} The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ``#'' case) or the longest matching pattern (the ``##'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter%word} ${parameter%%word} The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ``%'' case) or the longest matching pattern (the ``%%'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter/pattern/string} The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If Ipattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with #, it must match at the beginning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is @ or *, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list. Command Substitution Command substitution allows the output of a command to replace the command name. There are two forms: $(command) or `command` Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file). When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially. Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes. If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results. Arithmetic Expansion Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is: $((expression)) The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter expansion, string expansion, command substitution, and quote removal. Arithmetic expansions may be nested. The evaluation is performed according to the rules listed below under ARITHMETIC EVALUATION. If expression is invalid, bash prints a message indicating failure and no substitution occurs. Process Substitution Process substitution is supported on systems that support named pipes (FIFOs) or the /dev/fd method of naming open files. It takes the form of <(list) or >(list). The process list is run with its input or output connected to a FIFO or some file in /dev/fd. The name of this file is passed as an argument to the current command as the result of the expansion. If the >(list) form is used, writing to the file will provide input for list. If the <(list) form is used, the file passed as an argument should be read to obtain the output of list. When available, process substitution is performed simultaneously with parameter and variable expansion, command substitution, and arithmetic expansion. Word Splitting The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting. The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IFS is unset, or its value is exactly <space><tab><newline>, the default, then any sequence of IFS characters serves to delimit words. If IFS has a value other than the default, then sequences of the whitespace characters space and tab are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS whitespace character). Any character in IFS that is not IFS whitespace, along with any adjacent IFS whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS is null, no word splitting occurs. Explicit null arguments ("" or '') are retained. Unquoted implicit null arguments, resulting from the expansion of parameters that have no values, are removed. If a parameter with no value is expanded within double quotes, a null argument results and is retained. Note that if no expansion occurs, no splitting is performed. Pathname Expansion After word splitting, unless the -f option has been set, bash scans each word for the characters *, ?, and [. If one of these characters appears, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of file names matching the pattern. If no matching file names are found, and the shell option nullglob is disabled, the word is left unchanged. If the nullglob option is set, and no matches are found, the word is removed. If the failglob shell option is set, and no matches are found, an error message is printed and the command is not executed. If the shell option nocaseglob is enabled, the match is performed without regard to the case of alphabetic characters. When a pattern is used for pathname expansion, the character ``.'' at the start of a name or immediately following a slash must be matched explicitly, unless the shell option dotglob is set. When matching a pathname, the slash character must always be matched explicitly. In other cases, the ``.'' character is not treated specially. See the description of shopt below under SHELL BUILTIN COMMANDS for a description of the nocaseglob, nullglob, failglob, and dotglob shell options. The GLOBIGNORE shell variable may be used to restrict the set of file names matching a pattern. If GLOBIGNORE is set, each matching file name that also matches one of the patterns in GLOBIGNORE is removed from the list of matches. The file names ``.'' and ``..'' are always ignored when GLOBIGNORE is set and not null. However, setting GLOBIGNORE to a non-null value has the effect of enabling the dotglob shell option, so all other file names beginning with a ``.'' will match. To get the old behavior of ignoring file names beginning with a ``.'', make ``.*'' one of the patterns in GLOBIGNORE. The dotglob option is disabled when GLOBIGNORE is unset. Pattern Matching Any character that appears in a pattern, other than the special pattern characters described below, matches itself. The NUL character may not occur in a pattern. A backslash escapes the following character; the escaping backslash is discarded when matching. The special pattern characters must be quoted if they are to be matched literally. The special pattern characters have the following meanings: * Matches any string, including the null string. ? Matches any single character. [...] Matches any one of the enclosed characters. A pair of characters separated by a hyphen denotes a range expression; any character that sorts between those two characters, inclusive, using the current locale's collating sequence and character set, is matched. If the first character following the [ is a ! or a ^ then any character not enclosed is matched. The sorting order of characters in range expressions is determined by the current locale and the value of the LC_COLLATE shell variable, if set. A - may be matched by including it as the first or last character in the set. A ] may be matched by including it as the first character in the set. Within [ and ], character classes can be specified using the syntax [:class:], where class is one of the following classes defined in the POSIX standard: alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigit A character class matches any character belonging to that class. The word character class matches letters, digits, and the character _. Within [ and ], an equivalence class can be specified using the syntax [=c=], which matches all characters with the same collation weight (as defined by the current locale) as the character c. Within [ and ], the syntax [.symbol.] matches the collating symbol symbol. If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. In the following description, a pattern-list is a list of one or more patterns separated by a |. Composite patterns may be formed using one or more of the following sub-patterns: ?(pattern-list) Matches zero or one occurrence of the given patterns *(pattern-list) Matches zero or more occurrences of the given patterns +(pattern-list) Matches one or more occurrences of the given patterns @(pattern-list) Matches one of the given patterns !(pattern-list) Matches anything except one of the given patterns Quote Removal After the preceding expansions, all unquoted occurrences of the characters \, ', and " that did not result from one of the above expansions are removed. REDIRECTION Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redirection may also be used to open and close files for the current shell execution environment. The following redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right. In the following descriptions, if the file descriptor number is omitted, and the first character of the redirection operator is <, the redirection refers to the standard input (file descriptor 0). If the first character of the redirection operator is >, the redirection refers to the standard output (file descriptor 1). The word following the redirection operator in the following descriptions, unless otherwise noted, is subjected to brace expansion, tilde expansion, parameter expansion, command substitution, arithmetic expansion, quote removal, pathname expansion, and word splitting. If it expands to more than one word, bash reports an error. Note that the order of redirections is significant. For example, the command ls > dirlist 2>&1 directs both standard output and standard error to the file dirlist, while the command ls 2>&1 > dirlist directs only the standard output to file dirlist, because the standard error was duplicated as standard output before the standard output was redirected to dirlist. Bash handles several filenames specially when they are used in redirections, as described in the following table: /dev/fd/fd If fd is a valid integer, file descriptor fd is duplicated. /dev/stdin File descriptor 0 is duplicated. /dev/stdout File descriptor 1 is duplicated. /dev/stderr File descriptor 2 is duplicated. /dev/tcp/host/port If host is a valid hostname or Internet address, and port is an integer port number or service name, bash attempts to open a TCP connection to the corresponding socket. /dev/udp/host/port If host is a valid hostname or Internet address, and port is an integer port number or service name, bash attempts to open a UDP connection to the corresponding socket. A failure to open or create a file causes the redirection to fail. Redirections using file descriptors greater than 9 should be used with care, as they may conflict with file descriptors the shell uses internally. Redirecting Input Redirection of input causes the file whose name results from the expansion of word to be opened for reading on file descriptor n, or the standard input (file descriptor 0) if n is not specified. The general format for redirecting input is: [n]<word Redirecting Output Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size. The general format for redirecting output is: [n]>word If the redirection operator is >, and the noclobber option to the set builtin has been enabled, the redirection will fail if the file whose name results from the expansion of word exists and is a regular file. If the redirection operator is >|, or the redirection operator is > and the noclobber option to the set builtin command is not enabled, the redirection is attempted even if the file named by word exists. Appending Redirected Output Redirection of output in this fashion causes the file whose name results from the expansion of word to be opened for appending on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created. The general format for appending output is: [n]>>word Redirecting Standard Output and Standard Error Bash allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirected to the file whose name is the expansion of word with this construct. There are two formats for redirecting standard output and standard error: &>word and >&word Of the two forms, the first is preferred. This is semantically equivalent to >word 2>&1 Here Documents This type of redirection instructs the shell to read input from the current source until a line containing only word (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input for a command. The format of here-documents is: <<[-]word here-document delimiter No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `. If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion. Here Strings A variant of here documents, the format is: <<<word The word is expanded and supplied to the command on its standard input. Duplicating File Descriptors The redirection operator [n]<&word is used to duplicate input file descriptors. If word expands to one or more digits, the file descriptor denoted by n is made to be a copy of that file descriptor. If the digits in word do not specify a file descriptor open for input, a redirection error occurs. If word evaluates to -, file descriptor n is closed. If n is not specified, the standard input (file descriptor 0) is used. The operator [n]>&word is used similarly to duplicate output file descriptors. If n is not specified, the standard output (file descriptor 1) is used. If the digits in word do not specify a file descriptor open for output, a redirection error occurs. As a special case, if n is omitted, and word does not expand to one or more digits, the standard output and standard error are redirected as described previously. Moving File Descriptors The redirection operator [n]<&digit- moves the file descriptor digit to file descriptor n, or the standard input (file descriptor 0) if n is not specified. digit is closed after being duplicated to n. Similarly, the redirection operator [n]>&digit- moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1) if n is not specified. Opening File Descriptors for Reading and Writing The redirection operator [n]<>word causes the file whose name is the expansion of word to be opened for both reading and writing on file descriptor n, or on file descriptor 0 if n is not specified. If the file does not exist, it is created. ALIASES Aliases allow a string to be substituted for a word when it is used as the first word of a simple command. The shell maintains a list of aliases that may be set and unset with the alias and unalias builtin commands (see SHELL BUILTIN COMMANDS below). The first word of each simple command, if unquoted, is checked to see if it has an alias. If so, that word is replaced by the text of the alias. The characters /, $, `, and = and any of the shell metacharacters or quoting characters listed above may not appear in an alias name. The replacement text may contain any valid shell input, including shell metacharacters. The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias ls to ls -F, for instance, and bash does not try to recursively expand the replacement text. If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion. Aliases are created and listed with the alias command, and removed with the unalias command. There is no mechanism for using arguments in the replacement text. If arguments are needed, a shell function should be used (see FUNCTIONS below). Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below). The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input before executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias. This behavior is also an issue when functions are executed. Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a compound command. As a consequence, aliases defined in a function are not available until after that function is executed. To be safe, always put alias definitions on a separate line, and do not use alias in compound commands. For almost every purpose, aliases are superseded by shell functions. FUNCTIONS A shell function, defined as described above under SHELL GRAMMAR, stores a series of commands for later execution. When the name of a shell function is used as a simple command name, the list of commands associated with that function name is executed. Functions are executed in the context of the current shell; no new process is created to interpret them (contrast this with the execution of a shell script). When a function is executed, the arguments to the function become the positional parameters during its execution. The special parameter # is updated to reflect the change. Special parameter 0 is unchanged. The first element of the FUNCNAME variable is set to the name of the function while the function is executing. All other aspects of the shell execution environment are identical between a function and its caller with the exception that the DEBUG and RETURN traps (see the description of the trap builtin under SHELL BUILTIN COMMANDS below) are not inherited unless the function has been given the trace attribute (see the description of the declare builtin below) or the -o functrace shell option has been enabled with the set builtin (in which case all functions inherit the DEBUG and RETURN traps). Variables local to the function may be declared with the local builtin command. Ordinarily, variables and their values are shared between the function and its caller. If the builtin command return is executed in a function, the function completes and execution resumes with the next command after the function call. Any command associated with the RETURN trap is executed before execution resumes. When a function completes, the values of the positional parameters and the special parameter # are restored to the values they had prior to the function's execution. Function names and definitions may be listed with the -f option to the declare or typeset builtin commands. The -F option to declare or typeset will list the function names only (and optionally the source file and line number, if the extdebug shell option is enabled). Functions may be exported so that subshells automatically have them defined with the -f option to the export builtin. A function definition may be deleted using the -f option to the unset builtin. Note that shell functions and variables with the same name may result in multiple identically-named entries in the environment passed to the shell's children. Care should be taken in cases where this may cause a problem. Functions may be recursive. No limit is imposed on the number of recursive calls. ARITHMETIC EVALUATION The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let and declare builtin commands and Arithmetic Expansion). Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error. The operators and their precedence, associativity, and values are the same as in the C language. The following list of operators is grouped into levels of equal-precedence operators. The levels are listed in order of decreasing precedence. id++ id-- variable post-increment and post-decrement ++id --id variable pre-increment and pre-decrement - + unary minus and plus ! ~ logical and bitwise negation ** exponentiation * / % multiplication, division, remainder + - addition, subtraction << >> left and right bitwise shifts <= >= < > comparison == != equality and inequality & bitwise AND ^ bitwise exclusive OR | bitwise OR && logical AND || logical OR expr?expr:expr conditional operator = *= /= %= += -= <<= >>= &= ^= |= assignment expr1 , expr2 comma Shell variables are allowed as operands; parameter expansion is performed before the expression is evaluated. Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax. A shell variable that is null or unset evaluates to 0 when referenced by name without using the parameter expansion syntax. The value of a variable is evaluated as an arithmetic expression when it is referenced, or when a variable which has been given the integer attribute using declare -i is assigned a value. A null value evaluates to 0. A shell variable need not have its integer attribute turned on to be used in an expression. Constants with a leading 0 are interpreted as octal numbers. A leading 0x or 0X denotes hexadecimal. Otherwise, numbers take the form [base#]n, where base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used. The digits greater than 9 are represented by the lowercase letters, the uppercase letters, @, and _, in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably to represent numbers between 10 and 35. Operators are evaluated in order of precedence. Sub-expressions in parentheses are evaluated first and may override the precedence rules above. CONDITIONAL EXPRESSIONS Conditional expressions are used by the [[ compound command and the test and [ builtin commands to test file attributes and perform string and arithmetic comparisons. Expressions are formed from the following unary or binary primaries. If any file argument to one of the primaries is of the form /dev/fd/n, then file descriptor n is checked. If the file argument to one of the primaries is one of /dev/stdin, /dev/stdout, or /dev/stderr, file descriptor 0, 1, or 2, respectively, is checked. Unless otherwise specified, primaries that operate on files follow symbolic links and operate on the target of the link, rather than the link itself. -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 is set-group-id. -h file True if file exists and is a symbolic link. -k file True if file exists and its ``sticky'' bit is set. -p file True if file exists and is a named pipe (FIFO). -r file True if file exists and is readable. -s file True if file exists and has a size greater than zero. -t fd True if file descriptor fd is open and refers to a terminal. -u file True if file exists and its set-user-id bit is set. -w file True if file exists and is writable. -x file True if file exists and is executable. -O file True if file exists and is owned by the effective user id. -G file True if file exists and is owned by the effective group id. -L file True if file exists and is a symbolic link. -S file True if file exists and is a socket. -N file True if file exists and has been modified since it was last read. file1 -nt file2 True if file1 is newer (according to modification date) than file2, or if file1 exists and file2 does not. file1 -ot file2 True if file1 is older than file2, or if file2 exists and file1 does not. file1 -ef file2 True if file1 and file2 refer to the same device and inode numbers. -o optname True if shell option optname is enabled. See the list of options under the description of the -o option to the set builtin below. -z string True if the length of string is zero. string -n string True if the length of string is non-zero. string1 == string2 True if the strings are equal. = may be used in place of == for strict POSIX compliance. string1 != string2 True if the strings are not equal. string1 < string2 True if string1 sorts before string2 lexicographically in the current locale. string1 > string2 True if string1 sorts after string2 lexicographically in the current locale. arg1 OP arg2 OP is one of -eq, -ne, -lt, -le, -gt, or -ge. These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively. Arg1 and arg2 may be positive or negative integers. SIMPLE COMMAND EXPANSION When a simple command is executed, the shell performs the following expansions, assignments, and redirections, from left to right. 1. The words that the parser has marked as variable assignments (those preceding the command name) and redirections are saved for later processing. 2. The words that are not variable assignments or redirections are expanded. If any words remain after expansion, the first word is taken to be the name of the command and the remaining words are the arguments. 3. Redirections are performed as described above under REDIRECTION. 4. The text after the = in each variable assignment undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal before being assigned to the variable. If no command name results, the variable assignments affect the current shell environment. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment. If any of the assignments attempts to assign a value to a readonly variable, an error occurs, and the command exits with a non- zero status. If no command name results, redirections are performed, but do not affect the current shell environment. A redirection error causes the command to exit with a non-zero status. If there is a command name left after expansion, execution proceeds as described below. Otherwise, the command exits. If one of the expansions contained a command substitution, the exit status of the command is the exit status of the last command substitution performed. If there were no command substitutions, the command exits with a status of zero. COMMAND EXECUTION After a command has been split into words, if it results in a simple command and an optional list of arguments, the following actions are taken. If the command name contains no slashes, the shell attempts to locate it. If there exists a shell function by that name, that function is invoked as described above in FUNCTIONS. If the name does not match a function, the shell searches for it in the list of shell builtins. If a match is found, that builtin is invoked. If the name is neither a shell function nor a builtin, and contains no slashes, bash searches each element of the PATH for a directory containing an executable file by that name. Bash uses a hash table to remember the full pathnames of executable files (see hash under SHELL BUILTIN COMMANDS below). A full search of the directories in PATH is performed only if the command is not found in the hash table. If the search is unsuccessful, the shell prints an error message and returns an exit status of 127. If the search is successful, or if the command name contains one or more slashes, the shell executes the named program in a separate execution environment. Argument 0 is set to the name given, and the remaining arguments to the command are set to the arguments given, if any. If this 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, a file containing shell commands. A subshell is spawned to execute it. This subshell reinitializes itself, so that the effect is as if a new shell had been invoked to handle the script, with the exception that the locations of commands remembered by the parent (see hash below under SHELL BUILTIN COMMANDS) are retained by the child. If the program is a file beginning with #!, the remainder of the first line specifies an interpreter for the program. The shell executes the specified interpreter on operating systems that do not handle this executable format themselves. The arguments to the interpreter consist of a single optional argument following the interpreter name on the first line of the program, followed by the name of the program, followed by the command arguments, if any. COMMAND EXECUTION ENVIRONMENT The shell has an execution environment, which consists of the following: • open files inherited by the shell at invocation, as modified by redirections supplied to the exec builtin • the current working directory as set by cd, pushd, or popd, or inherited by the shell at invocation • the file creation mode mask as set by umask or inherited from the shell's parent • current traps set by trap • shell parameters that are set by variable assignment or with set or inherited from the shell's parent in the environment • shell functions defined during execution or inherited from the shell's parent in the environment • options enabled at invocation (either by default or with command-line arguments) or by set • options enabled by shopt • shell aliases defined with alias • various process IDs, including those of background jobs, the value of $$, and the value of $PPID When a simple command other than a builtin or shell function is to be executed, it is invoked in a separate execution environment that consists of the following. Unless otherwise noted, the values are inherited from the shell. • the shell's open files, plus any modifications and additions specified by redirections to the command • the current working directory • the file creation mode mask • shell variables and functions marked for export, along with variables exported for the command, passed in the environment • traps caught by the shell are reset to the values inherited from the shell's parent, and traps ignored by the shell are ignored A command invoked in this separate environment cannot affect the shell's execution environment. Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its parent at invocation. Builtin commands that are invoked as part of a pipeline are also executed in a subshell environment. Changes made to the subshell environment cannot affect the shell's execution environment. If a command is followed by a & and job control is not active, the default standard input for the command is the empty file /dev/null. Otherwise, the invoked command inherits the file descriptors of the calling shell as modified by redirections. ENVIRONMENT When a program is invoked it is given an array of strings called the environment. This is a list of name-value pairs, of the form name=value. The shell provides several ways to manipulate the environment. On invocation, the shell scans its own environment and creates a parameter for each name found, automatically marking it for export to child processes. Executed commands inherit the environment. The export and declare -x commands allow parameters and functions to be added to and deleted from the environment. If the value of a parameter in the environment is modified, the new value becomes part of the environment, replacing the old. The environment inherited by any executed command consists of the shell's initial environment, whose values may be modified in the shell, less any pairs removed by the unset command, plus any additions via the export and declare -x commands. The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described above in PARAMETERS. These assignment statements affect only the environment seen by that command. If the -k option is set (see the set builtin command below), then all parameter assignments are placed in the environment for a command, not just those that precede the command name. When bash invokes an external command, the variable _ is set to the full file name of the command and passed to that command in its environment. EXIT STATUS For the shell's purposes, a command which exits with a zero exit status has succeeded. An exit status of zero indicates success. A non-zero exit status indicates failure. When a command terminates on a fatal signal N, bash uses the value of 128+N as the exit status. If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not executable, the return status is 126. If a command fails because of an error during expansion or redirection, the exit status is greater than zero. Shell builtin commands return a status of 0 (true) if successful, and non-zero (false) if an error occurs while they execute. All builtins return an exit status of 2 to indicate incorrect usage. Bash itself returns the exit status of the last command executed, unless a syntax error occurs, in which case it exits with a non-zero value. See also the exit builtin command below. SIGNALS When bash is interactive, in the absence of any traps, it ignores SIGTERM (so that kill 0 does not kill an interactive shell), and SIGINT is caught and handled (so that the wait builtin is interruptible). In all cases, bash ignores SIGQUIT. If job control is in effect, bash ignores SIGTTIN, SIGTTOU, and SIGTSTP. Non-builtin commands run by bash have signal handlers set to the values inherited by the shell from its parent. When job control is not in effect, asynchronous commands ignore SIGINT and SIGQUIT in addition to these inherited handlers. Commands run as a result of command substitution ignore the keyboard-generated job control signals SIGTTIN, SIGTTOU, and SIGTSTP. The shell exits by default upon receipt of a SIGHUP. Before exiting, an interactive shell resends the SIGHUP to all jobs, running or stopped. Stopped jobs are sent SIGCONT to ensure that they receive the SIGHUP. To prevent the shell from sending the signal to a particular job, it should be removed from the jobs table with the disown builtin (see SHELL BUILTIN COMMANDS below) or marked to not receive SIGHUP using disown -h. If the huponexit shell option has been set with shopt, bash sends a SIGHUP to all jobs when an interactive login shell exits. If bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes. When bash is waiting for an asynchronous command via the wait builtin, the reception of a signal for which a trap has been set will cause the wait builtin to return immediately with an exit status greater than 128, immediately after which the trap is executed. JOB CONTROL Job control refers to the ability to selectively stop (suspend) the execution of processes and continue (resume) their execution at a later point. A user typically employs this facility via an interactive interface supplied jointly by the system's terminal driver and bash. The shell associates a job with each pipeline. It keeps a table of currently executing jobs, which may be listed with the jobs command. When bash starts a job asynchronously (in the background), it prints a line that looks like: [1] 25647 indicating that this job is job number 1 and that the process ID of the last process in the pipeline associated with this job is 25647. All of the processes in a single pipeline are members of the same job. Bash uses the job abstraction as the basis for job control. To facilitate the implementation of the user interface to job control, the operating system maintains the notion of a current terminal process group ID. Members of this process group (processes whose process group ID is equal to the current terminal process group ID) receive keyboard- generated signals such as SIGINT. These processes are said to be in the foreground. Background processes are those whose process group ID differs from the terminal's; such processes are immune to keyboard- generated signals. Only foreground processes are allowed to read from or write to the terminal. Background processes which attempt to read from (write to) the terminal are sent a SIGTTIN (SIGTTOU) signal by the terminal driver, which, unless caught, suspends the process. If the operating system on which bash is running supports job control, bash contains facilities to use it. Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. Typing the delayed suspend character (typically ^Y, Control-Y) causes the process to be stopped when it attempts to read input from the terminal, and control to be returned to bash. The user may then manipulate the state of this job, using the bg command to continue it in the background, the fg command to continue it in the foreground, or the kill command to kill it. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded. There are a number of ways to refer to a job in the shell. The character % introduces a job name. Job number n may be referred to as %n. A job may also be referred to using a prefix of the name used to start it, or using a substring that appears in its command line. For example, %ce refers to a stopped ce job. If a prefix matches more than one job, bash reports an error. Using %?ce, on the other hand, refers to any job containing the string ce in its command line. If the substring matches more than one job, bash reports an error. The symbols %% and %+ refer to the shell's notion of the current job, which is the last job stopped while it was in the foreground or started in the background. The previous job may be referenced using %-. In output pertaining to jobs (e.g., the output of the jobs command), the current job is always flagged with a +, and the previous job with a -. A single % (with no accompanying job specification) also refers to the current job. Simply naming a job can be used to bring it into the foreground: %1 is a synonym for ``fg %1'', bringing job 1 from the background into the foreground. Similarly, ``%1 &'' resumes job 1 in the background, equivalent to ``bg %1''. The shell learns immediately whenever a job changes state. Normally, bash waits until it is about to print a prompt before reporting changes in a job's status so as to not interrupt any other output. If the -b option to the set builtin command is enabled, bash reports such changes immediately. Any trap on SIGCHLD is executed for each child that exits. If an attempt to exit bash is made while jobs are stopped, the shell prints a warning message. The jobs command may then be used to inspect their status. If a second attempt to exit is made without an intervening command, the shell does not print another warning, and the stopped jobs are terminated. PROMPTING When executing interactively, bash displays the primary prompt PS1 when it is ready to read a command, and the secondary prompt PS2 when it needs more input to complete a command. Bash allows these prompt strings to be customized by inserting a number of backslash-escaped special characters that are decoded as follows: \a an ASCII bell character (07) \d the date in "Weekday Month Date" format (e.g., "Tue May 26") \D{format} the format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation. The braces are required \e an ASCII escape character (033) \h the hostname up to the first `.' \H the hostname \j the number of jobs currently managed by the shell \l the basename of the shell's terminal device name \n newline \r carriage return \s the name of the shell, the basename of $0 (the portion following the final slash) \t the current time in 24-hour HH:MM:SS format \T the current time in 12-hour HH:MM:SS format \@ the current time in 12-hour am/pm format \A the current time in 24-hour HH:MM format \u the username of the current user \v the version of bash (e.g., 2.00) \V the release of bash, version + patch level (e.g., 2.00.0) \w the current working directory, with $HOME abbreviated with a tilde \W the basename of the current working directory, with $HOME abbreviated with a tilde \! the history number of this command \# the command number of this command \$ if the effective UID is 0, a #, otherwise a $ \nnn the character corresponding to the octal number nnn \\ a backslash \[ begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt \] end a sequence of non-printing characters The command number and the history number are usually different: the history number of a command is its position in the history list, which may include commands restored from the history file (see HISTORY below), while the command number is the position in the sequence of commands executed during the current shell session. After the string is decoded, it is expanded via parameter expansion, command substitution, arithmetic expansion, and quote removal, subject to the value of the promptvars shell option (see the description of the shopt command under SHELL BUILTIN COMMANDS below). READLINE This is the library that handles reading input when using an interactive shell, unless the --noediting option is given at shell invocation. By default, the line editing commands are similar to those of emacs. A vi-style line editing interface is also available. To turn off line editing after the shell is running, use the +o emacs or +o vi options to the set builtin (see SHELL BUILTIN COMMANDS below). Readline Notation In this section, the emacs-style notation is used to denote keystrokes. Control keys are denoted by C-key, e.g., C-n means Control-N. Similarly, meta keys are denoted by M-key, so M-x means Meta-X. (On keyboards without a meta key, M-x means ESC x, i.e., press the Escape key then the x key. This makes ESC the meta prefix. The combination M-C-x means ESC-Control-x, or press the Escape key then hold the Control key while pressing the x key.) Readline commands may be given numeric arguments, which normally act as a repeat count. Sometimes, however, it is the sign of the argument that is significant. Passing a negative argument to a command that acts in the forward direction (e.g., kill-line) causes that command to act in a backward direction. Commands whose behavior with arguments deviates from this are noted below. When a command is described as killing text, the text deleted is saved for possible future retrieval (yanking). The killed text is saved in a kill ring. Consecutive kills cause the text to be accumulated into one unit, which can be yanked all at once. Commands which do not kill text separate the chunks of text on the kill ring. Readline Initialization Readline is customized by putting commands in an initialization file (the inputrc file). The name of this file is taken from the value of the INPUTRC variable. If that variable is unset, the default is ~/.inputrc. When a program which uses the readline library starts up, the initialization file is read, and the key bindings and variables are set. There are only a few basic constructs allowed in the readline initialization file. Blank lines are ignored. Lines beginning with a # are comments. Lines beginning with a $ indicate conditional constructs. Other lines denote key bindings and variable settings. The default key-bindings may be changed with an inputrc file. Other programs that use this library may add their own commands and bindings. For example, placing M-Control-u: universal-argument or C-Meta-u: universal-argument into the inputrc would make M-C-u execute the readline command universal-argument. The following symbolic character names are recognized: RUBOUT, DEL, ESC, LFD, NEWLINE, RET, RETURN, SPC, SPACE, and TAB. In addition to command names, readline allows keys to be bound to a string that is inserted when the key is pressed (a macro). Readline Key Bindings The syntax for controlling key bindings in the inputrc file is simple. All that is required is the name of the command or the text of a macro and a key sequence to which it should be bound. The name may be specified in one of two ways: as a symbolic key name, possibly with Meta- or Control- prefixes, or as a key sequence. When using the form keyname:function-name or macro, keyname is the name of a key spelled out in English. For example: Control-u: universal-argument Meta-Rubout: backward-kill-word Control-o: "> output" In the above example, C-u is bound to the function universal-argument, M-DEL is bound to the function backward-kill-word, and C-o is bound to run the macro expressed on the right hand side (that is, to insert the text ``> output'' into the line). In the second form, "keyseq":function-name or macro, keyseq differs from keyname above in that strings denoting an entire key sequence may be specified by placing the sequence within double quotes. Some GNU Emacs style key escapes can be used, as in the following example, but the symbolic character names are not recognized. "\C-u": universal-argument "\C-x\C-r": re-read-init-file "\e[11~": "Function Key 1" In this example, C-u is again bound to the function universal-argument. C-x C-r is bound to the function re-read-init-file, and ESC [ 1 1 ~ is bound to insert the text ``Function Key 1''. The full set of GNU Emacs style escape sequences is \C- control prefix \M- meta prefix \e an escape character \\ backslash \" literal " \' literal ' In addition to the GNU Emacs style escape sequences, a second set of backslash escapes is available: \a alert (bell) \b backspace \d delete \f form feed \n newline \r carriage return \t horizontal tab \v vertical tab \nnn the eight-bit character whose value is the octal value nnn (one to three digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) When entering the text of a macro, single or double quotes must be used to indicate a macro definition. Unquoted text is assumed to be a function name. In the macro body, the backslash escapes described above are expanded. Backslash will quote any other character in the macro text, including " and '. Bash allows the current readline key bindings to be displayed or modified with the bind builtin command. The editing mode may be switched during interactive use by using the -o option to the set builtin command (see SHELL BUILTIN COMMANDS below). Readline Variables Readline has variables that can be used to further customize its behavior. A variable may be set in the inputrc file with a statement of the form set variable-name value Except where noted, readline variables can take the values On or Off (without regard to case). Unrecognized variable names are ignored. When a variable value is read, empty or null values, "on" (case- insensitive), and "1" are equivalent to On. All other values are equivalent to Off. The variables and their default values are: bell-style (audible) Controls what happens when readline wants to ring the terminal bell. If set to none, readline never rings the bell. If set to visible, readline uses a visible bell if one is available. If set to audible, readline attempts to ring the terminal's bell. bind-tty-special-chars (On) If set to On, readline attempts to bind the control characters treated specially by the kernel's terminal driver to their readline equivalents. comment-begin (``#'') The string that is inserted when the readline insert-comment command is executed. This command is bound to M-# in emacs mode and to # in vi command mode. completion-ignore-case (Off) If set to On, readline performs filename matching and completion in a case-insensitive fashion. completion-query-items (100) This determines when the user is queried about viewing the number of possible completions generated by the possible-completions command. It may be set to any integer value greater than or equal to zero. If the number of possible completions is greater than or equal to the value of this variable, the user is asked whether or not he wishes to view them; otherwise they are simply listed on the terminal. convert-meta (On) If set to On, readline will convert characters with the eighth bit set to an ASCII key sequence by stripping the eighth bit and prefixing an escape character (in effect, using escape as the meta prefix). disable-completion (Off) If set to On, readline will inhibit word completion. Completion characters will be inserted into the line as if they had been mapped to self-insert. editing-mode (emacs) Controls whether readline begins with a set of key bindings similar to emacs or vi. editing-mode can be set to either emacs or vi. enable-keypad (Off) When set to On, readline will try to enable the application keypad when it is called. Some systems need this to enable the arrow keys. expand-tilde (Off) If set to on, tilde expansion is performed when readline attempts word completion. history-preserve-point (Off) If set to on, the history code attempts to place point at the same location on each history line retrieved with previous- history or next-history. horizontal-scroll-mode (Off) When set to On, makes readline use a single line for display, scrolling the input horizontally on a single screen line when it becomes longer than the screen width rather than wrapping to a new line. input-meta (Off) If set to On, readline will enable eight-bit input (that is, it will not strip the high bit from the characters it reads), regardless of what the terminal claims it can support. The name meta-flag is a synonym for this variable. isearch-terminators (``C-[C-J'') The string of characters that should terminate an incremental search without subsequently executing the character as a command. If this variable has not been given a value, the characters ESC and C-J will terminate an incremental search. keymap (emacs) Set the current readline keymap. The set of valid keymap names is emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-command, and vi-insert. vi is equivalent to vi-command; emacs is equivalent to emacs-standard. The default value is emacs; the value of editing-mode also affects the default keymap. mark-directories (On) If set to On, completed directory names have a slash appended. mark-modified-lines (Off) If set to On, history lines that have been modified are displayed with a preceding asterisk (*). mark-symlinked-directories (Off) If set to On, completed names which are symbolic links to directories have a slash appended (subject to the value of mark-directories). match-hidden-files (On) This variable, when set to On, causes readline to match files whose names begin with a `.' (hidden files) when performing filename completion, unless the leading `.' is supplied by the user in the filename to be completed. output-meta (Off) If set to On, readline will display characters with the eighth bit set directly rather than as a meta-prefixed escape sequence. page-completions (On) If set to On, readline uses an internal more-like pager to display a screenful of possible completions at a time. print-completions-horizontally (Off) If set to On, readline will display completions with matches sorted horizontally in alphabetical order, rather than down the screen. show-all-if-ambiguous (Off) This alters the default behavior of the completion functions. If set to on, words which have more than one possible completion cause the matches to be listed immediately instead of ringing the bell. show-all-if-unmodified (Off) This alters the default behavior of the completion functions in a fashion similar to show-all-if-ambiguous. If set to on, words which have more than one possible completion without any possible partial completion (the possible completions don't share a common prefix) cause the matches to be listed immediately instead of ringing the bell. visible-stats (Off) If set to On, a character denoting a file's type as reported by stat(2) is appended to the filename when listing possible completions. Readline Conditional Constructs Readline implements a facility similar in spirit to the conditional compilation features of the C preprocessor which allows key bindings and variable settings to be performed as the result of tests. There are four parser directives used. $if The $if construct allows bindings to be made based on the editing mode, the terminal being used, or the application using readline. The text of the test extends to the end of the line; no characters are required to isolate it. mode The mode= form of the $if directive is used to test whether readline is in emacs or vi mode. This may be used in conjunction with the set keymap command, for instance, to set bindings in the emacs-standard and emacs-ctlx keymaps only if readline is starting out in emacs mode. term The term= form may be used to include terminal-specific key bindings, perhaps to bind the key sequences output by the terminal's function keys. The word on the right side of the = is tested against the both full name of the terminal and the portion of the terminal name before the first -. This allows sun to match both sun and sun-cmd, for instance. application The application construct is used to include application- specific settings. Each program using the readline library sets the application name, and an initialization file can test for a particular value. This could be used to bind key sequences to functions useful for a specific program. For instance, the following command adds a key sequence that quotes the current or previous word in Bash: $if Bash # Quote the current or previous word "\C-xq": "\eb\"\ef\"" $endif $endif This command, as seen in the previous example, terminates an $if command. $else Commands in this branch of the $if directive are executed if the test fails. $include This directive takes a single filename as an argument and reads commands and bindings from that file. For example, the following directive would read /etc/inputrc: $include /etc/inputrc Searching Readline provides commands for searching through the command history (see HISTORY below) for lines containing a specified string. There are two search modes: incremental and non-incremental. Incremental searches begin before the user has finished typing the search string. As each character of the search string is typed, readline displays the next entry from the history matching the string typed so far. An incremental search requires only as many characters as needed to find the desired history entry. The characters present in the value of the isearch-terminators variable are used to terminate an incremental search. If that variable has not been assigned a value the Escape and Control-J characters will terminate an incremental search. Control-G will abort an incremental search and restore the original line. When the search is terminated, the history entry containing the search string becomes the current line. To find other matching entries in the history list, type Control-S or Control-R as appropriate. This will search backward or forward in the history for the next entry matching the search string typed so far. Any other key sequence bound to a readline command will terminate the search and execute that command. For instance, a newline will terminate the search and accept the line, thereby executing the command from the history list. Readline remembers the last incremental search string. If two Control- Rs are typed without any intervening characters defining a new search string, any remembered search string is used. Non-incremental searches read the entire search string before starting to search for matching history lines. The search string may be typed by the user or be part of the contents of the current line. Readline Command Names The following is a list of the names of the commands and the default key sequences to which they are bound. Command names without an accompanying key sequence are unbound by default. In the following descriptions, point refers to the current cursor position, and mark refers to a cursor position saved by the set-mark command. The text between the point and mark is referred to as the region. Commands for Moving beginning-of-line (C-a) Move to the start of the current line. end-of-line (C-e) Move to the end of the line. forward-char (C-f) Move forward a character. backward-char (C-b) Move back a character. forward-word (M-f) Move forward to the end of the next word. Words are composed of alphanumeric characters (letters and digits). backward-word (M-b) Move back to the start of the current or previous word. Words are composed of alphanumeric characters (letters and digits). clear-screen (C-l) Clear the screen leaving the current line at the top of the screen. With an argument, refresh the current line without clearing the screen. redraw-current-line Refresh the current line. Commands for Manipulating the History accept-line (Newline, Return) Accept the line regardless of where the cursor is. If this line is non-empty, add it to the history list according to the state of the HISTCONTROL variable. If the line is a modified history line, then restore the history line to its original state. previous-history (C-p) Fetch the previous command from the history list, moving back in the list. next-history (C-n) Fetch the next command from the history list, moving forward in the list. beginning-of-history (M-<) Move to the first line in the history. end-of-history (M->) Move to the end of the input history, i.e., the line currently being entered. reverse-search-history (C-r) Search backward starting at the current line and moving `up' through the history as necessary. This is an incremental search. forward-search-history (C-s) Search forward starting at the current line and moving `down' through the history as necessary. This is an incremental search. non-incremental-reverse-search-history (M-p) Search backward through the history starting at the current line using a non-incremental search for a string supplied by the user. non-incremental-forward-search-history (M-n) Search forward through the history using a non-incremental search for a string supplied by the user. history-search-forward Search forward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. history-search-backward Search backward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. yank-nth-arg (M-C-y) Insert the first argument to the previous command (usually the second word on the previous line) at point. With an argument n, insert the nth word from the previous command (the words in the previous command begin with word 0). A negative argument inserts the nth word from the end of the previous command. Once the argument n is computed, the argument is extracted as if the "!n" history expansion had been specified. yank-last-arg (M-., M-_) Insert the last argument to the previous command (the last word of the previous history entry). With an argument, behave exactly like yank-nth-arg. Successive calls to yank-last-arg move back through the history list, inserting the last argument of each line in turn. The history expansion facilities are used to extract the last argument, as if the "!$" history expansion had been specified. shell-expand-line (M-C-e) Expand the line as the shell does. This performs alias and history expansion as well as all of the shell word expansions. See HISTORY EXPANSION below for a description of history expansion. history-expand-line (M-^) Perform history expansion on the current line. See HISTORY EXPANSION below for a description of history expansion. magic-space Perform history expansion on the current line and insert a space. See HISTORY EXPANSION below for a description of history expansion. alias-expand-line Perform alias expansion on the current line. See ALIASES above for a description of alias expansion. history-and-alias-expand-line Perform history and alias expansion on the current line. insert-last-argument (M-., M-_) A synonym for yank-last-arg. operate-and-get-next (C-o) Accept the current line for execution and fetch the next line relative to the current line from the history for editing. Any argument is ignored. edit-and-execute-command (C-xC-e) Invoke an editor on the current command line, and execute the result as shell commands. Bash attempts to invoke $FCEDIT, $EDITOR, and emacs as the editor, in that order. Commands for Changing Text delete-char (C-d) Delete the character at point. If point is at the beginning of the line, there are no characters in the line, and the last character typed was not bound to delete-char, then return EOF. backward-delete-char (Rubout) Delete the character behind the cursor. When given a numeric argument, save the deleted text on the kill ring. forward-backward-delete-char Delete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted. quoted-insert (C-q, C-v) Add the next character typed to the line verbatim. This is how to insert characters like C-q, for example. tab-insert (C-v TAB) Insert a tab character. self-insert (a, b, A, 1, !, ...) Insert the character typed. transpose-chars (C-t) Drag the character before point forward over the character at point, moving point forward as well. If point is at the end of the line, then this transposes the two characters before point. Negative arguments have no effect. transpose-words (M-t) Drag the word before point past the word after point, moving point over that word as well. If point is at the end of the line, this transposes the last two words on the line. upcase-word (M-u) Uppercase the current (or following) word. With a negative argument, uppercase the previous word, but do not move point. downcase-word (M-l) Lowercase the current (or following) word. With a negative argument, lowercase the previous word, but do not move point. capitalize-word (M-c) Capitalize the current (or following) word. With a negative argument, capitalize the previous word, but do not move point. overwrite-mode Toggle overwrite mode. With an explicit positive numeric argument, switches to overwrite mode. With an explicit non- positive numeric argument, switches to insert mode. This command affects only emacs mode; vi mode does overwrite differently. Each call to readline() starts in insert mode. In overwrite mode, characters bound to self-insert replace the text at point rather than pushing the text to the right. Characters bound to backward-delete-char replace the character before point with a space. By default, this command is unbound. Killing and Yanking kill-line (C-k) Kill the text from point to the end of the line. backward-kill-line (C-x Rubout) Kill backward to the beginning of the line. unix-line-discard (C-u) Kill backward from point to the beginning of the line. The killed text is saved on the kill-ring. kill-whole-line Kill all characters on the current line, no matter where point is. kill-word (M-d) Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as those used by forward-word. backward-kill-word (M-Rubout) Kill the word behind point. Word boundaries are the same as those used by backward-word. unix-word-rubout (C-w) Kill the word behind point, using white space as a word boundary. The killed text is saved on the kill-ring. unix-filename-rubout Kill the word behind point, using white space and the slash character as the word boundaries. The killed text is saved on the kill-ring. delete-horizontal-space (M-\) Delete all spaces and tabs around point. kill-region Kill the text in the current region. copy-region-as-kill Copy the text in the region to the kill buffer. copy-backward-word Copy the word before point to the kill buffer. The word boundaries are the same as backward-word. copy-forward-word Copy the word following point to the kill buffer. The word boundaries are the same as forward-word. yank (C-y) Yank the top of the kill ring into the buffer at point. yank-pop (M-y) Rotate the kill ring, and yank the new top. Only works following yank or yank-pop. Numeric Arguments digit-argument (M-0, M-1, ..., M--) Add this digit to the argument already accumulating, or start a new argument. M-- starts a negative argument. universal-argument This is another way to specify an argument. If this command is followed by one or more digits, optionally with a leading minus sign, those digits define the argument. If the command is followed by digits, executing universal-argument again ends the numeric argument, but is otherwise ignored. As a special case, if this command is immediately followed by a character that is neither a digit or minus sign, the argument count for the next command is multiplied by four. The argument count is initially one, so executing this function the first time makes the argument count four, a second time makes the argument count sixteen, and so on. Completing complete (TAB) Attempt to perform completion on the text before point. Bash attempts completion treating the text as a variable (if the text begins with $), username (if the text begins with ~), hostname (if the text begins with @), or command (including aliases and functions) in turn. If none of these produces a match, filename completion is attempted. possible-completions (M-?) List the possible completions of the text before point. insert-completions (M-*) Insert all completions of the text before point that would have been generated by possible-completions. menu-complete Similar to complete, but replaces the word to be completed with a single match from the list of possible completions. Repeated execution of menu-complete steps through the list of possible completions, inserting each match in turn. At the end of the list of completions, the bell is rung (subject to the setting of bell-style) and the original text is restored. An argument of n moves n positions forward in the list of matches; a negative argument may be used to move backward through the list. This command is intended to be bound to TAB, but is unbound by default. delete-char-or-list Deletes the character under the cursor if not at the beginning or end of the line (like delete-char). If at the end of the line, behaves identically to possible-completions. This command is unbound by default. complete-filename (M-/) Attempt filename completion on the text before point. possible-filename-completions (C-x /) List the possible completions of the text before point, treating it as a filename. complete-username (M-~) Attempt completion on the text before point, treating it as a username. possible-username-completions (C-x ~) List the possible completions of the text before point, treating it as a username. complete-variable (M-$) Attempt completion on the text before point, treating it as a shell variable. possible-variable-completions (C-x $) List the possible completions of the text before point, treating it as a shell variable. complete-hostname (M-@) Attempt completion on the text before point, treating it as a hostname. possible-hostname-completions (C-x @) List the possible completions of the text before point, treating it as a hostname. complete-command (M-!) Attempt completion on the text before point, treating it as a command name. Command completion attempts to match the text against aliases, reserved words, shell functions, shell builtins, and finally executable filenames, in that order. possible-command-completions (C-x !) List the possible completions of the text before point, treating it as a command name. dynamic-complete-history (M-TAB) Attempt completion on the text before point, comparing the text against lines from the history list for possible completion matches. complete-into-braces (M-{) Perform filename completion and insert the list of possible completions enclosed within braces so the list is available to the shell (see Brace Expansion above). Keyboard Macros start-kbd-macro (C-x () Begin saving the characters typed into the current keyboard macro. end-kbd-macro (C-x )) Stop saving the characters typed into the current keyboard macro and store the definition. call-last-kbd-macro (C-x e) Re-execute the last keyboard macro defined, by making the characters in the macro appear as if typed at the keyboard. Miscellaneous re-read-init-file (C-x C-r) Read in the contents of the inputrc file, and incorporate any bindings or variable assignments found there. abort (C-g) Abort the current editing command and ring the terminal's bell (subject to the setting of bell-style). do-uppercase-version (M-a, M-b, M-x, ...) If the metafied character x is lowercase, run the command that is bound to the corresponding uppercase character. prefix-meta (ESC) Metafy the next character typed. ESC f is equivalent to Meta-f. undo (C-_, C-x C-u) Incremental undo, separately remembered for each line. revert-line (M-r) Undo all changes made to this line. This is like executing the undo command enough times to return the line to its initial state. tilde-expand (M-&) Perform tilde expansion on the current word. set-mark (C-@, M-<space>) Set the mark to the point. If a numeric argument is supplied, the mark is set to that position. exchange-point-and-mark (C-x C-x) Swap the point with the mark. The current cursor position is set to the saved position, and the old cursor position is saved as the mark. character-search (C-]) A character is read and point is moved to the next occurrence of that character. A negative count searches for previous occurrences. character-search-backward (M-C-]) A character is read and point is moved to the previous occurrence of that character. A negative count searches for subsequent occurrences. insert-comment (M-#) Without a numeric argument, the value of the readline comment-begin variable is inserted at the beginning of the current line. If a numeric argument is supplied, this command acts as a toggle: if the characters at the beginning of the line do not match the value of comment-begin, the value is inserted, otherwise the characters in comment-begin are deleted from the beginning of the line. In either case, the line is accepted as if a newline had been typed. The default value of comment-begin causes this command to make the current line a shell comment. If a numeric argument causes the comment character to be removed, the line will be executed by the shell. glob-complete-word (M-g) The word before point is treated as a pattern for pathname expansion, with an asterisk implicitly appended. This pattern is used to generate a list of matching file names for possible completions. glob-expand-word (C-x *) The word before point is treated as a pattern for pathname expansion, and the list of matching file names is inserted, replacing the word. If a numeric argument is supplied, an asterisk is appended before pathname expansion. glob-list-expansions (C-x g) The list of expansions that would have been generated by glob-expand-word is displayed, and the line is redrawn. If a numeric argument is supplied, an asterisk is appended before pathname expansion. dump-functions Print all of the functions and their key bindings to the readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. dump-variables Print all of the settable readline variables and their values to the readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. dump-macros Print all of the readline key sequences bound to macros and the strings they output. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. display-shell-version (C-x C-v) Display version information about the current instance of bash. Programmable Completion When word completion is attempted for an argument to a command for which a completion specification (a compspec) has been defined using the complete builtin (see SHELL BUILTIN COMMANDS below), the programmable completion facilities are invoked. First, the command name is identified. If a compspec has been defined for that command, the compspec is used to generate the list of possible completions for the word. If the command word is a full pathname, a compspec for the full pathname is searched for first. If no compspec is found for the full pathname, an attempt is made to find a compspec for the portion following the final slash. Once a compspec has been found, it is used to generate the list of matching words. If a compspec is not found, the default bash completion as described above under Completing is performed. First, the actions specified by the compspec are used. Only matches which are prefixed by the word being completed are returned. When the -f or -d option is used for filename or directory name completion, the shell variable FIGNORE is used to filter the matches. Any completions specified by a filename expansion pattern to the -G option are generated next. The words generated by the pattern need not match the word being completed. The GLOBIGNORE shell variable is not used to filter the matches, but the FIGNORE variable is used. Next, the string specified as the argument to the -W option is considered. The string is first split using the characters in the IFS special variable as delimiters. Shell quoting is honored. Each word is then expanded using brace expansion, tilde expansion, parameter and variable expansion, command substitution, and arithmetic expansion, as described above under EXPANSION. The results are split using the rules described above under Word Splitting. The results of the expansion are prefix-matched against the word being completed, and the matching words become the possible completions. After these matches have been generated, any shell function or command specified with the -F and -C options is invoked. When the command or function is invoked, the COMP_LINE and COMP_POINT variables are assigned values as described above under Shell Variables. If a shell function is being invoked, the COMP_WORDS and COMP_CWORD variables are also set. When the function or command is invoked, the first argument is the name of the command whose arguments are being completed, the second argument is the word being completed, and the third argument is the word preceding the word being completed on the current command line. No filtering of the generated completions against the word being completed is performed; the function or command has complete freedom in generating the matches. Any function specified with -F is invoked first. The function may use any of the shell facilities, including the compgen builtin described below, to generate the matches. It must put the possible completions in the COMPREPLY array variable. Next, any command specified with the -C option is invoked in an environment equivalent to command substitution. It should print a list of completions, one per line, to the standard output. Backslash may be used to escape a newline, if necessary. After all of the possible completions are generated, any filter specified with the -X option is applied to the list. The filter is a pattern as used for pathname expansion; a & in the pattern is replaced with the text of the word being completed. A literal & may be escaped with a backslash; the backslash is removed before attempting a match. Any completion that matches the pattern will be removed from the list. A leading ! negates the pattern; in this case any completion not matching the pattern will be removed. Finally, any prefix and suffix specified with the -P and -S options are added to each member of the completion list, and the result is returned to the readline completion code as the list of possible completions. If the previously-applied actions do not generate any matches, and the -o dirnames option was supplied to complete when the compspec was defined, directory name completion is attempted. If the -o plusdirs option was supplied to complete when the compspec was defined, directory name completion is attempted and any matches are added to the results of the other actions. By default, if a compspec is found, whatever it generates is returned to the completion code as the full set of possible completions. The default bash completions are not attempted, and the readline default of filename completion is disabled. If the -o bashdefault option was supplied to complete when the compspec was defined, the bash default completions are attempted if the compspec generates no matches. If the -o default option was supplied to complete when the compspec was defined, readline's default completion will be performed if the compspec (and, if attempted, the default bash completions) generate no matches. When a compspec indicates that directory name completion is desired, the programmable completion functions force readline to append a slash to completed names which are symbolic links to directories, subject to the value of the mark-directories readline variable, regardless of the setting of the mark-symlinked-directories readline variable. HISTORY When the -o history option to the set builtin is enabled, the shell provides access to the command history, the list of commands previously typed. The value of the HISTSIZE variable is used as the number of commands to save in a history list. The text of the last HISTSIZE commands (default 500) is saved. The shell stores each command in the history list prior to parameter and variable expansion (see EXPANSION above) but after history expansion is performed, subject to the values of the shell variables HISTIGNORE and HISTCONTROL. On startup, the history is initialized from the file named by the variable HISTFILE (default ~/.bash_history). The file named by the value of HISTFILE is truncated, if necessary, to contain no more than the number of lines specified by the value of HISTFILESIZE. When an interactive shell exits, the last $HISTSIZE lines are copied from the history list to $HISTFILE. If the histappend shell option is enabled (see the description of shopt under SHELL BUILTIN COMMANDS below), the lines are appended to the history file, otherwise the history file is overwritten. If HISTFILE is unset, or if the history file is unwritable, the history is not saved. After saving the history, the history file is truncated to contain no more than HISTFILESIZE lines. If HISTFILESIZE is not set, no truncation is performed. The builtin command fc (see SHELL BUILTIN COMMANDS below) may be used to list or edit and re-execute a portion of the history list. The history builtin may be used to display or modify the history list and manipulate the history file. When using command-line editing, search commands are available in each editing mode that provide access to the history list. The shell allows control over which commands are saved on the history list. The HISTCONTROL and HISTIGNORE variables may be set to cause the shell to save only a subset of the commands entered. The cmdhist shell option, if enabled, causes the shell to attempt to save each line of a multi-line command in the same history entry, adding semicolons where necessary to preserve syntactic correctness. The lithist shell option causes the shell to save the command with embedded newlines instead of semicolons. See the description of the shopt builtin below under SHELL BUILTIN COMMANDS for information on setting and unsetting shell options. HISTORY EXPANSION The shell supports a history expansion feature that is similar to the history expansion in csh. This section describes what syntax features are available. This feature is enabled by default for interactive shells, and can be disabled using the +H option to the set builtin command (see SHELL BUILTIN COMMANDS below). Non-interactive shells do not perform history expansion by default. History expansions introduce words from the history list into the input stream, making it easy to repeat commands, insert the arguments to a previous command into the current input line, or fix errors in previous commands quickly. History expansion is performed immediately after a complete line is read, before the shell breaks it into words. It takes place in two parts. The first is to determine which line from the history list to use during substitution. The second is to select portions of that line for inclusion into the current one. The line selected from the history is the event, and the portions of that line that are acted upon are words. Various modifiers are available to manipulate the selected words. The line is broken into words in the same fashion as when reading input, so that several metacharacter-separated words surrounded by quotes are considered one word. History expansions are introduced by the appearance of the history expansion character, which is ! by default. Only backslash (\) and single quotes can quote the history expansion character. Several characters inhibit history expansion if found immediately following the history expansion character, even if it is unquoted: space, tab, newline, carriage return, and =. If the extglob shell option is enabled, ( will also inhibit expansion. Several shell options settable with the shopt builtin may be used to tailor the behavior of history expansion. If the histverify shell option is enabled (see the description of the shopt builtin), and readline is being used, history substitutions are not immediately passed to the shell parser. Instead, the expanded line is reloaded into the readline editing buffer for further modification. If readline is being used, and the histreedit shell option is enabled, a failed history substitution will be reloaded into the readline editing buffer for correction. The -p option to the history builtin command may be used to see what a history expansion will do before using it. The -s option to the history builtin may be used to add commands to the end of the history list without actually executing them, so that they are available for subsequent recall. The shell allows control of the various characters used by the history expansion mechanism (see the description of histchars above under Shell Variables). Event Designators An event designator is a reference to a command line entry in the history list. ! Start a history substitution, except when followed by a blank, newline, carriage return, = or ( (when the extglob shell option is enabled using the shopt builtin). !n Refer to command line n. !-n Refer to the current command line minus n. !! Refer to the previous command. This is a synonym for `!-1'. !string Refer to the most recent command starting with string. !?string[?] Refer to the most recent command containing string. The trailing ? may be omitted if string is followed immediately by a newline. ^string1^string2^ Quick substitution. Repeat the last command, replacing string1 with string2. Equivalent to ``!!:s/string1/string2/'' (see Modifiers below). !# The entire command line typed so far. Word Designators Word designators are used to select desired words from the event. A : separates the event specification from the word designator. It may be omitted if the word designator begins with a ^, $, *, -, or %. Words are numbered from the beginning of the line, with the first word being denoted by 0 (zero). Words are inserted into the current line separated by single spaces. 0 (zero) The zeroth word. For the shell, this is the command word. n The nth word. ^ The first argument. That is, word 1. $ The last argument. % The word matched by the most recent `?string?' search. x-y A range of words; `-y' abbreviates `0-y'. * All of the words but the zeroth. This is a synonym for `1-$'. It is not an error to use * if there is just one word in the event; the empty string is returned in that case. x* Abbreviates x-$. x- Abbreviates x-$ like x*, but omits the last word. If a word designator is supplied without an event specification, the previous command is used as the event. Modifiers After the optional word designator, there may appear a sequence of one or more of the following modifiers, each preceded by a `:'. h Remove a trailing file name component, leaving only the head. t Remove all leading file name components, leaving the tail. r Remove a trailing suffix of the form .xxx, leaving the basename. e Remove all but the trailing suffix. p Print the new command but do not execute it. q Quote the substituted words, escaping further substitutions. x Quote the substituted words as with q, but break into words at blanks and newlines. s/old/new/ Substitute new for the first occurrence of old in the event line. Any delimiter can be used in place of /. The final delimiter is optional if it is the last character of the event line. The delimiter may be quoted in old and new with a single backslash. If & appears in new, it is replaced by old. A single backslash will quote the &. If old is null, it is set to the last old substituted, or, if no previous history substitutions took place, the last string in a !?string[?] search. & Repeat the previous substitution. g Cause changes to be applied over the entire event line. This is used in conjunction with `:s' (e.g., `:gs/old/new/') or `:&'. If used with `:s', any delimiter can be used in place of /, and the final delimiter is optional if it is the last character of the event line. An a may be used as a synonym for g. G Apply the following `s' modifier once to each word in the event line. SHELL BUILTIN COMMANDS Unless otherwise noted, each builtin command documented in this section as accepting options preceded by - accepts -- to signify the end of the options. For example, the :, true, false, and test builtins do not accept options. : [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned. . filename [arguments] source filename [arguments] Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename. If filename does not contain a slash, file names in PATH are used to find the directory containing filename. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read. alias [-p] [name[=value] ...] Alias with no arguments or with the -p option prints the list of aliases in the form alias name=value on standard output. When arguments are supplied, an alias is defined for each name whose value is given. A trailing space in value causes the next word to be checked for alias substitution when the alias is expanded. For each name in the argument list for which no value is supplied, the name and value of the alias is printed. Alias returns true unless a name is given for which no alias has been defined. bg [jobspec ...] Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used. bg jobspec returns 0 unless run when job control is disabled or, when run with job control enabled, any specified jobspec was not found or was started without job control. bind [-m keymap] [-lpsvPSV] bind [-m keymap] [-q function] [-u function] [-r keyseq] bind [-m keymap] -f filename bind [-m keymap] -x keyseq:shell-command bind [-m keymap] keyseq:function-name bind readline-command Display current readline key and function bindings, bind a key sequence to a readline function or macro, or set a readline variable. Each non-option argument is a command as it would appear in .inputrc, but each binding or command must be passed as a separate argument; e.g., '"\C-x\C-r": re-read-init-file'. Options, if supplied, have the following meanings: -m keymap Use keymap as the keymap to be affected by the subsequent bindings. Acceptable keymap names are emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command, and vi-insert. vi is equivalent to vi-command; emacs is equivalent to emacs-standard. -l List the names of all readline functions. -p Display readline function names and bindings in such a way that they can be re-read. -P List current readline function names and bindings. -v Display readline variable names and values in such a way that they can be re-read. -V List current readline variable names and values. -s Display readline key sequences bound to macros and the strings they output in such a way that they can be re- read. -S Display readline key sequences bound to macros and the strings they output. -f filename Read key bindings from filename. -q function Query about which keys invoke the named function. -u function Unbind all keys bound to the named function. -r keyseq Remove any current binding for keyseq. -x keyseq:shell-command Cause shell-command to be executed whenever keyseq is entered. The return value is 0 unless an unrecognized option is given or an error occurred. break [n] Exit from within a for, while, until, or select loop. If n is specified, break n levels. n must be ≥ 1. If n is greater than the number of enclosing loops, all enclosing loops are exited. The return value is 0 unless the shell is not executing a loop when break is executed. builtin shell-builtin [arguments] Execute the specified shell builtin, passing it arguments, and return its exit status. This is useful when defining a function whose name is the same as a shell builtin, retaining the functionality of the builtin within the function. The cd builtin is commonly redefined this way. The return status is false if shell-builtin is not a shell builtin command. cd [-L|-P] [dir] Change the current directory to dir. The variable HOME is the default dir. The variable CDPATH defines the search path for the directory containing dir. Alternative directory names in CDPATH are separated by a colon (:). A null directory name in CDPATH is the same as the current directory, i.e., ``.''. If dir begins with a slash (/), then CDPATH is not used. The -P option says to use the physical directory structure instead of following symbolic links (see also the -P option to the set builtin command); the -L option forces symbolic links to be followed. An argument of - is equivalent to $OLDPWD. If a non- empty directory name from CDPATH is used, or if - is the first argument, and the directory change is successful, the absolute pathname of the new working directory is written to the standard output. The return value is true if the directory was successfully changed; false otherwise. caller [expr] Returns the context of any active subroutine call (a shell function or a script executed with the . or source builtins. Without expr, caller displays the line number and source filename of the current subroutine call. If a non-negative integer is supplied as expr, caller displays the line number, subroutine name, and source file corresponding to that position in the current execution call stack. This extra information may be used, for example, to print a stack trace. The current frame is frame 0. The return value is 0 unless the shell is not executing a subroutine call or expr does not correspond to a valid position in the call stack. command [-pVv] command [arg ...] Run command with args suppressing the normal shell function lookup. Only builtin commands or commands found in the PATH are executed. If the -p option is given, the search for command is performed using a default value for PATH that is guaranteed to find all of the standard utilities. If either the -V or -v option is supplied, a description of command is printed. The -v option causes a single word indicating the command or file name used to invoke command to be displayed; the -V option produces a more verbose description. If the -V or -v option is supplied, the exit status is 0 if command was found, and 1 if not. If neither option is supplied and an error occurred or command cannot be found, the exit status is 127. Otherwise, the exit status of the command builtin is the exit status of command. compgen [option] [word] Generate possible completion matches for word according to the options, which may be any option accepted by the complete builtin with the exception of -p and -r, and write the matches to the standard output. When using the -F or -C options, the various shell variables set by the programmable completion facilities, while available, will not have useful values. The matches will be generated in the same way as if the programmable completion code had generated them directly from a completion specification with the same flags. If word is specified, only those completions matching word will be displayed. The return value is true unless an invalid option is supplied, or no matches were generated. complete [-abcdefgjksuv] [-o comp-option] [-A action] [-G globpat] [-W wordlist] [-P prefix] [-S suffix] [-X filterpat] [-F function] [-C command] name [name ...] complete -pr [name ...] Specify how arguments to each name should be completed. If the -p option is supplied, or if no options are supplied, existing completion specifications are printed in a way that allows them to be reused as input. The -r option removes a completion specification for each name, or, if no names are supplied, all completion specifications. The process of applying these completion specifications when word completion is attempted is described above under Programmable Completion. Other options, if specified, have the following meanings. The arguments to the -G, -W, and -X options (and, if necessary, the -P and -S options) should be quoted to protect them from expansion before the complete builtin is invoked. -o comp-option The comp-option controls several aspects of the compspec's behavior beyond the simple generation of completions. comp-option may be one of: bashdefault Perform the rest of the default bash completions if the compspec generates no matches. default Use readline's default filename completion if the compspec generates no matches. dirnames Perform directory name completion if the compspec generates no matches. filenames Tell readline that the compspec generates filenames, so it can perform any filename-specific processing (like adding a slash to directory names or suppressing trailing spaces). Intended to be used with shell functions. nospace Tell readline not to append a space (the default) to words completed at the end of the line. plusdirs After any matches defined by the compspec are generated, directory name completion is attempted and any matches are added to the results of the other actions. -A action The action may be one of the following to generate a list of possible completions: alias Alias names. May also be specified as -a. arrayvar Array variable names. binding Readline key binding names. builtin Names of shell builtin commands. May also be specified as -b. command Command names. May also be specified as -c. directory Directory names. May also be specified as -d. disabled Names of disabled shell builtins. enabled Names of enabled shell builtins. export Names of exported shell variables. May also be specified as -e. file File names. May also be specified as -f. function Names of shell functions. group Group names. May also be specified as -g. helptopic Help topics as accepted by the help builtin. hostname Hostnames, as taken from the file specified by the HOSTFILE shell variable. job Job names, if job control is active. May also be specified as -j. keyword Shell reserved words. May also be specified as -k. running Names of running jobs, if job control is active. service Service names. May also be specified as -s. setopt Valid arguments for the -o option to the set builtin. shopt Shell option names as accepted by the shopt builtin. signal Signal names. stopped Names of stopped jobs, if job control is active. user User names. May also be specified as -u. variable Names of all shell variables. May also be specified as -v. -G globpat The filename expansion pattern globpat is expanded to generate the possible completions. -W wordlist The wordlist is split using the characters in the IFS special variable as delimiters, and each resultant word is expanded. The possible completions are the members of the resultant list which match the word being completed. -C command command is executed in a subshell environment, and its output is used as the possible completions. -F function The shell function function is executed in the current shell environment. When it finishes, the possible completions are retrieved from the value of the COMPREPLY array variable. -X filterpat filterpat is a pattern as used for filename expansion. It is applied to the list of possible completions generated by the preceding options and arguments, and each completion matching filterpat is removed from the list. A leading ! in filterpat negates the pattern; in this case, any completion not matching filterpat is removed. -P prefix prefix is added at the beginning of each possible completion after all other options have been applied. -S suffix suffix is appended to each possible completion after all other options have been applied. The return value is true unless an invalid option is supplied, an option other than -p or -r is supplied without a name argument, an attempt is made to remove a completion specification for a name for which no specification exists, or an error occurs adding a completion specification. continue [n] Resume the next iteration of the enclosing for, while, until, or select loop. If n is specified, resume at the nth enclosing loop. n must be ≥ 1. If n is greater than the number of enclosing loops, the last enclosing loop (the ``top-level'' loop) is resumed. The return value is 0 unless the shell is not executing a loop when continue is executed. declare [-afFirtx] [-p] [name[=value] ...] typeset [-afFirtx] [-p] [name[=value] ...] Declare variables and/or give them attributes. If no names are given then display the values of variables. The -p option will display the attributes and values of each name. When -p is used, additional options are ignored. The -F option inhibits the display of function definitions; only the function name and attributes are printed. If the extdebug shell option is enabled using shopt, the source file name and line number where the function is defined are displayed as well. The -F option implies -f. The following options can be used to restrict output to variables with the specified attribute or to give variables attributes: -a Each name is an array variable (see Arrays above). -f Use function names only. -i The variable is treated as an integer; arithmetic evaluation (see ARITHMETIC EVALUATION ) is performed when the variable is assigned a value. -r Make names readonly. These names cannot then be assigned values by subsequent assignment statements or unset. -t Give each name the trace attribute. Traced functions inherit the DEBUG and RETURN traps from the calling shell. The trace attribute has no special meaning for variables. -x Mark names for export to subsequent commands via the environment. Using `+' instead of `-' turns off the attribute instead, with the exception that +a may not be used to destroy an array variable. When used in a function, makes each name local, as with the local command. If a variable name is followed by =value, the value of the variable is set to value. The return value is 0 unless an invalid option is encountered, an attempt is made to define a function using ``-f foo=bar'', an attempt is made to assign a value to a readonly variable, an attempt is made to assign a value to an array variable without using the compound assignment syntax (see Arrays above), one of the names is not a valid shell variable name, an attempt is made to turn off readonly status for a readonly variable, an attempt is made to turn off array status for an array variable, or an attempt is made to display a non-existent function with -f. dirs [-clpv] [+n] [-n] Without options, displays the list of currently remembered directories. The default display is on a single line with directory names separated by spaces. Directories are added to the list with the pushd command; the popd command removes entries from the list. +n Displays the nth entry counting from the left of the list shown by dirs when invoked without options, starting with zero. -n Displays the nth entry counting from the right of the list shown by dirs when invoked without options, starting with zero. -c Clears the directory stack by deleting all of the entries. -l Produces a longer listing; the default listing format uses a tilde to denote the home directory. -p Print the directory stack with one entry per line. -v Print the directory stack with one entry per line, prefixing each entry with its index in the stack. The return value is 0 unless an invalid option is supplied or n indexes beyond the end of the directory stack. disown [-ar] [-h] [jobspec ...] Without options, each jobspec is removed from the table of active jobs. If the -h option is given, each jobspec is not removed from the table, but is marked so that SIGHUP is not sent to the job if the shell receives a SIGHUP. If no jobspec is present, and neither the -a nor the -r option is supplied, the current job is used. If no jobspec is supplied, the -a option means to remove or mark all jobs; the -r option without a jobspec argument restricts operation to running jobs. The return value is 0 unless a jobspec does not specify a valid job. echo [-neE] [arg ...] Output the args, separated by spaces, followed by a newline. The return status is always 0. If -n is specified, the trailing newline is suppressed. If the -e option is given, interpretation of the following backslash-escaped characters is enabled. The -E option disables the interpretation of these escape characters, even on systems where they are interpreted by default. The xpg_echo shell option may be used to dynamically determine whether or not echo expands these escape characters by default. echo does not interpret -- to mean the end of options. echo interprets the following escape sequences: \a alert (bell) \b backspace \c suppress trailing newline \e an escape character \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \\ backslash \0nnn the eight-bit character whose value is the octal value nnn (zero to three octal digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) enable [-adnps] [-f filename] [name ...] Enable and disable builtin shell commands. Disabling a builtin allows a disk command which has the same name as a shell builtin to be executed without specifying a full pathname, even though the shell normally searches for builtins before disk commands. If -n is used, each name is disabled; otherwise, names are enabled. For example, to use the test binary found via the PATH instead of the shell builtin version, run ``enable -n test''. The -f option means to load the new builtin command name from shared object filename, on systems that support dynamic loading. The -d option will delete a builtin previously loaded with -f. If no name arguments are given, or if the -p option is supplied, a list of shell builtins is printed. With no other option arguments, the list consists of all enabled shell builtins. If -n is supplied, only disabled builtins are printed. If -a is supplied, the list printed includes all builtins, with an indication of whether or not each is enabled. If -s is supplied, the output is restricted to the POSIX special builtins. The return value is 0 unless a name is not a shell builtin or there is an error loading a new builtin from a shared object. eval [arg ...] The args are read and concatenated together into a single command. This command is then read and executed by the shell, and its exit status is returned as the value of eval. If there are no args, or only null arguments, eval returns 0. exec [-cl] [-a name] [command [arguments]] If command is specified, it replaces the shell. No new process is created. The arguments become the arguments to command. If the -l option is supplied, the shell places a dash at the beginning of the zeroth arg passed to command. This is what login(1) does. The -c option causes command to be executed with an empty environment. If -a is supplied, the shell passes name as the zeroth argument to the executed command. If command cannot be executed for some reason, a non-interactive shell exits, unless the shell option execfail is enabled, in which case it returns failure. An interactive shell returns failure if the file cannot be executed. If command is not specified, any redirections take effect in the current shell, and the return status is 0. If there is a redirection error, the return status is 1. exit [n] Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the last command executed. A trap on EXIT is executed before the shell terminates. export [-fn] [name[=word]] ... export -p The supplied names are marked for automatic export to the environment of subsequently executed commands. If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of all names that are exported in this shell is printed. The -n option causes the export property to be removed from each name. If a variable name is followed by =word, the value of the variable is set to word. export returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function. fc [-e ename] [-nlr] [first] [last] fc -s [pat=rep] [cmd] Fix Command. In the first form, a range of commands from first to last is selected from the history list. First and last may be specified as a string (to locate the last command beginning with that string) or as a number (an index into the history list, where a negative number is used as an offset from the current command number). If last is not specified it is set to the current command for listing (so that ``fc -l -10'' prints the last 10 commands) and to first otherwise. If first is not specified it is set to the previous command for editing and -16 for listing. The -n option suppresses the command numbers when listing. The -r option reverses the order of the commands. If the -l option is given, the commands are listed on standard output. Otherwise, the editor given by ename is invoked on a file containing those commands. If ename is not given, the value of the FCEDIT variable is used, and the value of EDITOR if FCEDIT is not set. If neither variable is set, vi is used. When editing is complete, the edited commands are echoed and executed. In the second form, command is re-executed after each instance of pat is replaced by rep. A useful alias to use with this is ``r="fc -s"'', so that typing ``r cc'' runs the last command beginning with ``cc'' and typing ``r'' re-executes the last command. If the first form is used, the return value is 0 unless an invalid option is encountered or first or last specify history lines out of range. If the -e option is supplied, the return value is the value of the last command executed or failure if an error occurs with the temporary file of commands. If the second form is used, the return status is that of the command re- executed, unless cmd does not specify a valid history line, in which case fc returns failure. fg [jobspec] Resume jobspec in the foreground, and make it the current job. If jobspec is not present, the shell's notion of the current job is used. The return value is that of the command placed into the foreground, or failure if run when job control is disabled or, when run with job control enabled, if jobspec does not specify a valid job or jobspec specifies a job that was started without job control. getopts optstring name [args] getopts is used by shell procedures to parse positional parameters. optstring contains the option characters to be recognized; if a character is followed by a colon, the option is expected to have an argument, which should be separated from it by white space. The colon and question mark characters may not be used as option characters. Each time it is invoked, getopts places the next option in the shell variable name, initializing name if it does not exist, and the index of the next argument to be processed into the variable OPTIND. OPTIND is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument, getopts places that argument into the variable OPTARG. The shell does not reset OPTIND automatically; it must be manually reset between multiple calls to getopts within the same shell invocation if a new set of parameters is to be used. When the end of options is encountered, getopts exits with a return value greater than zero. OPTIND is set to the index of the first non-option argument, and name is set to ?. getopts normally parses the positional parameters, but if more arguments are given in args, getopts parses those instead. getopts can report errors in two ways. If the first character of optstring is a colon, silent error reporting is used. In normal operation diagnostic messages are printed when invalid options or missing option arguments are encountered. If the variable OPTERR is set to 0, no error messages will be displayed, even if the first character of optstring is not a colon. If an invalid option is seen, getopts places ? into name and, if not silent, prints an error message and unsets OPTARG. If getopts is silent, the option character found is placed in OPTARG and no diagnostic message is printed. If a required argument is not found, and getopts is not silent, a question mark (?) is placed in name, OPTARG is unset, and a diagnostic message is printed. If getopts is silent, then a colon (:) is placed in name and OPTARG is set to the option character found. getopts returns true if an option, specified or unspecified, is found. It returns false if the end of options is encountered or an error occurs. hash [-lr] [-p filename] [-dt] [name] For each name, the full file name of the command is determined by searching the directories in $PATH and remembered. If the -p option is supplied, no path search is performed, and filename is used as the full file name of the command. The -r option causes the shell to forget all remembered locations. The -d option causes the shell to forget the remembered location of each name. If the -t option is supplied, the full pathname to which each name corresponds is printed. If multiple name arguments are supplied with -t, the name is printed before the hashed full pathname. The -l option causes output to be displayed in a format that may be reused as input. If no arguments are given, or if only -l is supplied, information about remembered commands is printed. The return status is true unless a name is not found or an invalid option is supplied. help [-s] [pattern] Display helpful information about builtin commands. If pattern is specified, help gives detailed help on all commands matching pattern; otherwise help for all the builtins and shell control structures is printed. The -s option restricts the information displayed to a short usage synopsis. The return status is 0 unless no command matches pattern. history [n] history -c history -d offset history -anrw [filename] history -p arg [arg ...] history -s arg [arg ...] With no options, display the command history list with line numbers. Lines listed with a * have been modified. An argument of n lists only the last n lines. If the shell variable HISTTIMEFORMAT is set and not null, it is used as a format string for strftime(3) to display the time stamp associated with each displayed history entry. No intervening blank is printed between the formatted time stamp and the history line. If filename is supplied, it is used as the name of the history file; if not, the value of HISTFILE is used. Options, if supplied, have the following meanings: -c Clear the history list by deleting all the entries. -d offset Delete the history entry at position offset. -a Append the ``new'' history lines (history lines entered since the beginning of the current bash session) to the history file. -n Read the history lines not already read from the history file into the current history list. These are lines appended to the history file since the beginning of the current bash session. -r Read the contents of the history file and use them as the current history. -w Write the current history to the history file, overwriting the history file's contents. -p Perform history substitution on the following args and display the result on the standard output. Does not store the results in the history list. Each arg must be quoted to disable normal history expansion. -s Store the args in the history list as a single entry. The last command in the history list is removed before the args are added. If the HISTTIMEFORMAT is set, the time stamp information associated with each history entry is written to the history file. The return value is 0 unless an invalid option is encountered, an error occurs while reading or writing the history file, an invalid offset is supplied as an argument to -d, or the history expansion supplied as an argument to -p fails. jobs [-lnprs] [ jobspec ... ] jobs -x command [ args ... ] The first form lists the active jobs. The options have the following meanings: -l List process IDs in addition to the normal information. -p List only the process ID of the job's process group leader. -n Display information only about jobs that have changed status since the user was last notified of their status. -r Restrict output to running jobs. -s Restrict output to stopped jobs. If jobspec is given, output is restricted to information about that job. The return status is 0 unless an invalid option is encountered or an invalid jobspec is supplied. If the -x option is supplied, jobs replaces any jobspec found in command or args with the corresponding process group ID, and executes command passing it args, returning its exit status. kill [-s sigspec | -n signum | -sigspec] [pid | jobspec] ... kill -l [sigspec | exit_status] Send the signal named by sigspec or signum to the processes named by pid or jobspec. sigspec is either a case-insensitive signal name such as SIGKILL (with or without the SIG prefix) or a signal number; signum is a signal number. If sigspec is not present, then SIGTERM is assumed. An argument of -l lists the signal names. If any arguments are supplied when -l is given, the names of the signals corresponding to the arguments are listed, and the return status is 0. The exit_status argument to -l is a number specifying either a signal number or the exit status of a process terminated by a signal. kill returns true if at least one signal was successfully sent, or false if an error occurs or an invalid option is encountered. let arg [arg ...] Each arg is an arithmetic expression to be evaluated (see ARITHMETIC EVALUATION). If the last arg evaluates to 0, let returns 1; 0 is returned otherwise. local [option] [name[=value] ...] For each argument, a local variable named name is created, and assigned value. The option can be any of the options accepted by declare. When local is used within a function, it causes the variable name to have a visible scope restricted to that function and its children. With no operands, local writes a list of local variables to the standard output. It is an error to use local when not within a function. The return status is 0 unless local is used outside a function, an invalid name is supplied, or name is a readonly variable. logout Exit a login shell. popd [-n] [+n] [-n] Removes entries from the directory stack. With no arguments, removes the top directory from the stack, and performs a cd to the new top directory. Arguments, if supplied, have the following meanings: +n Removes the nth entry counting from the left of the list shown by dirs, starting with zero. For example: ``popd +0'' removes the first directory, ``popd +1'' the second. -n Removes the nth entry counting from the right of the list shown by dirs, starting with zero. For example: ``popd -0'' removes the last directory, ``popd -1'' the next to last. -n Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated. If the popd command is successful, a dirs is performed as well, and the return status is 0. popd returns false if an invalid option is encountered, the directory stack is empty, a non- existent directory stack entry is specified, or the directory change fails. printf [-v var] format [arguments] Write the formatted arguments to the standard output under the control of the format. The format is a character string which contains three types of objects: plain characters, which are simply copied to standard output, character escape sequences, which are converted and copied to the standard output, and format specifications, each of which causes printing of the next successive argument. In addition to the standard printf(1) formats, %b causes printf to expand backslash escape sequences in the corresponding argument (except that \c terminates output, backslashes in \', \", and \? are not removed, and octal escapes beginning with \0 may contain up to four digits), and %q causes printf to output the corresponding argument in a format that can be reused as shell input. The -v option causes the output to be assigned to the variable var rather than being printed to the standard output. The format is reused as necessary to consume all of the arguments. If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied. The return value is zero on success, non-zero on failure. pushd [-n] [dir] pushd [-n] [+n] [-n] Adds a directory to the top of the directory stack, or rotates the stack, making the new top of the stack the current working directory. With no arguments, exchanges the top two directories and returns 0, unless the directory stack is empty. Arguments, if supplied, have the following meanings: +n Rotates the stack so that the nth directory (counting from the left of the list shown by dirs, starting with zero) is at the top. -n Rotates the stack so that the nth directory (counting from the right of the list shown by dirs, starting with zero) is at the top. -n Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. dir Adds dir to the directory stack at the top, making it the new current working directory. If the pushd command is successful, a dirs is performed as well. If the first form is used, pushd returns 0 unless the cd to dir fails. With the second form, pushd returns 0 unless the directory stack is empty, a non-existent directory stack element is specified, or the directory change to the specified new current directory fails. pwd [-LP] Print the absolute pathname of the current working directory. The pathname printed contains no symbolic links if the -P option is supplied or the -o physical option to the set builtin command is enabled. If the -L option is used, the pathname printed may contain symbolic links. The return status is 0 unless an error occurs while reading the name of the current directory or an invalid option is supplied. read [-ers] [-u fd] [-t timeout] [-a aname] [-p prompt] [-n nchars] [-d delim] [name ...] One line is read from the standard input, or from the file descriptor fd supplied as an argument to the -u option, and the first word is assigned to the first name, the second word to the second name, and so on, with leftover words and their intervening separators assigned to the last name. If there are fewer words read from the input stream than names, the remaining names are assigned empty values. The characters in IFS are used to split the line into words. The backslash character (\) may be used to remove any special meaning for the next character read and for line continuation. Options, if supplied, have the following meanings: -a aname The words are assigned to sequential indices of the array variable aname, starting at 0. aname is unset before any new values are assigned. Other name arguments are ignored. -d delim The first character of delim is used to terminate the input line, rather than newline. -e If the standard input is coming from a terminal, readline (see READLINE above) is used to obtain the line. -n nchars read returns after reading nchars characters rather than waiting for a complete line of input. -p prompt Display prompt on standard error, without a trailing newline, before attempting to read any input. The prompt is displayed only if input is coming from a terminal. -r Backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation. -s Silent mode. If input is coming from a terminal, characters are not echoed. -t timeout Cause read to time out and return failure if a complete line of input is not read within timeout seconds. This option has no effect if read is not reading input from the terminal or a pipe. -u fd Read input from file descriptor fd. If no names are supplied, the line read is assigned to the variable REPLY. The return code is zero, unless end-of-file is encountered, read times out, or an invalid file descriptor is supplied as the argument to -u. readonly [-apf] [name[=word] ...] The given names are marked readonly; the values of these names may not be changed by subsequent assignment. If the -f option is supplied, the functions corresponding to the names are so marked. The -a option restricts the variables to arrays. If no name arguments are given, or if the -p option is supplied, a list of all readonly names is printed. The -p option causes output to be displayed in a format that may be reused as input. If a variable name is followed by =word, the value of the variable is set to word. The return status is 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function. return [n] Causes a function to exit with the return value specified by n. If n is omitted, the return status is that of the last command executed in the function body. If used outside a function, but during execution of a script by the . (source) command, it causes the shell to stop executing that script and return either n or the exit status of the last command executed within the script as the exit status of the script. If used outside a function and not during execution of a script by ., the return status is false. Any command associated with the RETURN trap is executed before execution resumes after the function or script. set [--abefhkmnptuvxBCHP] [-o option] [arg ...] Without options, the name and value of each shell variable are displayed in a format that can be reused as input for setting or resetting the currently-set variables. Read-only variables cannot be reset. In posix mode, only shell variables are listed. The output is sorted according to the current locale. When options are specified, they set or unset shell attributes. Any arguments remaining after the options are processed are treated as values for the positional parameters and are assigned, in order, to $1, $2, ... $n. Options, if specified, have the following meanings: -a Automatically mark variables and functions which are modified or created for export to the environment of subsequent commands. -b Report the status of terminated background jobs immediately, rather than before the next primary prompt. This is effective only when job control is enabled. -e Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a && or ⎪⎪ list, or if the command's return value is being inverted via !. A trap on ERR, if set, is executed before the shell exits. -f Disable pathname expansion. -h Remember the location of commands as they are looked up for execution. This is enabled by default. -k All arguments in the form of assignment statements are placed in the environment for a command, not just those that precede the command name. -m Monitor mode. Job control is enabled. This option is on by default for interactive shells on systems that support it (see JOB CONTROL above). Background processes run in a separate process group and a line containing their exit status is printed upon their completion. -n Read commands but do not execute them. This may be used to check a shell script for syntax errors. This is ignored by interactive shells. -o option-name The option-name can be one of the following: allexport Same as -a. braceexpand Same as -B. emacs Use an emacs-style command line editing interface. This is enabled by default when the shell is interactive, unless the shell is started with the --noediting option. errtrace Same as -E. functrace Same as -T. errexit Same as -e. hashall Same as -h. histexpand Same as -H. history Enable command history, as described above under HISTORY. This option is on by default in interactive shells. ignoreeof The effect is as if the shell command ``IGNOREEOF=10'' had been executed (see Shell Variables above). keyword Same as -k. monitor Same as -m. noclobber Same as -C. noexec Same as -n. noglob Same as -f. nolog Currently ignored. notify Same as -b. nounset Same as -u. onecmd Same as -t. physical Same as -P. pipefail If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default. posix Change the behavior of bash where the default operation differs from the POSIX standard to match the standard (posix mode). privileged Same as -p. verbose Same as -v. vi Use a vi-style command line editing interface. xtrace Same as -x. If -o is supplied with no option-name, the values of the current options are printed. If +o is supplied with no option-name, a series of set commands to recreate the current option settings is displayed on the standard output. -p Turn on privileged mode. In this mode, the $ENV and $BASH_ENV files are not processed, shell functions are not inherited from the environment, and the SHELLOPTS variable, if it appears in the environment, is ignored. If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, these actions are taken and the effective user id is set to the real user id. If the -p option is supplied at startup, the effective user id is not reset. Turning this option off causes the effective user and group ids to be set to the real user and group ids. -t Exit after reading and executing one command. -u Treat unset variables as an error when performing parameter expansion. If expansion is attempted on an unset variable, the shell prints an error message, and, if not interactive, exits with a non-zero status. -v Print shell input lines as they are read. -x After expanding each simple command, for command, case command, select command, or arithmetic for command, display the expanded value of PS4, followed by the command and its expanded arguments or associated word list. -B The shell performs brace expansion (see Brace Expansion above). This is on by default. -C If set, bash does not overwrite an existing file with the >, >&, and <> redirection operators. This may be overridden when creating output files by using the redirection operator >| instead of >. -E If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment. The ERR trap is normally not inherited in such cases. -H Enable ! style history substitution. This option is on by default when the shell is interactive. -P If set, the shell does not follow symbolic links when executing commands such as cd that change the current working directory. It uses the physical directory structure instead. By default, bash follows the logical chain of directories when performing commands which change the current directory. -T If set, any traps on DEBUG and RETURN are inherited by shell functions, command substitutions, and commands executed in a subshell environment. The DEBUG and RETURN traps are normally not inherited in such cases. -- If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters are set to the args, even if some of them begin with a -. - Signal the end of options, cause all remaining args to be assigned to the positional parameters. The -x and -v options are turned off. If there are no args, the positional parameters remain unchanged. The options are off by default unless otherwise noted. Using + rather than - causes these options to be turned off. The options can also be specified as arguments to an invocation of the shell. The current set of options may be found in $-. The return status is always true unless an invalid option is encountered. shift [n] The positional parameters from n+1 ... are renamed to $1 .... Parameters represented by the numbers $# down to $#-n+1 are unset. n must be a non-negative number less than or equal to $#. If n is 0, no parameters are changed. If n is not given, it is assumed to be 1. If n is greater than $#, the positional parameters are not changed. The return status is greater than zero if n is greater than $# or less than zero; otherwise 0. shopt [-pqsu] [-o] [optname ...] Toggle the values of variables controlling optional shell behavior. With no options, or with the -p option, a list of all settable options is displayed, with an indication of whether or not each is set. The -p option causes output to be displayed in a form that may be reused as input. Other options have the following meanings: -s Enable (set) each optname. -u Disable (unset) each optname. -q Suppresses normal output (quiet mode); the return status indicates whether the optname is set or unset. If multiple optname arguments are given with -q, the return status is zero if all optnames are enabled; non-zero otherwise. -o Restricts the values of optname to be those defined for the -o option to the set builtin. If either -s or -u is used with no optname arguments, the display is limited to those options which are set or unset, respectively. Unless otherwise noted, the shopt options are disabled (unset) by default. The return status when listing options is zero if all optnames are enabled, non-zero otherwise. When setting or unsetting options, the return status is zero unless an optname is not a valid shell option. The list of shopt options is: cdable_vars If set, an argument to the cd builtin command that is not a directory is assumed to be the name of a variable whose value is the directory to change to. cdspell If set, minor errors in the spelling of a directory component in a cd command will be corrected. The errors checked for are transposed characters, a missing character, and one character too many. If a correction is found, the corrected file name is printed, and the command proceeds. This option is only used by interactive shells. checkhash If set, bash checks that a command found in the hash table exists before trying to execute it. If a hashed command no longer exists, a normal path search is performed. checkwinsize If set, bash checks the window size after each command and, if necessary, updates the values of LINES and COLUMNS. cmdhist If set, bash attempts to save all lines of a multiple- line command in the same history entry. This allows easy re-editing of multi-line commands. compat31 If set, bash changes its behavior to that of version 3.1 with respect to quoted arguments to the conditional command's =~ operator. dotglob If set, bash includes filenames beginning with a `.' in the results of pathname expansion. execfail If set, a non-interactive shell will not exit if it cannot execute the file specified as an argument to the exec builtin command. An interactive shell does not exit if exec fails. expand_aliases If set, aliases are expanded as described above under ALIASES. This option is enabled by default for interactive shells. extdebug If set, behavior intended for use by debuggers is enabled: 1. The -F option to the declare builtin displays the source file name and line number corresponding to each function name supplied as an argument. 2. If the command run by the DEBUG trap returns a non-zero value, the next command is skipped and not executed. 3. If the command run by the DEBUG trap returns a value of 2, and the shell is executing in a subroutine (a shell function or a shell script executed by the . or source builtins), a call to return is simulated. 4. BASH_ARGC and BASH_ARGV are updated as described in their descriptions above. 5. Function tracing is enabled: command substitution, shell functions, and subshells invoked with ( command ) inherit the DEBUG and RETURN traps. 6. Error tracing is enabled: command substitution, shell functions, and subshells invoked with ( command ) inherit the ERROR trap. extglob If set, the extended pattern matching features described above under Pathname Expansion are enabled. extquote If set, $'string' and $"string" quoting is performed within ${parameter} expansions enclosed in double quotes. This option is enabled by default. failglob If set, patterns which fail to match filenames during pathname expansion result in an expansion error. force_fignore If set, the suffixes specified by the FIGNORE shell variable cause words to be ignored when performing word completion even if the ignored words are the only possible completions. See SHELL VARIABLES above for a description of FIGNORE. This option is enabled by default. gnu_errfmt If set, shell error messages are written in the standard GNU error message format. histappend If set, the history list is appended to the file named by the value of the HISTFILE variable when the shell exits, rather than overwriting the file. histreedit If set, and readline is being used, a user is given the opportunity to re-edit a failed history substitution. histverify If set, and readline is being used, the results of history substitution are not immediately passed to the shell parser. Instead, the resulting line is loaded into the readline editing buffer, allowing further modification. hostcomplete If set, and readline is being used, bash will attempt to perform hostname completion when a word containing a @ is being completed (see Completing under READLINE above). This is enabled by default. huponexit If set, bash will send SIGHUP to all jobs when an interactive login shell exits. interactive_comments If set, allow a word beginning with # to cause that word and all remaining characters on that line to be ignored in an interactive shell (see COMMENTS above). This option is enabled by default. lithist If set, and the cmdhist option is enabled, multi-line commands are saved to the history with embedded newlines rather than using semicolon separators where possible. login_shell The shell sets this option if it is started as a login shell (see INVOCATION above). The value may not be changed. mailwarn If set, and a file that bash is checking for mail has been accessed since the last time it was checked, the message ``The mail in mailfile has been read'' is displayed. no_empty_cmd_completion If set, and readline is being used, bash will not attempt to search the PATH for possible completions when completion is attempted on an empty line. nocaseglob If set, bash matches filenames in a case-insensitive fashion when performing pathname expansion (see Pathname Expansion above). nocasematch If set, bash matches patterns in a case-insensitive fashion when performing matching while executing case or [[ conditional commands. nullglob If set, bash allows patterns which match no files (see Pathname Expansion above) to expand to a null string, rather than themselves. progcomp If set, the programmable completion facilities (see Programmable Completion above) are enabled. This option is enabled by default. promptvars If set, prompt strings undergo parameter expansion, command substitution, arithmetic expansion, and quote removal after being expanded as described in PROMPTING above. This option is enabled by default. restricted_shell The shell sets this option if it is started in restricted mode (see RESTRICTED SHELL below). The value may not be changed. This is not reset when the startup files are executed, allowing the startup files to discover whether or not a shell is restricted. shift_verbose If set, the shift builtin prints an error message when the shift count exceeds the number of positional parameters. sourcepath If set, the source (.) builtin uses the value of PATH to find the directory containing the file supplied as an argument. This option is enabled by default. xpg_echo If set, the echo builtin expands backslash-escape sequences by default. suspend [-f] Suspend the execution of this shell until it receives a SIGCONT signal. The -f option says not to complain if this is a login shell; just suspend anyway. The return status is 0 unless the shell is a login shell and -f is not supplied, or if job control is not enabled. test expr [ expr ] Return a status of 0 or 1 depending on the evaluation of the conditional expression expr. Each operator and operand must be a separate argument. Expressions are composed of the primaries described above under CONDITIONAL EXPRESSIONS. test does not accept any options, nor does it accept and ignore an argument of -- as signifying the end of options. Expressions may be combined using the following operators, listed in decreasing order of precedence. ! expr True if expr is false. ( expr ) Returns the value of expr. This may be used to override the normal precedence of operators. expr1 -a expr2 True if both expr1 and expr2 are true. expr1 -o expr2 True if either expr1 or expr2 is true. test and [ evaluate conditional expressions using a set of rules based on the number of arguments. 0 arguments The expression is false. 1 argument The expression is true if and only if the argument is not null. 2 arguments If the first argument is !, the expression is true if and only if the second argument is null. If the first argument is one of the unary conditional operators listed above under CONDITIONAL EXPRESSIONS, the expression is true if the unary test is true. If the first argument is not a valid unary conditional operator, the expression is false. 3 arguments If the second argument is one of the binary conditional operators listed above under CONDITIONAL EXPRESSIONS, the result of the expression is the result of the binary test using the first and third arguments as operands. If the first argument is !, the value is the negation of the two-argument test using the second and third arguments. If the first argument is exactly ( and the third argument is exactly ), the result is the one-argument test of the second argument. Otherwise, the expression is false. The -a and -o operators are considered binary operators in this case. 4 arguments If the first argument is !, the result is the negation of the three-argument expression composed of the remaining arguments. Otherwise, the expression is parsed and evaluated according to precedence using the rules listed above. 5 or more arguments The expression is parsed and evaluated according to precedence using the rules listed above. times Print the accumulated user and system times for the shell and for processes run from the shell. The return status is 0. trap [-lp] [[arg] sigspec ...] The command arg is to be read and executed when the shell receives signal(s) sigspec. If arg is absent (and there is a single sigspec) or -, each specified signal is reset to its original disposition (the value it had upon entrance to the shell). If arg is the null string the signal specified by each sigspec is ignored by the shell and by the commands it invokes. If arg is not present and -p has been supplied, then the trap commands associated with each sigspec are displayed. If no arguments are supplied or if only -p is given, trap prints the list of commands associated with each signal. The -l option causes the shell to print a list of signal names and their corresponding numbers. Each sigspec is either a signal name defined in <signal.h>, or a signal number. Signal names are case insensitive and the SIG prefix is optional. If a sigspec is EXIT (0) the command arg is executed on exit from the shell. If a sigspec is DEBUG, the command arg is executed before every simple command, for command, case command, select command, every arithmetic for command, and before the first command executes in a shell function (see SHELL GRAMMAR above). Refer to the description of the extdebug option to the shopt builtin for details of its effect on the DEBUG trap. If a sigspec is ERR, the command arg is executed whenever a simple command has a non-zero exit status, subject to the following conditions. The ERR trap is not executed if the failed command is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a && or ⎪⎪ list, or if the command's return value is being inverted via !. These are the same conditions obeyed by the errexit option. If a sigspec is RETURN, the command arg is executed each time a shell function or a script executed with the . or source builtins finishes executing. Signals ignored upon entry to the shell cannot be trapped or reset. Trapped signals that are not being ignored are reset to their original values in a child process when it is created. The return status is false if any sigspec is invalid; otherwise trap returns true. type [-aftpP] name [name ...] With no options, indicate how each name would be interpreted if used as a command name. If the -t option is used, type prints a string which is one of alias, keyword, function, builtin, or file if name is an alias, shell reserved word, function, builtin, or disk file, respectively. If the name is not found, then nothing is printed, and an exit status of false is returned. If the -p option is used, type either returns the name of the disk file that would be executed if name were specified as a command name, or nothing if ``type -t name'' would not return file. The -P option forces a PATH search for each name, even if ``type -t name'' would not return file. If a command is hashed, -p and -P print the hashed value, not necessarily the file that appears first in PATH. If the -a option is used, type prints all of the places that contain an executable named name. This includes aliases and functions, if and only if the -p option is not also used. The table of hashed commands is not consulted when using -a. The -f option suppresses shell function lookup, as with the command builtin. type returns true if any of the arguments are found, false if none are found. ulimit [-SHacdefilmnpqrstuvx [limit]] Provides control over the resources available to the shell and to processes started by it, on systems that allow such control. The -H and -S options specify that the hard or soft limit is set for the given resource. A hard limit cannot be increased once it is set; a soft limit may be increased up to the value of the hard limit. If neither -H nor -S is specified, both the soft and hard limits are set. The value of limit can be a number in the unit specified for the resource or one of the special values hard, soft, or unlimited, which stand for the current hard limit, the current soft limit, and no limit, respectively. If limit is omitted, the current value of the soft limit of the resource is printed, unless the -H option is given. When more than one resource is specified, the limit name and unit are printed before the value. Other options are interpreted as follows: -a All current limits are reported -c The maximum size of core files created -d The maximum size of a process's data segment -e The maximum scheduling priority ("nice") -f The maximum size of files written by the shell and its children -i The maximum number of pending signals -l The maximum size that may be locked into memory -m The maximum resident set size -n The maximum number of open file descriptors (most systems do not allow this value to be set) -p The pipe size in 512-byte blocks (this may not be set) -q The maximum number of bytes in POSIX message queues -r The maximum real-time scheduling priority -s The maximum stack size -t The maximum amount of cpu time in seconds -u The maximum number of processes available to a single user -v The maximum amount of virtual memory available to the shell -x The maximum number of file locks If limit is given, it is the new value of the specified resource (the -a option is display only). If no option is given, then -f is assumed. Values are in 1024-byte increments, except for -t, which is in seconds, -p, which is in units of 512-byte blocks, and -n and -u, which are unscaled values. The return status is 0 unless an invalid option or argument is supplied, or an error occurs while setting a new limit. umask [-p] [-S] [mode] The user file-creation mask is set to mode. If mode begins with a digit, it is interpreted as an octal number; otherwise it is interpreted as a symbolic mode mask similar to that accepted by chmod(1). If mode is omitted, the current value of the mask is printed. The -S option causes the mask to be printed in symbolic form; the default output is an octal number. If the -p option is supplied, and mode is omitted, the output is in a form that may be reused as input. The return status is 0 if the mode was successfully changed or if no mode argument was supplied, and false otherwise. unalias [-a] [name ...] Remove each name from the list of defined aliases. If -a is supplied, all alias definitions are removed. The return value is true unless a supplied name is not a defined alias. unset [-fv] [name ...] For each name, remove the corresponding variable or function. If no options are supplied, or the -v option is given, each name refers to a shell variable. Read-only variables may not be unset. If -f is specified, each name refers to a shell function, and the function definition is removed. Each unset variable or function is removed from the environment passed to subsequent commands. If any of RANDOM, SECONDS, LINENO, HISTCMD, FUNCNAME, GROUPS, or DIRSTACK are unset, they lose their special properties, even if they are subsequently reset. The exit status is true unless a name is readonly. wait [n ...] Wait for each specified process and return its termination status. Each n may be a process ID or a job specification; if a job spec is given, all processes in that job's pipeline are waited for. If n is not given, all currently active child processes are waited for, and the return status is zero. If n specifies a non-existent process or job, the return status is 127. Otherwise, the return status is the exit status of the last process or job waited for. RESTRICTED SHELL If bash is started with the name rbash, or the -r option is supplied at invocation, the shell becomes restricted. A restricted shell is used to set up an environment more controlled than the standard shell. It behaves identically to bash with the exception that the following are disallowed or not performed: • changing directories with cd • setting or unsetting the values of SHELL, PATH, ENV, or BASH_ENV • specifying command names containing / • specifying a file name containing a / as an argument to the . builtin command • Specifying a filename containing a slash as an argument to the -p option to the hash builtin command • importing function definitions from the shell environment at startup • parsing the value of SHELLOPTS from the shell environment at startup • redirecting output using the >, >|, <>, >&, &>, and >> redirection operators • using the exec builtin command to replace the shell with another command • adding or deleting builtin commands with the -f and -d options to the enable builtin command • Using the enable builtin command to enable disabled shell builtins • specifying the -p option to the command builtin command • turning off restricted mode with set +r or set +o restricted. These restrictions are enforced after any startup files are read. When a command that is found to be a shell script is executed (see COMMAND EXECUTION above), rbash turns off any restrictions in the shell spawned to execute the script. SEE ALSO Bash Reference Manual, Brian Fox and Chet Ramey The Gnu Readline Library, Brian Fox and Chet Ramey The Gnu History Library, Brian Fox and Chet Ramey Portable Operating System Interface (POSIX) Part 2: Shell and Utilities, IEEE sh(1), ksh(1), csh(1) emacs(1), vi(1) readline(3) FILES /bin/bash The bash executable /etc/profile The systemwide initialization file, executed for login shells ~/.bash_profile The personal initialization file, executed for login shells ~/.bashrc The individual per-interactive-shell startup file ~/.bash_logout The individual login shell cleanup file, executed when a login shell exits ~/.inputrc Individual readline initialization file AUTHORS Brian Fox, Free Software Foundation bfox@gnu.org Chet Ramey, Case Western Reserve University chet@po.cwru.edu BUG REPORTS If you find a bug in bash, you should report it. But first, you should make sure that it really is a bug, and that it appears in the latest version of bash. The latest version is always available from ftp://ftp.gnu.org/pub/bash/. Once you have determined that a bug actually exists, use the bashbug command to submit a bug report. If you have a fix, you are encouraged to mail that as well! Suggestions and `philosophical' bug reports may be mailed to bug-bash@gnu.org or posted to the Usenet newsgroup gnu.bash.bug. ALL bug reports should include: The version number of bash The hardware and operating system The compiler used to compile A description of the bug behaviour A short script or `recipe' which exercises the bug bashbug inserts the first three items automatically into the template it provides for filing a bug report. Comments and bug reports concerning this manual page should be directed to chet@po.cwru.edu. BUGS It's too big and too slow. There are some subtle differences between bash and traditional versions of sh, mostly because of the POSIX specification. Aliases are confusing in some uses. Shell builtin commands and functions are not stoppable/restartable. Compound commands and command sequences of the form `a ; b ; c' are not handled gracefully when process suspension is attempted. When a process is stopped, the shell immediately executes the next command in the sequence. It suffices to place the sequence of commands between parentheses to force it into a subshell, which may be stopped as a unit. Commands inside of $(...) command substitution are not parsed until substitution is attempted. This will delay error reporting until some time after the command is entered. For example, unmatched parentheses, even inside shell comments, will result in error messages while the construct is being read. Array variables may not (yet) be exported. GNU Bash-3.2 2006 September 28 BASH(1)
null
kill
The kill utility sends a signal to the processes specified by the pid operands. Only the super-user may send signals to other users' processes. The options are as follows: -s signal_name A symbolic signal name specifying the signal to be sent instead of the default TERM. -l [exit_status] If no operand is given, list the signal names; otherwise, write the signal name corresponding to exit_status. -signal_name A symbolic signal name specifying the signal to be sent instead of the default TERM. -signal_number A non-negative decimal integer, specifying the signal to be sent instead of the default TERM. The following PIDs have special meanings: -1 If superuser, broadcast the signal to all processes; otherwise broadcast to all processes belonging to the user. Some of the more commonly used signals: 1 HUP (hang up) 2 INT (interrupt) 3 QUIT (quit) 6 ABRT (abort) 9 KILL (non-catchable, non-ignorable kill) 14 ALRM (alarm clock) 15 TERM (software termination signal) Some shells may provide a builtin kill command which is similar or identical to this utility. Consult the builtin(1) manual page. EXIT STATUS The kill utility exits 0 on success, and >0 if an error occurs.
kill – terminate or signal a process
kill [-s signal_name] pid ... kill -l [exit_status] kill -signal_name pid ... kill -signal_number pid ...
null
Terminate the processes with PIDs 142 and 157: kill 142 157 Send the hangup signal (SIGHUP) to the process with PID 507: kill -s HUP 507 Terminate the process group with PGID 117: kill -- -117 SEE ALSO builtin(1), csh(1), killall(1), ps(1), sh(1), kill(2), sigaction(2) STANDARDS The kill utility is expected to be IEEE Std 1003.2 (“POSIX.2”) compatible. HISTORY A kill command appeared in Version 3 AT&T UNIX in section 8 of the manual. BUGS A replacement for the command “kill 0” for csh(1) users should be provided. macOS 14.5 October 3, 2016 macOS 14.5
sh
sh is a POSIX-compliant command interpreter (shell). It is implemented by re-execing as either bash(1), dash(1), or zsh(1) as determined by the symbolic link located at /private/var/select/sh. If /private/var/select/sh does not exist or does not point to a valid shell, sh will use one of the supported shells. FILES /private/var/select/sh $HOME/.profile /etc/profile SEE ALSO bash(1), dash(1), ksh(1), tcsh(1), zsh(1) macOS 14.5 February 8, 2019 macOS 14.5
sh – POSIX-compliant command interpreter
sh [options]
null
null
ps
The ps utility displays a header line, followed by lines containing information about all of your processes that have controlling terminals. A different set of processes can be selected for display by using any combination of the -a, -G, -g, -p, -T, -t, -U, and -u options. If more than one of these options are given, then ps will select all processes which are matched by at least one of the given options. For the processes which have been selected for display, ps will usually display one line per process. The -M option may result in multiple output lines (one line per thread) for some processes. By default all of these output lines are sorted first by controlling terminal, then by process ID. The -m, -r, and -v options will change the sort order. If more than one sorting option was given, then the selected processes will be sorted by the last sorting option which was specified. For the processes which have been selected for display, the information to display is selected based on a set of keywords (see the -L, -O, and -o options). The default output format includes, for each process, the process' ID, controlling terminal, CPU time (including both user and system time), state, and associated command. The options are as follows: -A Display information about other users' processes, including those without controlling terminals. -a Display information about other users' processes as well as your own. This will skip any processes which do not have a controlling terminal, unless the -x option is also specified. -C Change the way the CPU percentage is calculated by using a “raw” CPU calculation that ignores “resident” time (this normally has no effect). -c Change the “command” column output to just contain the executable name, rather than the full command line. -d Like -A, but excludes session leaders. -E Display the environment as well. This does not reflect changes in the environment after process launch. -e Identical to -A. -f Display the uid, pid, parent pid, recent CPU usage, process start time, controlling tty, elapsed CPU usage, and the associated command. If the -u option is also used, display the user name rather then the numeric uid. When -o or -O is used to add to the display following -f, the command field is not truncated as severely as it is in other formats. -G Display information about processes which are running with the specified real group IDs. -g Display information about processes with the specified process group leaders. -h Repeat the information header as often as necessary to guarantee one header per page of information. -j Print information associated with the following keywords: user, pid, ppid, pgid, sess, jobc, state, tt, time, and command. -L List the set of keywords available for the -O and -o options. -l Display information associated with the following keywords: uid, pid, ppid, flags, cpu, pri, nice, vsz=SZ, rss, wchan, state=S, paddr=ADDR, tty, time, and command=CMD. -M Print the threads corresponding to each task. -m Sort by memory usage, instead of the combination of controlling terminal and process ID. -O Add the information associated with the space or comma separated list of keywords specified, after the process ID, in the default information display. Keywords may be appended with an equals (‘=’) sign and a string. This causes the printed header to use the specified string instead of the standard header. -o Display information associated with the space or comma separated list of keywords specified. Multiple keywords may also be given in the form of more than one -o option. Keywords may be appended with an equals (‘=’) sign and a string. This causes the printed header to use the specified string instead of the standard header. If all keywords have empty header texts, no header line is written. -p Display information about processes which match the specified process IDs. -r Sort by current CPU usage, instead of the combination of controlling terminal and process ID. -S Change the way the process time is calculated by summing all exited children to their parent process. -T Display information about processes attached to the device associated with the standard input. -t Display information about processes attached to the specified terminal devices. -U Display the processes belonging to the specified real user IDs. -u Display the processes belonging to the specified usernames. -v Display information associated with the following keywords: pid, state, time, sl, re, pagein, vsz, rss, lim, tsiz, %cpu, %mem, and command. The -v option implies the -m option. -w Use 132 columns to display information, instead of the default which is your window size. If the -w option is specified more than once, ps will use as many columns as necessary without regard for your window size. When output is not to a terminal, an unlimited number of columns are always used. -X When displaying processes matched by other options, skip any processes which do not have a controlling terminal. -x When displaying processes matched by other options, include processes which do not have a controlling terminal. This is the opposite of the -X option. If both -X and -x are specified in the same command, then ps will use the one which was specified last. A complete list of the available keywords is given below. Some of these keywords are further specified as follows: %cpu The CPU utilization of the process; this is a decaying average over up to a minute of previous (real) time. Because the time base over which this is computed varies (some processes may be very young), it is possible for the sum of all %cpu fields to exceed 100%. %mem The percentage of real memory used by this process. flags The flags associated with the process as in the include file <sys/proc.h>: P_ADVLOCK 0x00001 Process may hold a POSIX advisory lock P_CONTROLT 0x00002 Has a controlling terminal P_LP64 0x00004 Process is LP64 P_NOCLDSTOP 0x00008 No SIGCHLD when children stop P_PPWAIT 0x00010 Parent is waiting for child to exec/exit P_PROFIL 0x00020 Has started profiling P_SELECT 0x00040 Selecting; wakeup/waiting danger P_CONTINUED 0x00080 Process was stopped and continued P_SUGID 0x00100 Had set id privileges since last exec P_SYSTEM 0x00200 System proc: no sigs, stats or swapping P_TIMEOUT 0x00400 Timing out during sleep P_TRACED 0x00800 Debugged process being traced P_WAITED 0x01000 Debugging process has waited for child P_WEXIT 0x02000 Working on exiting P_EXEC 0x04000 Process called exec P_OWEUPC 0x08000 Owe process an addupc() call at next ast P_WAITING 0x40000 Process has a wait() in progress P_KDEBUG 0x80000 Kdebug tracing on for this process lim The soft limit on memory used, specified via a call to setrlimit(2). lstart The exact time the command started, using the ‘%c’ format described in strftime(3). nice The process scheduling increment (see setpriority(2)). rss the real memory (resident set) size of the process (in 1024 byte units). start The time the command started. If the command started less than 24 hours ago, the start time is displayed using the “%l:ps.1p” format described in strftime(3). If the command started less than 7 days ago, the start time is displayed using the “%a6.15p” format. Otherwise, the start time is displayed using the “%e%b%y” format. state The state is given by a sequence of characters, for example, “RWNA”. The first character indicates the run state of the process: I Marks a process that is idle (sleeping for longer than about 20 seconds). R Marks a runnable process. S Marks a process that is sleeping for less than about 20 seconds. T Marks a stopped process. U Marks a process in uninterruptible wait. Z Marks a dead process (a “zombie”). Additional characters after these, if any, indicate additional state information: + The process is in the foreground process group of its control terminal. < The process has raised CPU scheduling priority. > The process has specified a soft limit on memory requirements and is currently exceeding that limit; such a process is (necessarily) not swapped. A the process has asked for random page replacement (VA_ANOM, from vadvise(2), for example, lisp(1) in a garbage collect). E The process is trying to exit. L The process has pages locked in core (for example, for raw I/O). N The process has reduced CPU scheduling priority (see setpriority(2)). S The process has asked for FIFO page replacement (VA_SEQL, from vadvise(2), for example, a large image processing program using virtual memory to sequentially address voluminous data). s The process is a session leader. V The process is suspended during a vfork(2). W The process is swapped out. X The process is being traced or debugged. tt An abbreviation for the pathname of the controlling terminal, if any. The abbreviation consists of the three letters following /dev/tty, or, for the console, “con”. This is followed by a ‘-’ if the process can no longer reach that controlling terminal (i.e., it has been revoked). wchan The event (an address in the system) on which a process waits. When printed numerically, the initial part of the address is trimmed off and the result is printed in hex, for example, 0x80324000 prints as 324000. When printing using the command keyword, a process that has exited and has a parent that has not yet waited for the process (in other words, a zombie) is listed as “<defunct>”, and a process which is blocked while trying to exit is listed as “<exiting>”. If the arguments cannot be located (usually because it has not been set, as is the case of system processes and/or kernel threads) the command name is printed within square brackets. The process can change the arguments shown with setproctitle(3). Otherwise, ps makes an educated guess as to the file name and arguments given when the process was created by examining memory or the swap area. The method is inherently somewhat unreliable and in any event a process is entitled to destroy this information. The ucomm (accounting) keyword can, however, be depended on. If the arguments are unavailable or do not agree with the ucomm keyword, the value for the ucomm keyword is appended to the arguments in parentheses. KEYWORDS The following is a complete list of the available keywords and their meanings. Several of them have aliases (keywords which are synonyms). %cpu percentage CPU usage (alias pcpu) %mem percentage memory usage (alias pmem) acflag accounting flag (alias acflg) args command and arguments comm command command command and arguments cpu short-term CPU usage factor (for scheduling) etime elapsed running time flags the process flags, in hexadecimal (alias f) gid processes group id (alias group) inblk total blocks read (alias inblock) jobc job control count ktrace tracing flags ktracep tracing vnode lim memoryuse limit logname login name of user who started the session lstart time started majflt total page faults minflt total page reclaims msgrcv total messages received (reads from pipes/sockets) msgsnd total messages sent (writes on pipes/sockets) nice nice value (alias ni) nivcsw total involuntary context switches nsigs total signals taken (alias nsignals) nswap total swaps in/out nvcsw total voluntary context switches nwchan wait channel (as an address) oublk total blocks written (alias oublock) p_ru resource usage (valid only for zombie) paddr swap address pagein pageins (same as majflt) pgid process group number pid process ID ppid parent process ID pri scheduling priority prsna persona re core residency time (in seconds; 127 = infinity) rgid real group ID rss resident set size ruid real user ID ruser user name (from ruid) sess session ID sig pending signals (alias pending) sigmask blocked signals (alias blocked) sl sleep time (in seconds; 127 = infinity) start time started state symbolic process state (alias stat) svgid saved gid from a setgid executable svuid saved UID from a setuid executable tdev control terminal device number time accumulated CPU time, user + system (alias cputime) tpgid control terminal process group ID tsess control terminal session ID tsiz text size (in Kbytes) tt control terminal name (two letter abbreviation) tty full name of control terminal ucomm name to be used for accounting uid effective user ID upr scheduling priority on return from system call (alias usrpri) user user name (from UID) utime user CPU time (alias putime) vsz virtual size in Kbytes (alias vsize) wchan wait channel (as a symbolic name) wq total number of workqueue threads wqb number of blocked workqueue threads wqr number of running workqueue threads wql workqueue limit status (C = constrained thread limit, T = total thread limit) xstat exit or stop status (valid only for stopped or zombie process) ENVIRONMENT The following environment variables affect the execution of ps: COLUMNS If set, specifies the user's preferred output width in column positions. By default, ps attempts to automatically determine the terminal width. FILES /dev special files and device names /var/run/dev.db /dev name database /var/db/kvm_kernel.db system namelist database LEGACY DESCRIPTION In legacy mode, ps functions as described above, with the following differences: -e Display the environment as well. Same as -E. -g Ignored for compatibility. Takes no argument. -l Display information associated with the following keywords: uid, pid, ppid, cpu, pri, nice, vsz, rss, wchan, state, tt, time, and command. -u Display information associated with the following keywords: user, pid, %cpu, %mem, vsz, rss, tt, state, start, time, and command. The -u option implies the -r option. The biggest change is in the interpretation of the -u option, which now displays processes belonging to the specified username(s). Thus, "ps -aux" will fail (unless you want to know about user "x"). As a convenience, however, "ps aux" still works as it did in Tiger. For more information about legacy mode, see compat(5). SEE ALSO kill(1), w(1), kvm(3), strftime(3), sysctl(8) STANDARDS The ps utility supports the Version 3 of the Single UNIX Specification (“SUSv3”) standard. HISTORY The ps command appeared in Version 4 AT&T UNIX. BUGS Since ps cannot run faster than the system and is run as any other scheduled process, the information it displays can never be exact. The ps utility does not correctly display argument lists containing multibyte characters. macOS 14.5 March 20, 2005 macOS 14.5
ps – process status
ps [-AaCcEefhjlMmrSTvwXx] [-O fmt | -o fmt] [-G gid[,gid...]] [-g grp[,grp...]] [-u uid[,uid...]] [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]] ps [-L]
null
null
link
The ln utility creates a new directory entry (linked file) for the file name specified by target_file. The target_file will be created with the same file modes as the source_file. It is useful for maintaining multiple copies of a file in many places at once without using up storage for the “copies”; instead, a link “points” to the original copy. There are two types of links; hard links and symbolic links. How a link “points” to a file is one of the differences between a hard and symbolic link. The options are as follows: -F If the target file already exists and is a directory, then remove it so that the link may occur. The -F option should be used with either -f or -i options. If neither -f nor -i is specified, -f is implied. The -F option is a no-op unless -s is specified. -L When creating a hard link to a symbolic link, create a hard link to the target of the symbolic link. This is the default. This option cancels the -P option. -P When creating a hard link to a symbolic link, create a hard link to the symbolic link itself. This option cancels the -L option. -f If the target file already exists, then unlink it so that the link may occur. (The -f option overrides any previous -i and -w options.) -h If the target_file or target_dir is a symbolic link, do not follow it. This is most useful with the -f option, to replace a symlink which may point to a directory. -i Cause ln to write a prompt to standard error if the target file exists. If the response from the standard input begins with the character ‘y’ or ‘Y’, then unlink the target file so that the link may occur. Otherwise, do not attempt the link. (The -i option overrides any previous -f options.) -n Same as -h, for compatibility with other ln implementations. -s Create a symbolic link. -v Cause ln to be verbose, showing files as they are processed. -w Warn if the source of a symbolic link does not currently exist. By default, ln makes hard links. A hard link to a file is indistinguishable from the original directory entry; any changes to a file are effectively independent of the name used to reference the file. Directories may not be hardlinked, and hard links may not span file systems. A symbolic link contains the name of the file to which it is linked. The referenced file is used when an open(2) operation is performed on the link. A stat(2) on a symbolic link will return the linked-to file; an lstat(2) must be done to obtain information about the link. The readlink(2) call may be used to read the contents of a symbolic link. Symbolic links may span file systems and may refer to directories. Given one or two arguments, ln creates a link to an existing file source_file. If target_file is given, the link has that name; target_file may also be a directory in which to place the link; otherwise it is placed in the current directory. If only the directory is specified, the link will be made to the last component of source_file. Given more than two arguments, ln makes links in target_dir to all the named source files. The links made will have the same name as the files being linked to. When the utility is called as link, exactly two arguments must be supplied, neither of which may specify a directory. No options may be supplied in this simple mode of operation, which performs a link(2) operation using the two passed arguments.
ln, link – link files
ln [-L | -P | -s [-F]] [-f | -iw] [-hnv] source_file [target_file] ln [-L | -P | -s [-F]] [-f | -iw] [-hnv] source_file ... target_dir link source_file target_file
null
Create a symbolic link named /home/src and point it to /usr/src: # ln -s /usr/src /home/src Hard link /usr/local/bin/fooprog to file /usr/local/bin/fooprog-1.0: # ln /usr/local/bin/fooprog-1.0 /usr/local/bin/fooprog As an exercise, try the following commands: # ls -i /bin/[ 11553 /bin/[ # ls -i /bin/test 11553 /bin/test Note that both files have the same inode; that is, /bin/[ is essentially an alias for the test(1) command. This hard link exists so test(1) may be invoked from shell scripts, for example, using the if [ ] construct. In the next example, the second call to ln removes the original foo and creates a replacement pointing to baz: # mkdir bar baz # ln -s bar foo # ln -shf baz foo Without the -h option, this would instead leave foo pointing to bar and inside foo create a new symlink baz pointing to itself. This results from directory-walking. An easy rule to remember is that the argument order for ln is the same as for cp(1): The first argument needs to exist, the second one is created. COMPATIBILITY The -h, -i, -n, -v and -w options are non-standard and their use in scripts is not recommended. They are provided solely for compatibility with other ln implementations. The -F option is a FreeBSD extension and should not be used in portable scripts. SEE ALSO link(2), lstat(2), readlink(2), stat(2), symlink(2), symlink(7) STANDARDS The ln utility conforms to IEEE Std 1003.2-1992 (“POSIX.2”). The simplified link command conforms to Version 2 of the Single UNIX Specification (“SUSv2”). HISTORY An ln command appeared in Version 1 AT&T UNIX. macOS 14.5 May 10, 2021 macOS 14.5
tcsh
tcsh is an enhanced but completely compatible version of the Berkeley UNIX C shell, csh(1). It is a command language interpreter usable both as an interactive login shell and a shell script command processor. It includes a command-line editor (see The command-line editor), programmable word completion (see Completion and listing), spelling correction (see Spelling correction), a history mechanism (see History substitution), job control (see Jobs) and a C-like syntax. The NEW FEATURES section describes major enhancements of tcsh over csh(1). Throughout this manual, features of tcsh not found in most csh(1) implementations (specifically, the 4.4BSD csh) are labeled with `(+)', and features which are present in csh(1) but not usually documented are labeled with `(u)'. Argument list processing If the first argument (argument 0) to the shell is `-' then it is a login shell. A login shell can be also specified by invoking the shell with the -l flag as the only argument. The rest of the flag arguments are interpreted as follows: -b Forces a ``break'' from option processing, causing any further shell arguments to be treated as non-option arguments. The remaining arguments will not be interpreted as shell options. This may be used to pass options to a shell script without confusion or possible subterfuge. The shell will not run a set-user ID script without this option. -c Commands are read from the following argument (which must be present, and must be a single argument), stored in the command shell variable for reference, and executed. Any remaining arguments are placed in the argv shell variable. -d The shell loads the directory stack from ~/.cshdirs as described under Startup and shutdown, whether or not it is a login shell. (+) -Dname[=value] Sets the environment variable name to value. (Domain/OS only) (+) -e The shell exits if any invoked command terminates abnormally or yields a non-zero exit status. -f The shell does not load any resource or startup files, or perform any command hashing, and thus starts faster. -F The shell uses fork(2) instead of vfork(2) to spawn processes. This is now the default and this option is ignored. (+) -i The shell is interactive and prompts for its top-level input, even if it appears to not be a terminal. Shells are interactive without this option if their inputs and outputs are terminals. -l The shell is a login shell. Applicable only if -l is the only flag specified. -m The shell loads ~/.tcshrc even if it does not belong to the effective user. Newer versions of su(1) can pass -m to the shell. (+) -n The shell parses commands but does not execute them. This aids in debugging shell scripts. -q The shell accepts SIGQUIT (see Signal handling) and behaves when it is used under a debugger. Job control is disabled. (u) -s Command input is taken from the standard input. -t The shell reads and executes a single line of input. A `\' may be used to escape the newline at the end of this line and continue onto another line. -v Sets the verbose shell variable, so that command input is echoed after history substitution. -x Sets the echo shell variable, so that commands are echoed immediately before execution. -V Sets the verbose shell variable even before executing ~/.tcshrc. -X Is to -x as -V is to -v. --help Print a help message on the standard output and exit. (+) --version Print the version/platform/compilation options on the standard output and exit. This information is also contained in the version shell variable. (+) After processing of flag arguments, if arguments remain but none of the -c, -i, -s, or -t options were given, the first argument is taken as the name of a file of commands, or ``script'', to be executed. The shell opens this file and saves its name for possible resubstitution by `$0'. Because many systems use either the standard version 6 or version 7 shells whose shell scripts are not compatible with this shell, the shell uses such a `standard' shell to execute a script whose first character is not a `#', i.e., that does not start with a comment. Remaining arguments are placed in the argv shell variable. Startup and shutdown A login shell begins by executing commands from the system files /etc/csh.cshrc and /etc/csh.login. It then executes commands from files in the user's home directory: first ~/.tcshrc (+) or, if ~/.tcshrc is not found, ~/.cshrc, then the contents of ~/.history (or the value of the histfile shell variable) are loaded into memory, then ~/.login, and finally ~/.cshdirs (or the value of the dirsfile shell variable) (+). The shell may read /etc/csh.login before instead of after /etc/csh.cshrc, and ~/.login before instead of after ~/.tcshrc or ~/.cshrc and ~/.history, if so compiled; see the version shell variable. (+) Non-login shells read only /etc/csh.cshrc and ~/.tcshrc or ~/.cshrc on startup. For examples of startup files, please consult http://tcshrc.sourceforge.net. Commands like stty(1) and tset(1), which need be run only once per login, usually go in one's ~/.login file. Users who need to use the same set of files with both csh(1) and tcsh can have only a ~/.cshrc which checks for the existence of the tcsh shell variable (q.v.) before using tcsh-specific commands, or can have both a ~/.cshrc and a ~/.tcshrc which sources (see the builtin command) ~/.cshrc. The rest of this manual uses `~/.tcshrc' to mean `~/.tcshrc or, if ~/.tcshrc is not found, ~/.cshrc'. In the normal case, the shell begins reading commands from the terminal, prompting with `> '. (Processing of arguments and the use of the shell to process files containing command scripts are described later.) The shell repeatedly reads a line of command input, breaks it into words, places it on the command history list, parses it and executes each command in the line. One can log out by typing `^D' on an empty line, `logout' or `login' or via the shell's autologout mechanism (see the autologout shell variable). When a login shell terminates it sets the logout shell variable to `normal' or `automatic' as appropriate, then executes commands from the files /etc/csh.logout and ~/.logout. The shell may drop DTR on logout if so compiled; see the version shell variable. The names of the system login and logout files vary from system to system for compatibility with different csh(1) variants; see FILES. Editing We first describe The command-line editor. The Completion and listing and Spelling correction sections describe two sets of functionality that are implemented as editor commands but which deserve their own treatment. Finally, Editor commands lists and describes the editor commands specific to the shell and their default bindings. The command-line editor (+) Command-line input can be edited using key sequences much like those used in emacs(1) or vi(1). The editor is active only when the edit shell variable is set, which it is by default in interactive shells. The bindkey builtin can display and change key bindings. emacs(1)-style key bindings are used by default (unless the shell was compiled otherwise; see the version shell variable), but bindkey can change the key bindings to vi(1)-style bindings en masse. The shell always binds the arrow keys (as defined in the TERMCAP environment variable) to down down-history up up-history left backward-char right forward-char unless doing so would alter another single-character binding. One can set the arrow key escape sequences to the empty string with settc to prevent these bindings. The ANSI/VT100 sequences for arrow keys are always bound. Other key bindings are, for the most part, what emacs(1) and vi(1) users would expect and can easily be displayed by bindkey, so there is no need to list them here. Likewise, bindkey can list the editor commands with a short description of each. Certain key bindings have different behavior depending if emacs(1) or vi(1) style bindings are being used; see vimode for more information. Note that editor commands do not have the same notion of a ``word'' as does the shell. The editor delimits words with any non-alphanumeric characters not in the shell variable wordchars, while the shell recognizes only whitespace and some of the characters with special meanings to it, listed under Lexical structure. Completion and listing (+) The shell is often able to complete words when given a unique abbreviation. Type part of a word (for example `ls /usr/lost') and hit the tab key to run the complete-word editor command. The shell completes the filename `/usr/lost' to `/usr/lost+found/', replacing the incomplete word with the complete word in the input buffer. (Note the terminal `/'; completion adds a `/' to the end of completed directories and a space to the end of other completed words, to speed typing and provide a visual indicator of successful completion. The addsuffix shell variable can be unset to prevent this.) If no match is found (perhaps `/usr/lost+found' doesn't exist), the terminal bell rings. If the word is already complete (perhaps there is a `/usr/lost' on your system, or perhaps you were thinking too far ahead and typed the whole thing) a `/' or space is added to the end if it isn't already there. Completion works anywhere in the line, not at just the end; completed text pushes the rest of the line to the right. Completion in the middle of a word often results in leftover characters to the right of the cursor that need to be deleted. Commands and variables can be completed in much the same way. For example, typing `em[tab]' would complete `em' to `emacs' if emacs were the only command on your system beginning with `em'. Completion can find a command in any directory in path or if given a full pathname. Typing `echo $ar[tab]' would complete `$ar' to `$argv' if no other variable began with `ar'. The shell parses the input buffer to determine whether the word you want to complete should be completed as a filename, command or variable. The first word in the buffer and the first word following `;', `|', `|&', `&&' or `||' is considered to be a command. A word beginning with `$' is considered to be a variable. Anything else is a filename. An empty line is `completed' as a filename. You can list the possible completions of a word at any time by typing `^D' to run the delete-char-or-list-or-eof editor command. The shell lists the possible completions using the ls-F builtin (q.v.) and reprints the prompt and unfinished command line, for example: > ls /usr/l[^D] lbin/ lib/ local/ lost+found/ > ls /usr/l If the autolist shell variable is set, the shell lists the remaining choices (if any) whenever completion fails: > set autolist > nm /usr/lib/libt[tab] libtermcap.a@ libtermlib.a@ > nm /usr/lib/libterm If autolist is set to `ambiguous', choices are listed only when completion fails and adds no new characters to the word being completed. A filename to be completed can contain variables, your own or others' home directories abbreviated with `~' (see Filename substitution) and directory stack entries abbreviated with `=' (see Directory stack substitution). For example, > ls ~k[^D] kahn kas kellogg > ls ~ke[tab] > ls ~kellogg/ or > set local = /usr/local > ls $lo[tab] > ls $local/[^D] bin/ etc/ lib/ man/ src/ > ls $local/ Note that variables can also be expanded explicitly with the expand- variables editor command. delete-char-or-list-or-eof lists at only the end of the line; in the middle of a line it deletes the character under the cursor and on an empty line it logs one out or, if ignoreeof is set, does nothing. `M-^D', bound to the editor command list-choices, lists completion possibilities anywhere on a line, and list-choices (or any one of the related editor commands that do or don't delete, list and/or log out, listed under delete-char-or-list-or-eof) can be bound to `^D' with the bindkey builtin command if so desired. The complete-word-fwd and complete-word-back editor commands (not bound to any keys by default) can be used to cycle up and down through the list of possible completions, replacing the current word with the next or previous word in the list. The shell variable fignore can be set to a list of suffixes to be ignored by completion. Consider the following: > ls Makefile condiments.h~ main.o side.c README main.c meal side.o condiments.h main.c~ > set fignore = (.o \~) > emacs ma[^D] main.c main.c~ main.o > emacs ma[tab] > emacs main.c `main.c~' and `main.o' are ignored by completion (but not listing), because they end in suffixes in fignore. Note that a `\' was needed in front of `~' to prevent it from being expanded to home as described under Filename substitution. fignore is ignored if only one completion is possible. If the complete shell variable is set to `enhance', completion 1) ignores case and 2) considers periods, hyphens and underscores (`.', `-' and `_') to be word separators and hyphens and underscores to be equivalent. If you had the following files comp.lang.c comp.lang.perl comp.std.c++ comp.lang.c++ comp.std.c and typed `mail -f c.l.c[tab]', it would be completed to `mail -f comp.lang.c', and ^D would list `comp.lang.c' and `comp.lang.c++'. `mail -f c..c++[^D]' would list `comp.lang.c++' and `comp.std.c++'. Typing `rm a--file[^D]' in the following directory A_silly_file a-hyphenated-file another_silly_file would list all three files, because case is ignored and hyphens and underscores are equivalent. Periods, however, are not equivalent to hyphens or underscores. If the complete shell variable is set to `Enhance', completion ignores case and differences between a hyphen and an underscore word separator only when the user types a lowercase character or a hyphen. Entering an uppercase character or an underscore will not match the corresponding lowercase character or hyphen word separator. Typing `rm a--file[^D]' in the directory of the previous example would still list all three files, but typing `rm A--file' would match only `A_silly_file' and typing `rm a__file[^D]' would match just `A_silly_file' and `another_silly_file' because the user explicitly used an uppercase or an underscore character. Completion and listing are affected by several other shell variables: recexact can be set to complete on the shortest possible unique match, even if more typing might result in a longer match: > ls fodder foo food foonly > set recexact > rm fo[tab] just beeps, because `fo' could expand to `fod' or `foo', but if we type another `o', > rm foo[tab] > rm foo the completion completes on `foo', even though `food' and `foonly' also match. autoexpand can be set to run the expand-history editor command before each completion attempt, autocorrect can be set to spelling- correct the word to be completed (see Spelling correction) before each completion attempt and correct can be set to complete commands automatically after one hits `return'. matchbeep can be set to make completion beep or not beep in a variety of situations, and nobeep can be set to never beep at all. nostat can be set to a list of directories and/or patterns that match directories to prevent the completion mechanism from stat(2)ing those directories. listmax and listmaxrows can be set to limit the number of items and rows (respectively) that are listed without asking first. recognize_only_executables can be set to make the shell list only executables when listing commands, but it is quite slow. Finally, the complete builtin command can be used to tell the shell how to complete words other than filenames, commands and variables. Completion and listing do not work on glob-patterns (see Filename substitution), but the list-glob and expand-glob editor commands perform equivalent functions for glob-patterns. Spelling correction (+) The shell can sometimes correct the spelling of filenames, commands and variable names as well as completing and listing them. Individual words can be spelling-corrected with the spell-word editor command (usually bound to M-s and M-S) and the entire input buffer with spell-line (usually bound to M-$). The correct shell variable can be set to `cmd' to correct the command name or `all' to correct the entire line each time return is typed, and autocorrect can be set to correct the word to be completed before each completion attempt. When spelling correction is invoked in any of these ways and the shell thinks that any part of the command line is misspelled, it prompts with the corrected line: > set correct = cmd > lz /usr/bin CORRECT>ls /usr/bin (y|n|e|a)? One can answer `y' or space to execute the corrected line, `e' to leave the uncorrected command in the input buffer, `a' to abort the command as if `^C' had been hit, and anything else to execute the original line unchanged. Spelling correction recognizes user-defined completions (see the complete builtin command). If an input word in a position for which a completion is defined resembles a word in the completion list, spelling correction registers a misspelling and suggests the latter word as a correction. However, if the input word does not match any of the possible completions for that position, spelling correction does not register a misspelling. Like completion, spelling correction works anywhere in the line, pushing the rest of the line to the right and possibly leaving extra characters to the right of the cursor. Editor commands (+) `bindkey' lists key bindings and `bindkey -l' lists and briefly describes editor commands. Only new or especially interesting editor commands are described here. See emacs(1) and vi(1) for descriptions of each editor's key bindings. The character or characters to which each command is bound by default is given in parentheses. `^character' means a control character and `M-character' a meta character, typed as escape-character on terminals without a meta key. Case counts, but commands that are bound to letters by default are bound to both lower- and uppercase letters for convenience. backward-char (^B, left) Move back a character. Cursor behavior modified by vimode. backward-delete-word (M-^H, M-^?) Cut from beginning of current word to cursor - saved in cut buffer. Word boundary behavior modified by vimode. backward-word (M-b, M-B) Move to beginning of current word. Word boundary and cursor behavior modified by vimode. beginning-of-line (^A, home) Move to beginning of line. Cursor behavior modified by vimode. capitalize-word (M-c, M-C) Capitalize the characters from cursor to end of current word. Word boundary behavior modified by vimode. complete-word (tab) Completes a word as described under Completion and listing. complete-word-back (not bound) Like complete-word-fwd, but steps up from the end of the list. complete-word-fwd (not bound) Replaces the current word with the first word in the list of possible completions. May be repeated to step down through the list. At the end of the list, beeps and reverts to the incomplete word. complete-word-raw (^X-tab) Like complete-word, but ignores user-defined completions. copy-prev-word (M-^_) Copies the previous word in the current line into the input buffer. See also insert-last-word. Word boundary behavior modified by vimode. dabbrev-expand (M-/) Expands the current word to the most recent preceding one for which the current is a leading substring, wrapping around the history list (once) if necessary. Repeating dabbrev-expand without any intervening typing changes to the next previous word etc., skipping identical matches much like history-search- backward does. delete-char (not bound) Deletes the character under the cursor. See also delete-char- or-list-or-eof. Cursor behavior modified by vimode. delete-char-or-eof (not bound) Does delete-char if there is a character under the cursor or end-of-file on an empty line. See also delete-char-or-list-or- eof. Cursor behavior modified by vimode. delete-char-or-list (not bound) Does delete-char if there is a character under the cursor or list-choices at the end of the line. See also delete-char-or- list-or-eof. delete-char-or-list-or-eof (^D) Does delete-char if there is a character under the cursor, list-choices at the end of the line or end-of-file on an empty line. See also those three commands, each of which does only a single action, and delete-char-or-eof, delete-char-or-list and list-or-eof, each of which does a different two out of the three. delete-word (M-d, M-D) Cut from cursor to end of current word - save in cut buffer. Word boundary behavior modified by vimode. down-history (down-arrow, ^N) Like up-history, but steps down, stopping at the original input line. downcase-word (M-l, M-L) Lowercase the characters from cursor to end of current word. Word boundary behavior modified by vimode. end-of-file (not bound) Signals an end of file, causing the shell to exit unless the ignoreeof shell variable (q.v.) is set to prevent this. See also delete-char-or-list-or-eof. end-of-line (^E, end) Move cursor to end of line. Cursor behavior modified by vimode. expand-history (M-space) Expands history substitutions in the current word. See History substitution. See also magic-space, toggle-literal-history and the autoexpand shell variable. expand-glob (^X-*) Expands the glob-pattern to the left of the cursor. See Filename substitution. expand-line (not bound) Like expand-history, but expands history substitutions in each word in the input buffer. expand-variables (^X-$) Expands the variable to the left of the cursor. See Variable substitution. forward-char (^F, right) Move forward one character. Cursor behavior modified by vimode. forward-word (M-f, M-F) Move forward to end of current word. Word boundary and cursor behavior modified by vimode. history-search-backward (M-p, M-P) Searches backwards through the history list for a command beginning with the current contents of the input buffer up to the cursor and copies it into the input buffer. The search string may be a glob-pattern (see Filename substitution) containing `*', `?', `[]' or `{}'. up-history and down-history will proceed from the appropriate point in the history list. Emacs mode only. See also history-search-forward and i-search- back. history-search-forward (M-n, M-N) Like history-search-backward, but searches forward. i-search-back (not bound) Searches backward like history-search-backward, copies the first match into the input buffer with the cursor positioned at the end of the pattern, and prompts with `bck: ' and the first match. Additional characters may be typed to extend the search, i-search-back may be typed to continue searching with the same pattern, wrapping around the history list if necessary, (i-search-back must be bound to a single character for this to work) or one of the following special characters may be typed: ^W Appends the rest of the word under the cursor to the search pattern. delete (or any character bound to backward-delete-char) Undoes the effect of the last character typed and deletes a character from the search pattern if appropriate. ^G If the previous search was successful, aborts the entire search. If not, goes back to the last successful search. escape Ends the search, leaving the current line in the input buffer. Any other character not bound to self-insert-command terminates the search, leaving the current line in the input buffer, and is then interpreted as normal input. In particular, a carriage return causes the current line to be executed. See also i- search-fwd and history-search-backward. Word boundary behavior modified by vimode. i-search-fwd (not bound) Like i-search-back, but searches forward. Word boundary behavior modified by vimode. insert-last-word (M-_) Inserts the last word of the previous input line (`!$') into the input buffer. See also copy-prev-word. list-choices (M-^D) Lists completion possibilities as described under Completion and listing. See also delete-char-or-list-or-eof and list- choices-raw. list-choices-raw (^X-^D) Like list-choices, but ignores user-defined completions. list-glob (^X-g, ^X-G) Lists (via the ls-F builtin) matches to the glob-pattern (see Filename substitution) to the left of the cursor. list-or-eof (not bound) Does list-choices or end-of-file on an empty line. See also delete-char-or-list-or-eof. magic-space (not bound) Expands history substitutions in the current line, like expand- history, and inserts a space. magic-space is designed to be bound to the space bar, but is not bound by default. normalize-command (^X-?) Searches for the current word in PATH and, if it is found, replaces it with the full path to the executable. Special characters are quoted. Aliases are expanded and quoted but commands within aliases are not. This command is useful with commands that take commands as arguments, e.g., `dbx' and `sh -x'. normalize-path (^X-n, ^X-N) Expands the current word as described under the `expand' setting of the symlinks shell variable. overwrite-mode (unbound) Toggles between input and overwrite modes. run-fg-editor (M-^Z) Saves the current input line and looks for a stopped job where the file name portion of its first word is found in the editors shell variable. If editors is not set, then the file name portion of the EDITOR environment variable (`ed' if unset) and the VISUAL environment variable (`vi' if unset) will be used. If such a job is found, it is restarted as if `fg %job' had been typed. This is used to toggle back and forth between an editor and the shell easily. Some people bind this command to `^Z' so they can do this even more easily. run-help (M-h, M-H) Searches for documentation on the current command, using the same notion of `current command' as the completion routines, and prints it. There is no way to use a pager; run-help is designed for short help files. If the special alias helpcommand is defined, it is run with the command name as a sole argument. Else, documentation should be in a file named command.help, command.1, command.6, command.8 or command, which should be in one of the directories listed in the HPATH environment variable. If there is more than one help file only the first is printed. self-insert-command (text characters) In insert mode (the default), inserts the typed character into the input line after the character under the cursor. In overwrite mode, replaces the character under the cursor with the typed character. The input mode is normally preserved between lines, but the inputmode shell variable can be set to `insert' or `overwrite' to put the editor in that mode at the beginning of each line. See also overwrite-mode. sequence-lead-in (arrow prefix, meta prefix, ^X) Indicates that the following characters are part of a multi-key sequence. Binding a command to a multi-key sequence really creates two bindings: the first character to sequence-lead-in and the whole sequence to the command. All sequences beginning with a character bound to sequence-lead-in are effectively bound to undefined-key unless bound to another command. spell-line (M-$) Attempts to correct the spelling of each word in the input buffer, like spell-word, but ignores words whose first character is one of `-', `!', `^' or `%', or which contain `\', `*' or `?', to avoid problems with switches, substitutions and the like. See Spelling correction. spell-word (M-s, M-S) Attempts to correct the spelling of the current word as described under Spelling correction. Checks each component of a word which appears to be a pathname. toggle-literal-history (M-r, M-R) Expands or `unexpands' history substitutions in the input buffer. See also expand-history and the autoexpand shell variable. undefined-key (any unbound key) Beeps. up-history (up-arrow, ^P) Copies the previous entry in the history list into the input buffer. If histlit is set, uses the literal form of the entry. May be repeated to step up through the history list, stopping at the top. upcase-word (M-u, M-U) Uppercase the characters from cursor to end of current word. Word boundary behavior modified by vimode. vi-beginning-of-next-word (not bound) Vi goto the beginning of next word. Word boundary and cursor behavior modified by vimode. vi-eword (not bound) Vi move to the end of the current word. Word boundary behavior modified by vimode. vi-search-back (?) Prompts with `?' for a search string (which may be a glob- pattern, as with history-search-backward), searches for it and copies it into the input buffer. The bell rings if no match is found. Hitting return ends the search and leaves the last match in the input buffer. Hitting escape ends the search and executes the match. vi mode only. vi-search-fwd (/) Like vi-search-back, but searches forward. which-command (M-?) Does a which (see the description of the builtin command) on the first word of the input buffer. yank-pop (M-y) When executed immediately after a yank or another yank-pop, replaces the yanked string with the next previous string from the killring. This also has the effect of rotating the killring, such that this string will be considered the most recently killed by a later yank command. Repeating yank-pop will cycle through the killring any number of times. Lexical structure The shell splits input lines into words at blanks and tabs. The special characters `&', `|', `;', `<', `>', `(', and `)' and the doubled characters `&&', `||', `<<' and `>>' are always separate words, whether or not they are surrounded by whitespace. When the shell's input is not a terminal, the character `#' is taken to begin a comment. Each `#' and the rest of the input line on which it appears is discarded before further parsing. A special character (including a blank or tab) may be prevented from having its special meaning, and possibly made part of another word, by preceding it with a backslash (`\') or enclosing it in single (`''), double (`"') or backward (``') quotes. When not otherwise quoted a newline preceded by a `\' is equivalent to a blank, but inside quotes this sequence results in a newline. Furthermore, all Substitutions (see below) except History substitution can be prevented by enclosing the strings (or parts of strings) in which they appear with single quotes or by quoting the crucial character(s) (e.g., `$' or ``' for Variable substitution or Command substitution respectively) with `\'. (Alias substitution is no exception: quoting in any way any character of a word for which an alias has been defined prevents substitution of the alias. The usual way of quoting an alias is to precede it with a backslash.) History substitution is prevented by backslashes but not by single quotes. Strings quoted with double or backward quotes undergo Variable substitution and Command substitution, but other substitutions are prevented. Text inside single or double quotes becomes a single word (or part of one). Metacharacters in these strings, including blanks and tabs, do not form separate words. Only in one special case (see Command substitution below) can a double-quoted string yield parts of more than one word; single-quoted strings never do. Backward quotes are special: they signal Command substitution (q.v.), which may result in more than one word. Quoting complex strings, particularly strings which themselves contain quoting characters, can be confusing. Remember that quotes need not be used as they are in human writing! It may be easier to quote not an entire string, but only those parts of the string which need quoting, using different types of quoting to do so if appropriate. The backslash_quote shell variable (q.v.) can be set to make backslashes always quote `\', `'', and `"'. (+) This may make complex quoting tasks easier, but it can cause syntax errors in csh(1) scripts. Substitutions We now describe the various transformations the shell performs on the input in the order in which they occur. We note in passing the data structures involved and the commands and variables which affect them. Remember that substitutions can be prevented by quoting as described under Lexical structure. History substitution Each command, or ``event'', input from the terminal is saved in the history list. The previous command is always saved, and the history shell variable can be set to a number to save that many commands. The histdup shell variable can be set to not save duplicate events or consecutive duplicate events. Saved commands are numbered sequentially from 1 and stamped with the time. It is not usually necessary to use event numbers, but the current event number can be made part of the prompt by placing an `!' in the prompt shell variable. The shell actually saves history in expanded and literal (unexpanded) forms. If the histlit shell variable is set, commands that display and store history use the literal form. The history builtin command can print, store in a file, restore and clear the history list at any time, and the savehist and histfile shell variables can be set to store the history list automatically on logout and restore it on login. History substitutions introduce words from the history list into the input stream, making it easy to repeat commands, repeat arguments of a previous command in the current command, or fix spelling mistakes in the previous command with little typing and a high degree of confidence. History substitutions begin with the character `!'. They may begin anywhere in the input stream, but they do not nest. The `!' may be preceded by a `\' to prevent its special meaning; for convenience, a `!' is passed unchanged when it is followed by a blank, tab, newline, `=' or `('. History substitutions also occur when an input line begins with `^'. This special abbreviation will be described later. The characters used to signal history substitution (`!' and `^') can be changed by setting the histchars shell variable. Any input line which contains a history substitution is printed before it is executed. A history substitution may have an ``event specification'', which indicates the event from which words are to be taken, a ``word designator'', which selects particular words from the chosen event, and/or a ``modifier'', which manipulates the selected words. An event specification can be n A number, referring to a particular event -n An offset, referring to the event n before the current event # The current event. This should be used carefully in csh(1), where there is no check for recursion. tcsh allows 10 levels of recursion. (+) ! The previous event (equivalent to `-1') s The most recent event whose first word begins with the string s ?s? The most recent event which contains the string s. The second `?' can be omitted if it is immediately followed by a newline. For example, consider this bit of someone's history list: 9 8:30 nroff -man wumpus.man 10 8:31 cp wumpus.man wumpus.man.old 11 8:36 vi wumpus.man 12 8:37 diff wumpus.man.old wumpus.man The commands are shown with their event numbers and time stamps. The current event, which we haven't typed in yet, is event 13. `!11' and `!-2' refer to event 11. `!!' refers to the previous event, 12. `!!' can be abbreviated `!' if it is followed by `:' (`:' is described below). `!n' refers to event 9, which begins with `n'. `!?old?' also refers to event 12, which contains `old'. Without word designators or modifiers history references simply expand to the entire event, so we might type `!cp' to redo the copy command or `!!|more' if the `diff' output scrolled off the top of the screen. History references may be insulated from the surrounding text with braces if necessary. For example, `!vdoc' would look for a command beginning with `vdoc', and, in this example, not find one, but `!{v}doc' would expand unambiguously to `vi wumpus.mandoc'. Even in braces, history substitutions do not nest. (+) While csh(1) expands, for example, `!3d' to event 3 with the letter `d' appended to it, tcsh expands it to the last event beginning with `3d'; only completely numeric arguments are treated as event numbers. This makes it possible to recall events beginning with numbers. To expand `!3d' as in csh(1) say `!{3}d'. To select words from an event we can follow the event specification by a `:' and a designator for the desired words. The words of an input line are numbered from 0, the first (usually command) word being 0, the second word (first argument) being 1, etc. The basic word designators are: 0 The first (command) word n The nth argument ^ The first argument, equivalent to `1' $ The last argument % The word matched by an ?s? search x-y A range of words -y Equivalent to `0-y' * Equivalent to `^-$', but returns nothing if the event contains only 1 word x* Equivalent to `x-$' x- Equivalent to `x*', but omitting the last word (`$') Selected words are inserted into the command line separated by single blanks. For example, the `diff' command in the previous example might have been typed as `diff !!:1.old !!:1' (using `:1' to select the first argument from the previous event) or `diff !-2:2 !-2:1' to select and swap the arguments from the `cp' command. If we didn't care about the order of the `diff' we might have said `diff !-2:1-2' or simply `diff !-2:*'. The `cp' command might have been written `cp wumpus.man !#:1.old', using `#' to refer to the current event. `!n:- hurkle.man' would reuse the first two words from the `nroff' command to say `nroff -man hurkle.man'. The `:' separating the event specification from the word designator can be omitted if the argument selector begins with a `^', `$', `*', `%' or `-'. For example, our `diff' command might have been `diff !!^.old !!^' or, equivalently, `diff !!$.old !!$'. However, if `!!' is abbreviated `!', an argument selector beginning with `-' will be interpreted as an event specification. A history reference may have a word designator but no event specification. It then references the previous command. Continuing our `diff' example, we could have said simply `diff !^.old !^' or, to get the arguments in the opposite order, just `diff !*'. The word or words in a history reference can be edited, or ``modified'', by following it with one or more modifiers, each preceded by a `:': h Remove a trailing pathname component, leaving the head. t Remove all leading pathname components, leaving the tail. r Remove a filename extension `.xxx', leaving the root name. e Remove all but the extension. u Uppercase the first lowercase letter. l Lowercase the first uppercase letter. s/l/r/ Substitute l for r. l is simply a string like r, not a regular expression as in the eponymous ed(1) command. Any character may be used as the delimiter in place of `/'; a `\' can be used to quote the delimiter inside l and r. The character `&' in the r is replaced by l; `\' also quotes `&'. If l is empty (``''), the l from a previous substitution or the s from a previous search or event number in event specification is used. The trailing delimiter may be omitted if it is immediately followed by a newline. & Repeat the previous substitution. g Apply the following modifier once to each word. a (+) Apply the following modifier as many times as possible to a single word. `a' and `g' can be used together to apply a modifier globally. With the `s' modifier, only the patterns contained in the original word are substituted, not patterns that contain any substitution result. p Print the new command line but do not execute it. q Quote the substituted words, preventing further substitutions. x Like q, but break into words at blanks, tabs and newlines. Modifiers are applied to only the first modifiable word (unless `g' is used). It is an error for no word to be modifiable. For example, the `diff' command might have been written as `diff wumpus.man.old !#^:r', using `:r' to remove `.old' from the first argument on the same line (`!#^'). We could say `echo hello out there', then `echo !*:u' to capitalize `hello', `echo !*:au' to say it out loud, or `echo !*:agu' to really shout. We might follow `mail -s "I forgot my password" rot' with `!:s/rot/root' to correct the spelling of `root' (but see Spelling correction for a different approach). There is a special abbreviation for substitutions. `^', when it is the first character on an input line, is equivalent to `!:s^'. Thus we might have said `^rot^root' to make the spelling correction in the previous example. This is the only history substitution which does not explicitly begin with `!'. (+) In csh as such, only one modifier may be applied to each history or variable expansion. In tcsh, more than one may be used, for example % mv wumpus.man /usr/man/man1/wumpus.1 % man !$:t:r man wumpus In csh, the result would be `wumpus.1:r'. A substitution followed by a colon may need to be insulated from it with braces: > mv a.out /usr/games/wumpus > setenv PATH !$:h:$PATH Bad ! modifier: $. > setenv PATH !{-2$:h}:$PATH setenv PATH /usr/games:/bin:/usr/bin:. The first attempt would succeed in csh but fails in tcsh, because tcsh expects another modifier after the second colon rather than `$'. Finally, history can be accessed through the editor as well as through the substitutions just described. The up- and down-history, history- search-backward and -forward, i-search-back and -fwd, vi-search-back and -fwd, copy-prev-word and insert-last-word editor commands search for events in the history list and copy them into the input buffer. The toggle-literal-history editor command switches between the expanded and literal forms of history lines in the input buffer. expand-history and expand-line expand history substitutions in the current word and in the entire input buffer respectively. Alias substitution The shell maintains a list of aliases which can be set, unset and printed by the alias and unalias commands. After a command line is parsed into simple commands (see Commands) the first word of each command, left-to-right, is checked to see if it has an alias. If so, the first word is replaced by the alias. If the alias contains a history reference, it undergoes History substitution (q.v.) as though the original command were the previous input line. If the alias does not contain a history reference, the argument list is left untouched. Thus if the alias for `ls' were `ls -l' the command `ls /usr' would become `ls -l /usr', the argument list here being undisturbed. If the alias for `lookup' were `grep !^ /etc/passwd' then `lookup bill' would become `grep bill /etc/passwd'. Aliases can be used to introduce parser metasyntax. For example, `alias print 'pr \!* | lpr'' defines a ``command'' (`print') which pr(1)s its arguments to the line printer. Alias substitution is repeated until the first word of the command has no alias. If an alias substitution does not change the first word (as in the previous example) it is flagged to prevent a loop. Other loops are detected and cause an error. Some aliases are referred to by the shell; see Special aliases. Variable substitution The shell maintains a list of variables, each of which has as value a list of zero or more words. The values of shell variables can be displayed and changed with the set and unset commands. The system maintains its own list of ``environment'' variables. These can be displayed and changed with printenv, setenv and unsetenv. (+) Variables may be made read-only with `set -r' (q.v.). Read-only variables may not be modified or unset; attempting to do so will cause an error. Once made read-only, a variable cannot be made writable, so `set -r' should be used with caution. Environment variables cannot be made read-only. Some variables are set by the shell or referred to by it. For instance, the argv variable is an image of the shell's argument list, and words of this variable's value are referred to in special ways. Some of the variables referred to by the shell are toggles; the shell does not care what their value is, only whether they are set or not. For instance, the verbose variable is a toggle which causes command input to be echoed. The -v command line option sets this variable. Special shell variables lists all variables which are referred to by the shell. Other operations treat variables numerically. The `@' command permits numeric calculations to be performed and the result assigned to a variable. Variable values are, however, always represented as (zero or more) strings. For the purposes of numeric operations, the null string is considered to be zero, and the second and subsequent words of multi- word values are ignored. After the input line is aliased and parsed, and before each command is executed, variable substitution is performed keyed by `$' characters. This expansion can be prevented by preceding the `$' with a `\' except within `"'s where it always occurs, and within `''s where it never occurs. Strings quoted by ``' are interpreted later (see Command substitution below) so `$' substitution does not occur there until later, if at all. A `$' is passed unchanged if followed by a blank, tab, or end-of-line. Input/output redirections are recognized before variable expansion, and are variable expanded separately. Otherwise, the command name and entire argument list are expanded together. It is thus possible for the first (command) word (to this point) to generate more than one word, the first of which becomes the command name, and the rest of which become arguments. Unless enclosed in `"' or given the `:q' modifier the results of variable substitution may eventually be command and filename substituted. Within `"', a variable whose value consists of multiple words expands to a (portion of a) single word, with the words of the variable's value separated by blanks. When the `:q' modifier is applied to a substitution the variable will expand to multiple words with each word separated by a blank and quoted to prevent later command or filename substitution. The following metasequences are provided for introducing variable values into the shell input. Except as noted, it is an error to reference a variable which is not set. $name ${name} Substitutes the words of the value of variable name, each separated by a blank. Braces insulate name from following characters which would otherwise be part of it. Shell variables have names consisting of letters and digits starting with a letter. The underscore character is considered a letter. If name is not a shell variable, but is set in the environment, then that value is returned (but some of the other forms given below are not available in this case). $name[selector] ${name[selector]} Substitutes only the selected words from the value of name. The selector is subjected to `$' substitution and may consist of a single number or two numbers separated by a `-'. The first word of a variable's value is numbered `1'. If the first number of a range is omitted it defaults to `1'. If the last member of a range is omitted it defaults to `$#name'. The selector `*' selects all words. It is not an error for a range to be empty if the second argument is omitted or in range. $0 Substitutes the name of the file from which command input is being read. An error occurs if the name is not known. $number ${number} Equivalent to `$argv[number]'. $* Equivalent to `$argv', which is equivalent to `$argv[*]'. The `:' modifiers described under History substitution, except for `:p', can be applied to the substitutions above. More than one may be used. (+) Braces may be needed to insulate a variable substitution from a literal colon just as with History substitution (q.v.); any modifiers must appear within the braces. The following substitutions can not be modified with `:' modifiers. $?name ${?name} Substitutes the string `1' if name is set, `0' if it is not. $?0 Substitutes `1' if the current input filename is known, `0' if it is not. Always `0' in interactive shells. $#name ${#name} Substitutes the number of words in name. $# Equivalent to `$#argv'. (+) $%name ${%name} Substitutes the number of characters in name. (+) $%number ${%number} Substitutes the number of characters in $argv[number]. (+) $? Equivalent to `$status'. (+) $$ Substitutes the (decimal) process number of the (parent) shell. $! Substitutes the (decimal) process number of the last background process started by this shell. (+) $_ Substitutes the command line of the last command executed. (+) $< Substitutes a line from the standard input, with no further interpretation thereafter. It can be used to read from the keyboard in a shell script. (+) While csh always quotes $<, as if it were equivalent to `$<:q', tcsh does not. Furthermore, when tcsh is waiting for a line to be typed the user may type an interrupt to interrupt the sequence into which the line is to be substituted, but csh does not allow this. The editor command expand-variables, normally bound to `^X-$', can be used to interactively expand individual variables. Command, filename and directory stack substitution The remaining substitutions are applied selectively to the arguments of builtin commands. This means that portions of expressions which are not evaluated are not subjected to these expansions. For commands which are not internal to the shell, the command name is substituted separately from the argument list. This occurs very late, after input- output redirection is performed, and in a child of the main shell. Command substitution Command substitution is indicated by a command enclosed in ``'. The output from such a command is broken into separate words at blanks, tabs and newlines, and null words are discarded. The output is variable and command substituted and put in place of the original string. Command substitutions inside double quotes (`"') retain blanks and tabs; only newlines force new words. The single final newline does not force a new word in any case. It is thus possible for a command substitution to yield only part of a word, even if the command outputs a complete line. By default, the shell since version 6.12 replaces all newline and carriage return characters in the command by spaces. If this is switched off by unsetting csubstnonl, newlines separate commands as usual. Filename substitution If a word contains any of the characters `*', `?', `[' or `{' or begins with the character `~' it is a candidate for filename substitution, also known as ``globbing''. This word is then regarded as a pattern (``glob-pattern''), and replaced with an alphabetically sorted list of file names which match the pattern. In matching filenames, the character `.' at the beginning of a filename or immediately following a `/', as well as the character `/' must be matched explicitly (unless either globdot or globstar or both are set(+)). The character `*' matches any string of characters, including the null string. The character `?' matches any single character. The sequence `[...]' matches any one of the characters enclosed. Within `[...]', a pair of characters separated by `-' matches any character lexically between the two. (+) Some glob-patterns can be negated: The sequence `[^...]' matches any single character not specified by the characters and/or ranges of characters in the braces. An entire glob-pattern can also be negated with `^': > echo * bang crash crunch ouch > echo ^cr* bang ouch Glob-patterns which do not use `?', `*', or `[]' or which use `{}' or `~' (below) are not negated correctly. The metanotation `a{b,c,d}e' is a shorthand for `abe ace ade'. Left- to-right order is preserved: `/usr/source/s1/{oldls,ls}.c' expands to `/usr/source/s1/oldls.c /usr/source/s1/ls.c'. The results of matches are sorted separately at a low level to preserve this order: `../{memo,*box}' might expand to `../memo ../box ../mbox'. (Note that `memo' was not sorted with the results of matching `*box'.) It is not an error when this construct expands to files which do not exist, but it is possible to get an error from a command to which the expanded list is passed. This construct may be nested. As a special case the words `{', `}' and `{}' are passed undisturbed. The character `~' at the beginning of a filename refers to home directories. Standing alone, i.e., `~', it expands to the invoker's home directory as reflected in the value of the home shell variable. When followed by a name consisting of letters, digits and `-' characters the shell searches for a user with that name and substitutes their home directory; thus `~ken' might expand to `/usr/ken' and `~ken/chmach' to `/usr/ken/chmach'. If the character `~' is followed by a character other than a letter or `/' or appears elsewhere than at the beginning of a word, it is left undisturbed. A command like `setenv MANPATH /usr/man:/usr/local/man:~/lib/man' does not, therefore, do home directory substitution as one might hope. It is an error for a glob-pattern containing `*', `?', `[' or `~', with or without `^', not to match any files. However, only one pattern in a list of glob-patterns must match a file (so that, e.g., `rm *.a *.c *.o' would fail only if there were no files in the current directory ending in `.a', `.c', or `.o'), and if the nonomatch shell variable is set a pattern (or list of patterns) which matches nothing is left unchanged rather than causing an error. The globstar shell variable can be set to allow `**' or `***' as a file glob pattern that matches any string of characters including `/', recursively traversing any existing sub-directories. For example, `ls **.c' will list all the .c files in the current directory tree. If used by itself, it will match zero or more sub-directories (e.g. `ls /usr/include/**/time.h' will list any file named `time.h' in the /usr/include directory tree; `ls /usr/include/**time.h' will match any file in the /usr/include directory tree ending in `time.h'; and `ls /usr/include/**time**.h' will match any .h file with `time' either in a subdirectory name or in the filename itself). To prevent problems with recursion, the `**' glob-pattern will not descend into a symbolic link containing a directory. To override this, use `***' (+) The noglob shell variable can be set to prevent filename substitution, and the expand-glob editor command, normally bound to `^X-*', can be used to interactively expand individual filename substitutions. Directory stack substitution (+) The directory stack is a list of directories, numbered from zero, used by the pushd, popd and dirs builtin commands (q.v.). dirs can print, store in a file, restore and clear the directory stack at any time, and the savedirs and dirsfile shell variables can be set to store the directory stack automatically on logout and restore it on login. The dirstack shell variable can be examined to see the directory stack and set to put arbitrary directories into the directory stack. The character `=' followed by one or more digits expands to an entry in the directory stack. The special case `=-' expands to the last directory in the stack. For example, > dirs -v 0 /usr/bin 1 /usr/spool/uucp 2 /usr/accts/sys > echo =1 /usr/spool/uucp > echo =0/calendar /usr/bin/calendar > echo =- /usr/accts/sys The noglob and nonomatch shell variables and the expand-glob editor command apply to directory stack as well as filename substitutions. Other substitutions (+) There are several more transformations involving filenames, not strictly related to the above but mentioned here for completeness. Any filename may be expanded to a full path when the symlinks variable (q.v.) is set to `expand'. Quoting prevents this expansion, and the normalize-path editor command does it on demand. The normalize-command editor command expands commands in PATH into full paths on demand. Finally, cd and pushd interpret `-' as the old working directory (equivalent to the shell variable owd). This is not a substitution at all, but an abbreviation recognized by only those commands. Nonetheless, it too can be prevented by quoting. Commands The next three sections describe how the shell executes commands and deals with their input and output. Simple commands, pipelines and sequences A simple command is a sequence of words, the first of which specifies the command to be executed. A series of simple commands joined by `|' characters forms a pipeline. The output of each command in a pipeline is connected to the input of the next. Simple commands and pipelines may be joined into sequences with `;', and will be executed sequentially. Commands and pipelines can also be joined into sequences with `||' or `&&', indicating, as in the C language, that the second is to be executed only if the first fails or succeeds respectively. A simple command, pipeline or sequence may be placed in parentheses, `()', to form a simple command, which may in turn be a component of a pipeline or sequence. A command, pipeline or sequence can be executed without waiting for it to terminate by following it with an `&'. Builtin and non-builtin command execution Builtin commands are executed within the shell. If any component of a pipeline except the last is a builtin command, the pipeline is executed in a subshell. Parenthesized commands are always executed in a subshell. (cd; pwd); pwd thus prints the home directory, leaving you where you were (printing this after the home directory), while cd; pwd leaves you in the home directory. Parenthesized commands are most often used to prevent cd from affecting the current shell. When a command to be executed is found not to be a builtin command the shell attempts to execute the command via execve(2). Each word in the variable path names a directory in which the shell will look for the command. If the shell is not given a -f option, the shell hashes the names in these directories into an internal table so that it will try an execve(2) in only a directory where there is a possibility that the command resides there. This greatly speeds command location when a large number of directories are present in the search path. This hashing mechanism is not used: 1. If hashing is turned explicitly off via unhash. 2. If the shell was given a -f argument. 3. For each directory component of path which does not begin with a `/'. 4. If the command contains a `/'. In the above four cases the shell concatenates each component of the path vector with the given command name to form a path name of a file which it then attempts to execute it. If execution is successful, the search stops. If the file has execute permissions but is not an executable to the system (i.e., it is neither an executable binary nor a script that specifies its interpreter), then it is assumed to be a file containing shell commands and a new shell is spawned to read it. The shell special alias may be set to specify an interpreter other than the shell itself. On systems which do not understand the `#!' script interpreter convention the shell may be compiled to emulate it; see the version shell variable. If so, the shell checks the first line of the file to see if it is of the form `#!interpreter arg ...'. If it is, the shell starts interpreter with the given args and feeds the file to it on standard input. Input/output The standard input and standard output of a command may be redirected with the following syntax: < name Open file name (which is first variable, command and filename expanded) as the standard input. << word Read the shell input up to a line which is identical to word. word is not subjected to variable, filename or command substitution, and each input line is compared to word before any substitutions are done on this input line. Unless a quoting `\', `"', `' or ``' appears in word variable and command substitution is performed on the intervening lines, allowing `\' to quote `$', `\' and ``'. Commands which are substituted have all blanks, tabs, and newlines preserved, except for the final newline which is dropped. The resultant text is placed in an anonymous temporary file which is given to the command as standard input. > name >! name >& name >&! name The file name is used as standard output. If the file does not exist then it is created; if the file exists, it is truncated, its previous contents being lost. If the shell variable noclobber is set, then the file must not exist or be a character special file (e.g., a terminal or `/dev/null') or an error results. This helps prevent accidental destruction of files. In this case the `!' forms can be used to suppress this check. If notempty is given in noclobber, `>' is allowed on empty files; if ask is set, an interacive confirmation is presented, rather than an error. The forms involving `&' route the diagnostic output into the specified file as well as the standard output. name is expanded in the same way as `<' input filenames are. >> name >>& name >>! name >>&! name Like `>', but appends output to the end of name. If the shell variable noclobber is set, then it is an error for the file not to exist, unless one of the `!' forms is given. A command receives the environment in which the shell was invoked as modified by the input-output parameters and the presence of the command in a pipeline. Thus, unlike some previous shells, commands run from a file of shell commands have no access to the text of the commands by default; rather they receive the original standard input of the shell. The `<<' mechanism should be used to present inline data. This permits shell command scripts to function as components of pipelines and allows the shell to block read its input. Note that the default standard input for a command run detached is not the empty file /dev/null, but the original standard input of the shell. If this is a terminal and if the process attempts to read from the terminal, then the process will block and the user will be notified (see Jobs). Diagnostic output may be directed through a pipe with the standard output. Simply use the form `|&' rather than just `|'. The shell cannot presently redirect diagnostic output without also redirecting standard output, but `(command > output-file) >& error- file' is often an acceptable workaround. Either output-file or error- file may be `/dev/tty' to send output to the terminal. Features Having described how the shell accepts, parses and executes command lines, we now turn to a variety of its useful features. Control flow The shell contains a number of commands which can be used to regulate the flow of control in command files (shell scripts) and (in limited but useful ways) from terminal input. These commands all operate by forcing the shell to reread or skip in its input and, due to the implementation, restrict the placement of some of the commands. The foreach, switch, and while statements, as well as the if-then-else form of the if statement, require that the major keywords appear in a single simple command on an input line as shown below. If the shell's input is not seekable, the shell buffers up input whenever a loop is being read and performs seeks in this internal buffer to accomplish the rereading implied by the loop. (To the extent that this allows, backward gotos will succeed on non-seekable inputs.) Expressions The if, while and exit builtin commands use expressions with a common syntax. The expressions can include any of the operators described in the next three sections. Note that the @ builtin command (q.v.) has its own separate syntax. Logical, arithmetical and comparison operators These operators are similar to those of C and have the same precedence. They include || && | ^ & == != =~ !~ <= >= < > << >> + - * / % ! ~ ( ) Here the precedence increases to the right, `==' `!=' `=~' and `!~', `<=' `>=' `<' and `>', `<<' and `>>', `+' and `-', `*' `/' and `%' being, in groups, at the same level. The `==' `!=' `=~' and `!~' operators compare their arguments as strings; all others operate on numbers. The operators `=~' and `!~' are like `!=' and `==' except that the right hand side is a glob-pattern (see Filename substitution) against which the left hand operand is matched. This reduces the need for use of the switch builtin command in shell scripts when all that is really needed is pattern matching. Null or missing arguments are considered `0'. The results of all expressions are strings, which represent decimal numbers. It is important to note that no two components of an expression can appear in the same word; except when adjacent to components of expressions which are syntactically significant to the parser (`&' `|' `<' `>' `(' `)') they should be surrounded by spaces. Command exit status Commands can be executed in expressions and their exit status returned by enclosing them in braces (`{}'). Remember that the braces should be separated from the words of the command by spaces. Command executions succeed, returning true, i.e., `1', if the command exits with status 0, otherwise they fail, returning false, i.e., `0'. If more detailed status information is required then the command should be executed outside of an expression and the status shell variable examined. File inquiry operators Some of these operators perform true/false tests on files and related objects. They are of the form -op file, where op is one of r Read access w Write access x Execute access X Executable in the path or shell builtin, e.g., `-X ls' and `-X ls-F' are generally true, but `-X /bin/ls' is not (+) e Existence o Ownership z Zero size s Non-zero size (+) f Plain file d Directory l Symbolic link (+) * b Block special file (+) c Character special file (+) p Named pipe (fifo) (+) * S Socket special file (+) * u Set-user-ID bit is set (+) g Set-group-ID bit is set (+) k Sticky bit is set (+) t file (which must be a digit) is an open file descriptor for a terminal device (+) R Has been migrated (Convex only) (+) L Applies subsequent operators in a multiple-operator test to a symbolic link rather than to the file to which the link points (+) * file is command and filename expanded and then tested to see if it has the specified relationship to the real user. If file does not exist or is inaccessible or, for the operators indicated by `*', if the specified file type does not exist on the current system, then all inquiries return false, i.e., `0'. These operators may be combined for conciseness: `-xy file' is equivalent to `-x file && -y file'. (+) For example, `-fx' is true (returns `1') for plain executable files, but not for directories. L may be used in a multiple-operator test to apply subsequent operators to a symbolic link rather than to the file to which the link points. For example, `-lLo' is true for links owned by the invoking user. Lr, Lw and Lx are always true for links and false for non-links. L has a different meaning when it is the last operator in a multiple-operator test; see below. It is possible but not useful, and sometimes misleading, to combine operators which expect file to be a file with operators which do not (e.g., X and t). Following L with a non-file operator can lead to particularly strange results. Other operators return other information, i.e., not just `0' or `1'. (+) They have the same format as before; op may be one of A Last file access time, as the number of seconds since the epoch A: Like A, but in timestamp format, e.g., `Fri May 14 16:36:10 1993' M Last file modification time M: Like M, but in timestamp format C Last inode modification time C: Like C, but in timestamp format D Device number I Inode number F Composite file identifier, in the form device:inode L The name of the file pointed to by a symbolic link N Number of (hard) links P Permissions, in octal, without leading zero P: Like P, with leading zero Pmode Equivalent to `-P file & mode', e.g., `-P22 file' returns `22' if file is writable by group and other, `20' if by group only, and `0' if by neither Pmode: Like Pmode, with leading zero U Numeric userid U: Username, or the numeric userid if the username is unknown G Numeric groupid G: Groupname, or the numeric groupid if the groupname is unknown Z Size, in bytes Only one of these operators may appear in a multiple-operator test, and it must be the last. Note that L has a different meaning at the end of and elsewhere in a multiple-operator test. Because `0' is a valid return value for many of these operators, they do not return `0' when they fail: most return `-1', and F returns `:'. If the shell is compiled with POSIX defined (see the version shell variable), the result of a file inquiry is based on the permission bits of the file and not on the result of the access(2) system call. For example, if one tests a file with -w whose permissions would ordinarily allow writing but which is on a file system mounted read-only, the test will succeed in a POSIX shell but fail in a non-POSIX shell. File inquiry operators can also be evaluated with the filetest builtin command (q.v.) (+). Jobs The 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 (top-level) process, whose process id was 1234. If you are running a job and wish to do something else you may hit the suspend key (usually `^Z'), which sends a STOP signal to the current job. The shell will then normally indicate that the job has been `Suspended' and print another prompt. If the listjobs shell variable is set, all jobs will be listed like the jobs builtin command; if it is set to `long' the listing will be in long format, like `jobs -l'. You can then manipulate the state of the suspended job. You can put it in the ``background'' with the bg command or run some other commands and eventually bring the job back into the ``foreground'' with fg. (See also the run-fg-editor editor command.) A `^Z' takes effect immediately and is like an interrupt in that pending output and unread input are discarded when it is typed. The wait builtin command causes the shell to wait for all background jobs to complete. The `^]' key sends a delayed suspend signal, which does not generate a STOP signal until a program attempts to read(2) it, to the current job. This can usefully be typed ahead when you have prepared some commands for a job which you wish to stop after it has read them. The `^Y' key performs this function in csh(1); in tcsh, `^Y' is an editing command. (+) A job being run in the background stops 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 stop when they try to produce output like they do when they try to read input. There are several ways to refer to jobs in the shell. The character `%' introduces a job name. If you wish to refer to job number 1, you can name it as `%1'. Just naming a job brings it to the foreground; thus `%1' is a synonym for `fg %1', bringing job 1 back into the foreground. Similarly, saying `%1 &' resumes job 1 in the background, just like `bg %1'. A job can also be named by an unambiguous prefix of the string typed in to start it: `%ex' would normally restart a suspended ex(1) job, if there were only one suspended job whose name began with the string `ex'. It is also possible to say `%?string' to specify a job whose text contains string, if there is only one such job. The shell maintains a notion of the current and previous jobs. In output pertaining to jobs, the current job is marked with a `+' and the previous job with a `-'. The abbreviations `%+', `%', and (by analogy with the syntax of the history mechanism) `%%' all refer to the current job, and `%-' refers to the previous job. The job control mechanism requires that the stty(1) option `new' be set on some systems. It is an artifact from a `new' implementation of the tty driver which allows generation of interrupt characters from the keyboard to tell jobs to stop. See stty(1) and the setty builtin command for details on setting options in the new tty driver. Status reporting 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, but only right before it prints a prompt. This is done so that it does not otherwise disturb your work. If, however, you set the shell variable notify, the shell will notify you immediately of changes of status in background jobs. There is also a shell command notify which marks a single process so that its status changes will be immediately reported. By default notify marks the current process; simply say `notify' after starting a background job to mark it. When you try to leave the shell while jobs are stopped, you will be warned that `There are suspended 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, and the suspended jobs will be terminated. Automatic, periodic and timed events (+) There are various ways to run commands and take other actions automatically at various times in the ``life cycle'' of the shell. They are summarized here, and described in detail under the appropriate Builtin commands, Special shell variables and Special aliases. The sched builtin command puts commands in a scheduled-event list, to be executed by the shell at a given time. The beepcmd, cwdcmd, periodic, precmd, postcmd, and jobcmd Special aliases can be set, respectively, to execute commands when the shell wants to ring the bell, when the working directory changes, every tperiod minutes, before each prompt, before each command gets executed, after each command gets executed, and when a job is started or is brought into the foreground. The autologout shell variable can be set to log out or lock the shell after a given number of minutes of inactivity. The mail shell variable can be set to check for new mail periodically. The printexitvalue shell variable can be set to print the exit status of commands which exit with a status other than zero. The rmstar shell variable can be set to ask the user, when `rm *' is typed, if that is really what was meant. The time shell variable can be set to execute the time builtin command after the completion of any process that takes more than a given number of CPU seconds. The watch and who shell variables can be set to report when selected users log in or out, and the log builtin command reports on those users at any time. Native Language System support (+) The shell is eight bit clean (if so compiled; see the version shell variable) and thus supports character sets needing this capability. NLS support differs depending on whether or not the shell was compiled to use the system's NLS (again, see version). In either case, 7-bit ASCII is the default character code (e.g., the classification of which characters are printable) and sorting, and changing the LANG or LC_CTYPE environment variables causes a check for possible changes in these respects. When using the system's NLS, the setlocale(3) function is called to determine appropriate character code/classification and sorting (e.g., a 'en_CA.UTF-8' would yield "UTF-8" as a character code). This function typically examines the LANG and LC_CTYPE environment variables; refer to the system documentation for further details. When not using the system's NLS, the shell simulates it by assuming that the ISO 8859-1 character set is used whenever either of the LANG and LC_CTYPE variables are set, regardless of their values. Sorting is not affected for the simulated NLS. In addition, with both real and simulated NLS, all printable characters in the range \200-\377, i.e., those that have M-char bindings, are automatically rebound to self-insert-command. The corresponding binding for the escape-char sequence, if any, is left alone. These characters are not rebound if the NOREBIND environment variable is set. This may be useful for the simulated NLS or a primitive real NLS which assumes full ISO 8859-1. Otherwise, all M-char bindings in the range \240-\377 are effectively undone. Explicitly rebinding the relevant keys with bindkey is of course still possible. Unknown characters (i.e., those that are neither printable nor control characters) are printed in the format \nnn. If the tty is not in 8 bit mode, other 8 bit characters are printed by converting them to ASCII and using standout mode. The shell never changes the 7/8 bit mode of the tty and tracks user-initiated changes of 7/8 bit mode. NLS users (or, for that matter, those who want to use a meta key) may need to explicitly set the tty in 8 bit mode through the appropriate stty(1) command in, e.g., the ~/.login file. OS variant support (+) A number of new builtin commands are provided to support features in particular operating systems. All are described in detail in the Builtin commands section. On systems that support TCF (aix-ibm370, aix-ps2), getspath and setspath get and set the system execution path, getxvers and setxvers get and set the experimental version prefix and migrate migrates processes between sites. The jobs builtin prints the site on which each job is executing. Under BS2000, bs2cmd executes commands of the underlying BS2000/OSD operating system. Under Domain/OS, inlib adds shared libraries to the current environment, rootnode changes the rootnode and ver changes the systype. Under Mach, setpath is equivalent to Mach's setpath(1). Under Masscomp/RTU and Harris CX/UX, universe sets the universe. Under Harris CX/UX, ucb or att runs a command under the specified universe. Under Convex/OS, warp prints or sets the universe. The VENDOR, OSTYPE and MACHTYPE environment variables indicate respectively the vendor, operating system and machine type (microprocessor class or machine model) of the system on which the shell thinks it is running. These are particularly useful when sharing one's home directory between several types of machines; one can, for example, set path = (~/bin.$MACHTYPE /usr/ucb /bin /usr/bin .) in one's ~/.login and put executables compiled for each machine in the appropriate directory. The version shell variable indicates what options were chosen when the shell was compiled. Note also the newgrp builtin, the afsuser and echo_style shell variables and the system-dependent locations of the shell's input files (see FILES). Signal handling Login shells ignore interrupts when reading the file ~/.logout. The shell ignores quit signals unless started with -q. Login shells catch the terminate signal, but non-login shells inherit the terminate behavior from their parents. Other signals have the values which the shell inherited from its parent. In shell scripts, the shell's handling of interrupt and terminate signals can be controlled with onintr, and its handling of hangups can be controlled with hup and nohup. The shell exits on a hangup (see also the logout shell variable). By default, the shell's children do too, but the shell does not send them a hangup when it exits. hup arranges for the shell to send a hangup to a child when it exits, and nohup sets a child to ignore hangups. Terminal management (+) The shell uses three different sets of terminal (``tty'') modes: `edit', used when editing, `quote', used when quoting literal characters, and `execute', used when executing commands. The shell holds some settings in each mode constant, so commands which leave the tty in a confused state do not interfere with the shell. The shell also matches changes in the speed and padding of the tty. The list of tty modes that are kept constant can be examined and modified with the setty builtin. Note that although the editor uses CBREAK mode (or its equivalent), it takes typed-ahead characters anyway. The echotc, settc and telltc commands can be used to manipulate and debug terminal capabilities from the command line. On systems that support SIGWINCH or SIGWINDOW, the shell adapts to window resizing automatically and adjusts the environment variables LINES and COLUMNS if set. If the environment variable TERMCAP contains li# and co# fields, the shell adjusts them to reflect the new window size. REFERENCE The next sections of this manual describe all of the available Builtin commands, Special aliases and Special shell variables. Builtin commands %job A synonym for the fg builtin command. %job & A synonym for the bg builtin command. : Does nothing, successfully. @ @ name = expr @ name[index] = expr @ name++|-- @ name[index]++|-- The first form prints the values of all shell variables. The second form assigns the value of expr to name. The third form assigns the value of expr to the index'th component of name; both name and its index'th component must already exist. expr may contain the operators `*', `+', etc., as in C. If expr contains `<', `>', `&' or `' then at least that part of expr must be placed within `()'. Note that the syntax of expr has nothing to do with that described under Expressions. The fourth and fifth forms increment (`++') or decrement (`--') name or its index'th component. The space between `@' and name is required. The spaces between name and `=' and between `=' and expr are optional. Components of expr must be separated by spaces. alias [name [wordlist]] Without arguments, prints all aliases. With name, prints the alias for name. With name and wordlist, assigns wordlist as the alias of name. wordlist is command and filename substituted. name may not be `alias' or `unalias'. See also the unalias builtin command. alloc Shows the amount of dynamic memory acquired, broken down into used and free memory. With an argument shows the number of free and used blocks in each size category. The categories start at size 8 and double at each step. This command's output may vary across system types, because systems other than the VAX may use a different memory allocator. bg [%job ...] Puts the specified jobs (or, without arguments, the current job) into the background, continuing each if it is stopped. job may be a number, a string, `', `%', `+' or `-' as described under Jobs. bindkey [-l|-d|-e|-v|-u] (+) bindkey [-a] [-b] [-k] [-r] [--] key (+) bindkey [-a] [-b] [-k] [-c|-s] [--] key command (+) Without options, the first form lists all bound keys and the editor command to which each is bound, the second form lists the editor command to which key is bound and the third form binds the editor command command to key. Options include: -l Lists all editor commands and a short description of each. -d Binds all keys to the standard bindings for the default editor, as per -e and -v below. -e Binds all keys to emacs(1)-style bindings. Unsets vimode. -v Binds all keys to vi(1)-style bindings. Sets vimode. -a Lists or changes key-bindings in the alternative key map. This is the key map used in vimode command mode. -b key is interpreted as a control character written ^character (e.g., `^A') or C-character (e.g., `C-A'), a meta character written M-character (e.g., `M-A'), a function key written F-string (e.g., `F-string'), or an extended prefix key written X-character (e.g., `X-A'). -k key is interpreted as a symbolic arrow key name, which may be one of `down', `up', `left' or `right'. -r Removes key's binding. Be careful: `bindkey -r' does not bind key to self-insert-command (q.v.), it unbinds key completely. -c command is interpreted as a builtin or external command instead of an editor command. -s command is taken as a literal string and treated as terminal input when key is typed. Bound keys in command are themselves reinterpreted, and this continues for ten levels of interpretation. -- Forces a break from option processing, so the next word is taken as key even if it begins with '-'. -u (or any invalid option) Prints a usage message. key may be a single character or a string. If a command is bound to a string, the first character of the string is bound to sequence-lead-in and the entire string is bound to the command. Control characters in key can be literal (they can be typed by preceding them with the editor command quoted-insert, normally bound to `^V') or written caret-character style, e.g., `^A'. Delete is written `^?' (caret-question mark). key and command can contain backslashed escape sequences (in the style of System V echo(1)) as follows: \a Bell \b Backspace \e Escape \f Form feed \n Newline \r Carriage return \t Horizontal tab \v Vertical tab \nnn The ASCII character corresponding to the octal number nnn `\' nullifies the special meaning of the following character, if it has any, notably `\' and `^'. bs2cmd bs2000-command (+) Passes bs2000-command to the BS2000 command interpreter for execution. Only non-interactive commands can be executed, and it is not possible to execute any command that would overlay the image of the current process, like /EXECUTE or /CALL- PROCEDURE. (BS2000 only) break Causes execution to resume after the end of the nearest enclosing foreach or while. The remaining commands on the current line are executed. Multi-level breaks are thus possible by writing them all on one line. breaksw Causes a break from a switch, resuming after the endsw. builtins (+) Prints the names of all builtin commands. bye (+) A synonym for the logout builtin command. Available only if the shell was so compiled; see the version shell variable. case label: A label in a switch statement as discussed below. cd [-p] [-l] [-n|-v] [I--] [name] If a directory name is given, changes the shell's working directory to name. If not, changes to home, unless the cdtohome variable is not set, in which case a name is required. If name is `-' it is interpreted as the previous working directory (see Other substitutions). (+) If name is not a subdirectory of the current directory (and does not begin with `/', `./' or `../'), each component of the variable cdpath is checked to see if it has a subdirectory name. Finally, if all else fails but name is a shell variable whose value begins with `/' or '.', then this is tried to see if it is a directory, and the -p option is implied. With -p, prints the final directory stack, just like dirs. The -l, -n and -v flags have the same effect on cd as on dirs, and they imply -p. (+) Using -- forces a break from option processing so the next word is taken as the directory name even if it begins with '-'. (+) See also the implicitcd and cdtohome shell variables. chdir A synonym for the cd builtin command. complete [command [word/pattern/list[:select]/[[suffix]/] ...]] (+) Without arguments, lists all completions. With command, lists completions for command. With command and word etc., defines completions. command may be a full command name or a glob-pattern (see Filename substitution). It can begin with `-' to indicate that completion should be used only when command is ambiguous. word specifies which word relative to the current word is to be completed, and may be one of the following: c Current-word completion. pattern is a glob-pattern which must match the beginning of the current word on the command line. pattern is ignored when completing the current word. C Like c, but includes pattern when completing the current word. n Next-word completion. pattern is a glob-pattern which must match the beginning of the previous word on the command line. N Like n, but must match the beginning of the word two before the current word. p Position-dependent completion. pattern is a numeric range, with the same syntax used to index shell variables, which must include the current word. list, the list of possible completions, may be one of the following: a Aliases b Bindings (editor commands) c Commands (builtin or external commands) C External commands which begin with the supplied path prefix d Directories D Directories which begin with the supplied path prefix e Environment variables f Filenames F Filenames which begin with the supplied path prefix g Groupnames j Jobs l Limits n Nothing s Shell variables S Signals t Plain (``text'') files T Plain (``text'') files which begin with the supplied path prefix v Any variables u Usernames x Like n, but prints select when list-choices is used. X Completions $var Words from the variable var (...) Words from the given list `...` Words from the output of command select is an optional glob-pattern. If given, words from only list that match select are considered and the fignore shell variable is ignored. The last three types of completion may not have a select pattern, and x uses select as an explanatory message when the list-choices editor command is used. suffix is a single character to be appended to a successful completion. If null, no character is appended. If omitted (in which case the fourth delimiter can also be omitted), a slash is appended to directories and a space to other words. command invoked from `...` version has additional environment variable set, the variable name is COMMAND_LINE and contains (as its name indicates) contents of the current (already typed in) command line. One can examine and use contents of the COMMAND_LINE variable in her custom script to build more sophisticated completions (see completion for svn(1) included in this package). Now for some examples. Some commands take only directories as arguments, so there's no point completing plain files. > complete cd 'p/1/d/' completes only the first word following `cd' (`p/1') with a directory. p-type completion can also be used to narrow down command completion: > co[^D] complete compress > complete -co* 'p/0/(compress)/' > co[^D] > compress This completion completes commands (words in position 0, `p/0') which begin with `co' (thus matching `co*') to `compress' (the only word in the list). The leading `-' indicates that this completion is to be used with only ambiguous commands. > complete find 'n/-user/u/' is an example of n-type completion. Any word following `find' and immediately following `-user' is completed from the list of users. > complete cc 'c/-I/d/' demonstrates c-type completion. Any word following `cc' and beginning with `-I' is completed as a directory. `-I' is not taken as part of the directory because we used lowercase c. Different lists are useful with different commands. > complete alias 'p/1/a/' > complete man 'p/*/c/' > complete set 'p/1/s/' > complete true 'p/1/x:Truth has no options./' These complete words following `alias' with aliases, `man' with commands, and `set' with shell variables. `true' doesn't have any options, so x does nothing when completion is attempted and prints `Truth has no options.' when completion choices are listed. Note that the man example, and several other examples below, could just as well have used 'c/*' or 'n/*' as 'p/*'. Words can be completed from a variable evaluated at completion time, > complete ftp 'p/1/$hostnames/' > set hostnames = (rtfm.mit.edu tesla.ee.cornell.edu) > ftp [^D] rtfm.mit.edu tesla.ee.cornell.edu > ftp [^C] > set hostnames = (rtfm.mit.edu tesla.ee.cornell.edu uunet.uu.net) > ftp [^D] rtfm.mit.edu tesla.ee.cornell.edu uunet.uu.net or from a command run at completion time: > complete kill 'p/*/`ps | awk \{print\ \$1\}`/' > kill -9 [^D] 23113 23377 23380 23406 23429 23529 23530 PID Note that the complete command does not itself quote its arguments, so the braces, space and `$' in `{print $1}' must be quoted explicitly. One command can have multiple completions: > complete dbx 'p/2/(core)/' 'p/*/c/' completes the second argument to `dbx' with the word `core' and all other arguments with commands. Note that the positional completion is specified before the next-word completion. Because completions are evaluated from left to right, if the next-word completion were specified first it would always match and the positional completion would never be executed. This is a common mistake when defining a completion. The select pattern is useful when a command takes files with only particular forms as arguments. For example, > complete cc 'p/*/f:*.[cao]/' completes `cc' arguments to files ending in only `.c', `.a', or `.o'. select can also exclude files, using negation of a glob- pattern as described under Filename substitution. One might use > complete rm 'p/*/f:^*.{c,h,cc,C,tex,1,man,l,y}/' to exclude precious source code from `rm' completion. Of course, one could still type excluded names manually or override the completion mechanism using the complete-word-raw or list-choices-raw editor commands (q.v.). The `C', `D', `F' and `T' lists are like `c', `d', `f' and `t' respectively, but they use the select argument in a different way: to restrict completion to files beginning with a particular path prefix. For example, the Elm mail program uses `=' as an abbreviation for one's mail directory. One might use > complete elm c@=@F:$HOME/Mail/@ to complete `elm -f =' as if it were `elm -f ~/Mail/'. Note that we used `@' instead of `/' to avoid confusion with the select argument, and we used `$HOME' instead of `~' because home directory substitution works at only the beginning of a word. suffix is used to add a nonstandard suffix (not space or `/' for directories) to completed words. > complete finger 'c/*@/$hostnames/' 'p/1/u/@' completes arguments to `finger' from the list of users, appends an `@', and then completes after the `@' from the `hostnames' variable. Note again the order in which the completions are specified. Finally, here's a complex example for inspiration: > complete find \ 'n/-name/f/' 'n/-newer/f/' 'n/-{,n}cpio/f/' \ ´n/-exec/c/' 'n/-ok/c/' 'n/-user/u/' \ 'n/-group/g/' 'n/-fstype/(nfs 4.2)/' \ 'n/-type/(b c d f l p s)/' \ ´c/-/(name newer cpio ncpio exec ok user \ group fstype type atime ctime depth inum \ ls mtime nogroup nouser perm print prune \ size xdev)/' \ 'p/*/d/' This completes words following `-name', `-newer', `-cpio' or `ncpio' (note the pattern which matches both) to files, words following `-exec' or `-ok' to commands, words following `user' and `group' to users and groups respectively and words following `-fstype' or `-type' to members of the given lists. It also completes the switches themselves from the given list (note the use of c-type completion) and completes anything not otherwise completed to a directory. Whew. Remember that programmed completions are ignored if the word being completed is a tilde substitution (beginning with `~') or a variable (beginning with `$'). See also the uncomplete builtin command. continue Continues execution of the nearest enclosing while or foreach. The rest of the commands on the current line are executed. default: Labels the default case in a switch statement. It should come after all case labels. dirs [-l] [-n|-v] dirs -S|-L [filename] (+) dirs -c (+) The first form prints the directory stack. The top of the stack is at the left and the first directory in the stack is the current directory. With -l, `~' or `~name' in the output is expanded explicitly to home or the pathname of the home directory for user name. (+) With -n, entries are wrapped before they reach the edge of the screen. (+) With -v, entries are printed one per line, preceded by their stack positions. (+) If more than one of -n or -v is given, -v takes precedence. -p is accepted but does nothing. With -S, the second form saves the directory stack to filename as a series of cd and pushd commands. With -L, the shell sources filename, which is presumably a directory stack file saved by the -S option or the savedirs mechanism. In either case, dirsfile is used if filename is not given and ~/.cshdirs is used if dirsfile is unset. Note that login shells do the equivalent of `dirs -L' on startup and, if savedirs is set, `dirs -S' before exiting. Because only ~/.tcshrc is normally sourced before ~/.cshdirs, dirsfile should be set in ~/.tcshrc rather than ~/.login. The last form clears the directory stack. echo [-n] word ... Writes each word to the shell's standard output, separated by spaces and terminated with a newline. The echo_style shell variable may be set to emulate (or not) the flags and escape sequences of the BSD and/or System V versions of echo; see echo(1). echotc [-sv] arg ... (+) Exercises the terminal capabilities (see termcap(5)) in args. For example, 'echotc home' sends the cursor to the home position, 'echotc cm 3 10' sends it to column 3 and row 10, and 'echotc ts 0; echo "This is a test."; echotc fs' prints "This is a test." in the status line. If arg is 'baud', 'cols', 'lines', 'meta' or 'tabs', prints the value of that capability ("yes" or "no" indicating that the terminal does or does not have that capability). One might use this to make the output from a shell script less verbose on slow terminals, or limit command output to the number of lines on the screen: > set history=`echotc lines` > @ history-- Termcap strings may contain wildcards which will not echo correctly. One should use double quotes when setting a shell variable to a terminal capability string, as in the following example that places the date in the status line: > set tosl="`echotc ts 0`" > set frsl="`echotc fs`" > echo -n "$tosl";date; echo -n "$frsl" With -s, nonexistent capabilities return the empty string rather than causing an error. With -v, messages are verbose. else end endif endsw See the description of the foreach, if, switch, and while statements below. eval arg ... Treats the arguments as input to the shell and executes the resulting command(s) in the context of the current shell. This is usually used to execute commands generated as the result of command or variable substitution, because parsing occurs before these substitutions. See tset(1) for a sample use of eval. exec command Executes the specified command in place of the current shell. exit [expr] The shell exits either with the value of the specified expr (an expression, as described under Expressions) or, without expr, with the value 0. fg [%job ...] Brings the specified jobs (or, without arguments, the current job) into the foreground, continuing each if it is stopped. job may be a number, a string, `', `%', `+' or `-' as described under Jobs. See also the run-fg-editor editor command. filetest -op file ... (+) Applies op (which is a file inquiry operator as described under File inquiry operators) to each file and returns the results as a space-separated list. foreach name (wordlist) ... end Successively sets the variable name to each member of wordlist and executes the sequence of commands between this command and the matching end. (Both foreach and end must appear alone on separate lines.) The builtin command continue may be used to continue the loop prematurely and the builtin command break to terminate it prematurely. When this command is read from the terminal, the loop is read once prompting with `foreach? ' (or prompt2) before any statements in the loop are executed. If you make a mistake typing in a loop at the terminal you can rub it out. getspath (+) Prints the system execution path. (TCF only) getxvers (+) Prints the experimental version prefix. (TCF only) glob wordlist Like echo, but the `-n' parameter is not recognized and words are delimited by null characters in the output. Useful for programs which wish to use the shell to filename expand a list of words. goto word word is filename and command-substituted to yield a string of the form `label'. The shell rewinds its input as much as possible, searches for a line of the form `label:', possibly preceded by blanks or tabs, and continues execution after that line. hashstat Prints a statistics line indicating how effective the internal hash table has been at locating commands (and avoiding exec's). An exec is attempted for each component of the path where the hash function indicates a possible hit, and in each component which does not begin with a `/'. On machines without vfork(2), prints only the number and size of hash buckets. history [-hTr] [n] history -S|-L|-M [filename] (+) history -c (+) The first form prints the history event list. If n is given only the n most recent events are printed or saved. With -h, the history list is printed without leading numbers. If -T is specified, timestamps are printed also in comment form. (This can be used to produce files suitable for loading with 'history -L' or 'source -h'.) With -r, the order of printing is most recent first rather than oldest first. With -S, the second form saves the history list to filename. If the first word of the savehist shell variable is set to a number, at most that many lines are saved. If the second word of savehist is set to `merge', the history list is merged with the existing history file instead of replacing it (if there is one) and sorted by time stamp. (+) Merging is intended for an environment like the X Window System with several shells in simultaneous use. If the second word of savehist is `merge' and the third word is set to `lock', the history file update will be serialized with other shell sessions that would possibly like to merge history at exactly the same time. With -L, the shell appends filename, which is presumably a history list saved by the -S option or the savehist mechanism, to the history list. -M is like -L, but the contents of filename are merged into the history list and sorted by timestamp. In either case, histfile is used if filename is not given and ~/.history is used if histfile is unset. `history -L' is exactly like 'source -h' except that it does not require a filename. Note that login shells do the equivalent of `history -L' on startup and, if savehist is set, `history -S' before exiting. Because only ~/.tcshrc is normally sourced before ~/.history, histfile should be set in ~/.tcshrc rather than ~/.login. If histlit is set, the first and second forms print and save the literal (unexpanded) form of the history list. The last form clears the history list. hup [command] (+) With command, runs command such that it will exit on a hangup signal and arranges for the shell to send it a hangup signal when the shell exits. Note that commands may set their own response to hangups, overriding hup. Without an argument, causes the non-interactive shell only to exit on a hangup for the remainder of the script. See also Signal handling and the nohup builtin command. if (expr) command If expr (an expression, as described under Expressions) evaluates true, then command is executed. Variable substitution on command happens early, at the same time it does for the rest of the if command. command must be a simple command, not an alias, a pipeline, a command list or a parenthesized command list, but it may have arguments. Input/output redirection occurs even if expr is false and command is thus not executed; this is a bug. if (expr) then ... else if (expr2) then ... else ... endif If the specified expr is true then the commands to the first else are executed; otherwise if expr2 is true then the commands to the second else are executed, etc. Any number of else-if pairs are possible; only one endif is needed. The else part is likewise optional. (The words else and endif must appear at the beginning of input lines; the if must appear alone on its input line or after an else.) inlib shared-library ... (+) Adds each shared-library to the current environment. There is no way to remove a shared library. (Domain/OS only) jobs [-l] Lists the active jobs. With -l, lists process IDs in addition to the normal information. On TCF systems, prints the site on which each job is executing. kill [-s signal] %job|pid ... kill -l The first and second forms sends the specified signal (or, if none is given, the TERM (terminate) signal) to the specified jobs or processes. job may be a number, a string, `', `%', `+' or `-' as described under Jobs. Signals are either given by number or by name (as given in /usr/include/signal.h, stripped of the prefix `SIG'). There is no default job; saying just `kill' does not send a signal to the current job. If the signal being sent is TERM (terminate) or HUP (hangup), then the job or process is sent a CONT (continue) signal as well. The third form lists the signal names. limit [-h] [resource [maximum-use]] Limits the consumption by the current process and each process it creates to not individually exceed maximum-use on the specified resource. If no maximum-use is given, then the current limit is printed; if no resource is given, then all limitations are given. If the -h flag is given, the hard limits are used instead of the current limits. The hard limits impose a ceiling on the values of the current limits. Only the super-user may raise the hard limits, but a user may lower or raise the current limits within the legal range. Controllable resources currently include (if supported by the OS): cputime the maximum number of cpu-seconds to be used by each process filesize the largest single file which can be created datasize the maximum growth of the data+stack region via sbrk(2) beyond the end of the program text stacksize the maximum size of the automatically-extended stack region coredumpsize the size of the largest core dump that will be created memoryuse the maximum amount of physical memory a process may have allocated to it at a given time vmemoryuse the maximum amount of virtual memory a process may have allocated to it at a given time (address space) vmemoryuse the maximum amount of virtual memory a process may have allocated to it at a given time heapsize the maximum amount of memory a process may allocate per brk() system call descriptors or openfiles the maximum number of open files for this process pseudoterminals the maximum number of pseudo-terminals for this user kqueues the maximum number of kqueues allocated for this process concurrency the maximum number of threads for this process memorylocked the maximum size which a process may lock into memory using mlock(2) maxproc the maximum number of simultaneous processes for this user id maxthread the maximum number of simultaneous threads (lightweight processes) for this user id threads the maximum number of threads for this process sbsize the maximum size of socket buffer usage for this user swapsize the maximum amount of swap space reserved or used for this user maxlocks the maximum number of locks for this user posixlocks the maximum number of POSIX advisory locks for this user maxsignal the maximum number of pending signals for this user maxmessage the maximum number of bytes in POSIX mqueues for this user maxnice the maximum nice priority the user is allowed to raise mapped from [19...-20] to [0...39] for this user maxrtprio the maximum realtime priority for this user maxrttime the timeout for RT tasks in microseconds for this user. maximum-use may be given as a (floating point or integer) number followed by a scale factor. For all limits other than cputime the default scale is `k' or `kilobytes' (1024 bytes); a scale factor of `m' or `megabytes' or `g' or `gigabytes' may also be used. For cputime the default scaling is `seconds', while `m' for minutes or `h' for hours, or a time of the form `mm:ss' giving minutes and seconds may be used. If maximum-use is `unlimited', then the limitation on the specified resource is removed (this is equivalent to the unlimit builtin command). For both resource names and scale factors, unambiguous prefixes of the names suffice. log (+) Prints the watch shell variable and reports on each user indicated in watch who is logged in, regardless of when they last logged in. See also watchlog. login Terminates a login shell, replacing it with an instance of /bin/login. This is one way to log off, included for compatibility with sh(1). logout Terminates a login shell. Especially useful if ignoreeof is set. ls-F [-switch ...] [file ...] (+) Lists files like `ls -F', but much faster. It identifies each type of special file in the listing with a special character: / Directory * Executable # Block device % Character device | Named pipe (systems with named pipes only) = Socket (systems with sockets only) @ Symbolic link (systems with symbolic links only) + Hidden directory (AIX only) or context dependent (HP/UX only) : Network special (HP/UX only) If the listlinks shell variable is set, symbolic links are identified in more detail (on only systems that have them, of course): @ Symbolic link to a non-directory > Symbolic link to a directory & Symbolic link to nowhere listlinks also slows down ls-F and causes partitions holding files pointed to by symbolic links to be mounted. If the listflags shell variable is set to `x', `a' or `A', or any combination thereof (e.g., `xA'), they are used as flags to ls-F, making it act like `ls -xF', `ls -Fa', `ls -FA' or a combination (e.g., `ls -FxA'). On machines where `ls -C' is not the default, ls-F acts like `ls -CF', unless listflags contains an `x', in which case it acts like `ls -xF'. ls-F passes its arguments to ls(1) if it is given any switches, so `alias ls ls-F' generally does the right thing. The ls-F builtin can list files using different colors depending on the filetype or extension. See the color shell variable and the LS_COLORS environment variable. migrate [-site] pid|%jobid ... (+) migrate -site (+) The first form migrates the process or job to the site specified or the default site determined by the system path. The second form is equivalent to `migrate -site $$': it migrates the current process to the specified site. Migrating the shell itself can cause unexpected behavior, because the shell does not like to lose its tty. (TCF only) newgrp [-] [group] (+) Equivalent to `exec newgrp'; see newgrp(1). Available only if the shell was so compiled; see the version shell variable. nice [+number] [command] Sets the scheduling priority for the shell to number, or, without number, to 4. With command, runs command at the appropriate priority. The greater the number, the less cpu the process gets. The super-user may specify negative priority by using `nice -number ...'. Command is always executed in a sub- shell, and the restrictions placed on commands in simple if statements apply. nohup [command] With command, runs command such that it will ignore hangup signals. Note that commands may set their own response to hangups, overriding nohup. Without an argument, causes the non-interactive shell only to ignore hangups for the remainder of the script. See also Signal handling and the hup builtin command. notify [%job ...] Causes the shell to notify the user asynchronously when the status of any of the specified jobs (or, without %job, the current job) changes, instead of waiting until the next prompt as is usual. job may be a number, a string, `', `%', `+' or `-' as described under Jobs. See also the notify shell variable. onintr [-|label] Controls the action of the shell on interrupts. Without arguments, restores the default action of the shell on interrupts, which is to terminate shell scripts or to return to the terminal command input level. With `-', causes all interrupts to be ignored. With label, causes the shell to execute a `goto label' when an interrupt is received or a child process terminates because it was interrupted. onintr is ignored if the shell is running detached and in system startup files (see FILES), where interrupts are disabled anyway. popd [-p] [-l] [-n|-v] [+n] Without arguments, pops the directory stack and returns to the new top directory. With a number `+n', discards the n'th entry in the stack. Finally, all forms of popd print the final directory stack, just like dirs. The pushdsilent shell variable can be set to prevent this and the -p flag can be given to override pushdsilent. The -l, -n and -v flags have the same effect on popd as on dirs. (+) printenv [name] (+) Prints the names and values of all environment variables or, with name, the value of the environment variable name. pushd [-p] [-l] [-n|-v] [name|+n] Without arguments, exchanges the top two elements of the directory stack. If pushdtohome is set, pushd without arguments does `pushd ~', like cd. (+) With name, pushes the current working directory onto the directory stack and changes to name. If name is `-' it is interpreted as the previous working directory (see Filename substitution). (+) If dunique is set, pushd removes any instances of name from the stack before pushing it onto the stack. (+) With a number `+n', rotates the nth element of the directory stack around to be the top element and changes to it. If dextract is set, however, `pushd +n' extracts the nth directory, pushes it onto the top of the stack and changes to it. (+) Finally, all forms of pushd print the final directory stack, just like dirs. The pushdsilent shell variable can be set to prevent this and the -p flag can be given to override pushdsilent. The -l, -n and -v flags have the same effect on pushd as on dirs. (+) rehash Causes the internal hash table of the contents of the directories in the path variable to be recomputed. This is needed if the autorehash shell variable is not set and new commands are added to directories in path while you are logged in. With autorehash, a new command will be found automatically, except in the special case where another command of the same name which is located in a different directory already exists in the hash table. Also flushes the cache of home directories built by tilde expansion. repeat count command The specified command, which is subject to the same restrictions as the command in the one line if statement above, is executed count times. I/O redirections occur exactly once, even if count is 0. rootnode //nodename (+) Changes the rootnode to //nodename, so that `/' will be interpreted as `//nodename'. (Domain/OS only) sched (+) sched [+]hh:mm command (+) sched -n (+) The first form prints the scheduled-event list. The sched shell variable may be set to define the format in which the scheduled-event list is printed. The second form adds command to the scheduled-event list. For example, > sched 11:00 echo It\'s eleven o\'clock. causes the shell to echo `It's eleven o'clock.' at 11 AM. The time may be in 12-hour AM/PM format > sched 5pm set prompt='[%h] It\'s after 5; go home: >' or may be relative to the current time: > sched +2:15 /usr/lib/uucp/uucico -r1 -sother A relative time specification may not use AM/PM format. The third form removes item n from the event list: > sched 1 Wed Apr 4 15:42 /usr/lib/uucp/uucico -r1 -sother 2 Wed Apr 4 17:00 set prompt=[%h] It's after 5; go home: > > sched -2 > sched 1 Wed Apr 4 15:42 /usr/lib/uucp/uucico -r1 -sother A command in the scheduled-event list is executed just before the first prompt is printed after the time when the command is scheduled. It is possible to miss the exact time when the command is to be run, but an overdue command will execute at the next prompt. A command which comes due while the shell is waiting for user input is executed immediately. However, normal operation of an already-running command will not be interrupted so that a scheduled-event list element may be run. This mechanism is similar to, but not the same as, the at(1) command on some Unix systems. Its major disadvantage is that it may not run a command at exactly the specified time. Its major advantage is that because sched runs directly from the shell, it has access to shell variables and other structures. This provides a mechanism for changing one's working environment based on the time of day. set set name ... set name=word ... set [-r] [-f|-l] name=(wordlist) ... (+) set name[index]=word ... set -r (+) set -r name ... (+) set -r name=word ... (+) The first form of the command prints the value of all shell variables. Variables which contain more than a single word print as a parenthesized word list. The second form sets name to the null string. The third form sets name to the single word. The fourth form sets name to the list of words in wordlist. In all cases the value is command and filename expanded. If -r is specified, the value is set read-only. If -f or -l are specified, set only unique words keeping their order. -f prefers the first occurrence of a word, and -l the last. The fifth form sets the index'th component of name to word; this component must already exist. The sixth form lists only the names of all shell variables that are read-only. The seventh form makes name read-only, whether or not it has a value. The eighth form is the same as the third form, but make name read-only at the same time. These arguments can be repeated to set and/or make read-only multiple variables in a single set command. Note, however, that variable expansion happens for all arguments before any setting occurs. Note also that `=' can be adjacent to both name and word or separated from both by whitespace, but cannot be adjacent to only one or the other. See also the unset builtin command. setenv [name [value]] Without arguments, prints the names and values of all environment variables. Given name, sets the environment variable name to value or, without value, to the null string. setpath path (+) Equivalent to setpath(1). (Mach only) setspath LOCAL|site|cpu ... (+) Sets the system execution path. (TCF only) settc cap value (+) Tells the shell to believe that the terminal capability cap (as defined in termcap(5)) has the value value. No sanity checking is done. Concept terminal users may have to `settc xn no' to get proper wrapping at the rightmost column. setty [-d|-q|-x] [-a] [[+|-]mode] (+) Controls which tty modes (see Terminal management) the shell does not allow to change. -d, -q or -x tells setty to act on the `edit', `quote' or `execute' set of tty modes respectively; without -d, -q or -x, `execute' is used. Without other arguments, setty lists the modes in the chosen set which are fixed on (`+mode') or off (`-mode'). The available modes, and thus the display, vary from system to system. With -a, lists all tty modes in the chosen set whether or not they are fixed. With +mode, -mode or mode, fixes mode on or off or removes control from mode in the chosen set. For example, `setty +echok echoe' fixes `echok' mode on and allows commands to turn `echoe' mode on or off, both when the shell is executing commands. setxvers [string] (+) Set the experimental version prefix to string, or removes it if string is omitted. (TCF only) shift [variable] Without arguments, discards argv[1] and shifts the members of argv to the left. It is an error for argv not to be set or to have less than one word as value. With variable, performs the same function on variable. source [-h] name [args ...] The shell reads and executes commands from name. The commands are not placed on the history list. If any args are given, they are placed in argv. (+) source commands may be nested; if they are nested too deeply the shell may run out of file descriptors. An error in a source at any level terminates all nested source commands. With -h, commands are placed on the history list instead of being executed, much like `history -L'. stop %job|pid ... Stops the specified jobs or processes which are executing in the background. job may be a number, a string, `', `%', `+' or `-' as described under Jobs. There is no default job; saying just `stop' does not stop the current job. suspend Causes the shell to stop in its tracks, much as if it had been sent a stop signal with ^Z. This is most often used to stop shells started by su(1). switch (string) case str1: ... breaksw ... default: ... breaksw endsw Each case label is successively matched, against the specified string which is first command and filename expanded. The file metacharacters `*', `?' and `[...]' may be used in the case labels, which are variable expanded. If none of the labels match before a `default' label is found, then the execution begins after the default label. Each case label and the default label must appear at the beginning of a line. The command breaksw causes execution to continue after the endsw. Otherwise control may fall through case labels and default labels as in C. If no label matches and there is no default, execution continues after the endsw. telltc (+) Lists the values of all terminal capabilities (see termcap(5)). termname [terminal type] (+) Tests if terminal type (or the current value of TERM if no terminal type is given) has an entry in the hosts termcap(5) or terminfo(5) database. Prints the terminal type to stdout and returns 0 if an entry is present otherwise returns 1. time [command] Executes command (which must be a simple command, not an alias, a pipeline, a command list or a parenthesized command list) and prints a time summary as described under the time variable. If necessary, an extra shell is created to print the time statistic when the command completes. Without command, prints a time summary for the current shell and its children. umask [value] Sets the file creation mask to value, which is given in octal. Common values for the mask are 002, giving all access to the group and read and execute access to others, and 022, giving read and execute access to the group and others. Without value, prints the current file creation mask. unalias pattern Removes all aliases whose names match pattern. `unalias *' thus removes all aliases. It is not an error for nothing to be unaliased. uncomplete pattern (+) Removes all completions whose names match pattern. `uncomplete *' thus removes all completions. It is not an error for nothing to be uncompleted. unhash Disables use of the internal hash table to speed location of executed programs. universe universe (+) Sets the universe to universe. (Masscomp/RTU only) unlimit [-hf] [resource] Removes the limitation on resource or, if no resource is specified, all resource limitations. With -h, the corresponding hard limits are removed. Only the super-user may do this. Note that unlimit may not exit successful, since most systems do not allow descriptors to be unlimited. With -f errors are ignored. unset pattern Removes all variables whose names match pattern, unless they are read-only. `unset *' thus removes all variables unless they are read-only; this is a bad idea. It is not an error for nothing to be unset. unsetenv pattern Removes all environment variables whose names match pattern. `unsetenv *' thus removes all environment variables; this is a bad idea. It is not an error for nothing to be unsetenved. ver [systype [command]] (+) Without arguments, prints SYSTYPE. With systype, sets SYSTYPE to systype. With systype and command, executes command under systype. systype may be `bsd4.3' or `sys5.3'. (Domain/OS only) wait The shell waits for all background jobs. If the shell is interactive, an interrupt will disrupt the wait and cause the shell to print the names and job numbers of all outstanding jobs. warp universe (+) Sets the universe to universe. (Convex/OS only) watchlog (+) An alternate name for the log builtin command (q.v.). Available only if the shell was so compiled; see the version shell variable. where command (+) Reports all known instances of command, including aliases, builtins and executables in path. which command (+) Displays the command that will be executed by the shell after substitutions, path searching, etc. The builtin command is just like which(1), but it correctly reports tcsh aliases and builtins and is 10 to 100 times faster. See also the which- command editor command. while (expr) ... end Executes the commands between the while and the matching end while expr (an expression, as described under Expressions) evaluates non-zero. while and end must appear alone on their input lines. break and continue may be used to terminate or continue the loop prematurely. If the input is a terminal, the user is prompted the first time through the loop as with foreach. Special aliases (+) If set, each of these aliases executes automatically at the indicated time. They are all initially undefined. beepcmd Runs when the shell wants to ring the terminal bell. cwdcmd Runs after every change of working directory. For example, if the user is working on an X window system using xterm(1) and a re-parenting window manager that supports title bars such as twm(1) and does > alias cwdcmd 'echo -n "^[]2;${HOST}:$cwd ^G"' then the shell will change the title of the running xterm(1) to be the name of the host, a colon, and the full current working directory. A fancier way to do that is > alias cwdcmd 'echo -n "^[]2;${HOST}:$cwd^G^[]1;${HOST}^G"' This will put the hostname and working directory on the title bar but only the hostname in the icon manager menu. Note that putting a cd, pushd or popd in cwdcmd may cause an infinite loop. It is the author's opinion that anyone doing so will get what they deserve. jobcmd Runs before each command gets executed, or when the command changes state. This is similar to postcmd, but it does not print builtins. > alias jobcmd 'echo -n "^[]2\;\!#:q^G"' then executing vi foo.c will put the command string in the xterm title bar. helpcommand Invoked by the run-help editor command. The command name for which help is sought is passed as sole argument. For example, if one does > alias helpcommand '\!:1 --help' then the help display of the command itself will be invoked, using the GNU help calling convention. Currently there is no easy way to account for various calling conventions (e.g., the customary Unix `-h'), except by using a table of many commands. periodic Runs every tperiod minutes. This provides a convenient means for checking on common but infrequent changes such as new mail. For example, if one does > set tperiod = 30 > alias periodic checknews then the checknews(1) program runs every 30 minutes. If periodic is set but tperiod is unset or set to 0, periodic behaves like precmd. precmd Runs just before each prompt is printed. For example, if one does > alias precmd date then date(1) runs just before the shell prompts for each command. There are no limits on what precmd can be set to do, but discretion should be used. postcmd Runs before each command gets executed. > alias postcmd 'echo -n "^[]2\;\!#:q^G"' then executing vi foo.c will put the command string in the xterm title bar. shell Specifies the interpreter for executable scripts which do not themselves specify an interpreter. The first word should be a full path name to the desired interpreter (e.g., `/bin/csh' or `/usr/local/bin/tcsh'). Special shell variables The variables described in this section have special meaning to the shell. The shell sets addsuffix, argv, autologout, csubstnonl, command, echo_style, edit, gid, group, home, loginsh, oid, path, prompt, prompt2, prompt3, shell, shlvl, tcsh, term, tty, uid, user and version at startup; they do not change thereafter unless changed by the user. The shell updates cwd, dirstack, owd and status when necessary, and sets logout on logout. The shell synchronizes group, home, path, shlvl, term and user with the environment variables of the same names: whenever the environment variable changes the shell changes the corresponding shell variable to match (unless the shell variable is read-only) and vice versa. Note that although cwd and PWD have identical meanings, they are not synchronized in this manner, and that the shell automatically converts between the different formats of path and PATH. addsuffix (+) If set, filename completion adds `/' to the end of directories and a space to the end of normal files when they are matched exactly. Set by default. afsuser (+) If set, autologout's autolock feature uses its value instead of the local username for kerberos authentication. ampm (+) If set, all times are shown in 12-hour AM/PM format. anyerror (+) This variable selects what is propagated to the value of the status variable. For more information see the description of the status variable below. argv The arguments to the shell. Positional parameters are taken from argv, i.e., `$1' is replaced by `$argv[1]', etc. Set by default, but usually empty in interactive shells. autocorrect (+) If set, the spell-word editor command is invoked automatically before each completion attempt. autoexpand (+) If set, the expand-history editor command is invoked automatically before each completion attempt. If this is set to onlyhistory, then only history will be expanded and a second completion will expand filenames. autolist (+) If set, possibilities are listed after an ambiguous completion. If set to `ambiguous', possibilities are listed only when no new characters are added by completion. autologout (+) The first word is the number of minutes of inactivity before automatic logout. The optional second word is the number of minutes of inactivity before automatic locking. When the shell automatically logs out, it prints `auto-logout', sets the variable logout to `automatic' and exits. When the shell automatically locks, the user is required to enter his password to continue working. Five incorrect attempts result in automatic logout. Set to `60' (automatic logout after 60 minutes, and no locking) by default in login and superuser shells, but not if the shell thinks it is running under a window system (i.e., the DISPLAY environment variable is set), the tty is a pseudo-tty (pty) or the shell was not so compiled (see the version shell variable). See also the afsuser and logout shell variables. autorehash (+) If set, the internal hash table of the contents of the directories in the path variable will be recomputed if a command is not found in the hash table. In addition, the list of available commands will be rebuilt for each command completion or spelling correction attempt if set to `complete' or `correct' respectively; if set to `always', this will be done for both cases. backslash_quote (+) If set, backslashes (`\') always quote `\', `'', and `"'. This may make complex quoting tasks easier, but it can cause syntax errors in csh(1) scripts. catalog The file name of the message catalog. If set, tcsh use `tcsh.${catalog}' as a message catalog instead of default `tcsh'. cdpath A list of directories in which cd should search for subdirectories if they aren't found in the current directory. cdtohome (+) If not set, cd requires a directory name, and will not go to the home directory if it's omitted. This is set by default. color If set, it enables color display for the builtin ls-F and it passes --color=auto to ls. Alternatively, it can be set to only ls-F or only ls to enable color to only one command. Setting it to nothing is equivalent to setting it to (ls-F ls). colorcat If set, it enables color escape sequence for NLS message files. And display colorful NLS messages. command (+) If set, the command which was passed to the shell with the -c flag (q.v.). compat_expr (+) If set, the shell will evaluate expressions right to left, like the original csh. complete (+) If set to `igncase', the completion becomes case insensitive. If set to `enhance', completion ignores case and considers hyphens and underscores to be equivalent; it will also treat periods, hyphens and underscores (`.', `-' and `_') as word separators. If set to `Enhance', completion matches uppercase and underscore characters explicitly and matches lowercase and hyphens in a case-insensitive manner; it will treat periods, hyphens and underscores as word separators. continue (+) If set to a list of commands, the shell will continue the listed commands, instead of starting a new one. continue_args (+) Same as continue, but the shell will execute: echo `pwd` $argv > ~/.<cmd>_pause; %<cmd> correct (+) If set to `cmd', commands are automatically spelling-corrected. If set to `complete', commands are automatically completed. If set to `all', the entire command line is corrected. csubstnonl (+) If set, newlines and carriage returns in command substitution are replaced by spaces. Set by default. cwd The full pathname of the current directory. See also the dirstack and owd shell variables. dextract (+) If set, `pushd +n' extracts the nth directory from the directory stack rather than rotating it to the top. dirsfile (+) The default location in which `dirs -S' and `dirs -L' look for a history file. If unset, ~/.cshdirs is used. Because only ~/.tcshrc is normally sourced before ~/.cshdirs, dirsfile should be set in ~/.tcshrc rather than ~/.login. dirstack (+) An array of all the directories on the directory stack. `$dirstack[1]' is the current working directory, `$dirstack[2]' the first directory on the stack, etc. Note that the current working directory is `$dirstack[1]' but `=0' in directory stack substitutions, etc. One can change the stack arbitrarily by setting dirstack, but the first element (the current working directory) is always correct. See also the cwd and owd shell variables. dspmbyte (+) Has an effect iff 'dspm' is listed as part of the version shell variable. If set to `euc', it enables display and editing EUC- kanji(Japanese) code. If set to `sjis', it enables display and editing Shift-JIS(Japanese) code. If set to `big5', it enables display and editing Big5(Chinese) code. If set to `utf8', it enables display and editing Utf8(Unicode) code. If set to the following format, it enables display and editing of original multi-byte code format: > set dspmbyte = 0000....(256 bytes)....0000 The table requires just 256 bytes. Each character of 256 characters corresponds (from left to right) to the ASCII codes 0x00, 0x01, ... 0xff. Each character is set to number 0,1,2 and 3. Each number has the following meaning: 0 ... not used for multi-byte characters. 1 ... used for the first byte of a multi-byte character. 2 ... used for the second byte of a multi-byte character. 3 ... used for both the first byte and second byte of a multi-byte character. Example: If set to `001322', the first character (means 0x00 of the ASCII code) and second character (means 0x01 of ASCII code) are set to `0'. Then, it is not used for multi-byte characters. The 3rd character (0x02) is set to '1', indicating that it is used for the first byte of a multi-byte character. The 4th character(0x03) is set '3'. It is used for both the first byte and the second byte of a multi-byte character. The 5th and 6th characters (0x04,0x05) are set to '2', indicating that they are used for the second byte of a multi-byte character. The GNU fileutils version of ls cannot display multi-byte filenames without the -N ( --literal ) option. If you are using this version, set the second word of dspmbyte to "ls". If not, for example, "ls-F -l" cannot display multi-byte filenames. Note: This variable can only be used if KANJI and DSPMBYTE has been defined at compile time. dunique (+) If set, pushd removes any instances of name from the stack before pushing it onto the stack. echo If set, each command with its arguments is echoed just before it is executed. For non-builtin commands all expansions occur before echoing. Builtin commands are echoed before command and filename substitution, because these substitutions are then done selectively. Set by the -x command line option. echo_style (+) The style of the echo builtin. May be set to bsd Don't echo a newline if the first argument is `-n'; the default for csh. sysv Recognize backslashed escape sequences in echo strings. both Recognize both the `-n' flag and backslashed escape sequences; the default for tcsh. none Recognize neither. Set by default to the local system default. The BSD and System V options are described in the echo(1) man pages on the appropriate systems. edit (+) If set, the command-line editor is used. Set by default in interactive shells. editors (+) A list of command names for the run-fg-editor editor command to match. If not set, the EDITOR (`ed' if unset) and VISUAL (`vi' if unset) environment variables will be used instead. ellipsis (+) If set, the `%c'/`%.' and `%C' prompt sequences (see the prompt shell variable) indicate skipped directories with an ellipsis (`...') instead of `/<skipped>'. euid (+) The user's effective user ID. euser (+) The first matching passwd entry name corresponding to the effective user ID. fignore (+) Lists file name suffixes to be ignored by completion. filec In tcsh, completion is always used and this variable is ignored by default. If edit is unset, then the traditional csh completion is used. If set in csh, filename completion is used. gid (+) The user's real group ID. globdot (+) If set, wild-card glob patterns will match files and directories beginning with `.' except for `.' and `..' globstar (+) If set, the `**' and `***' file glob patterns will match any string of characters including `/' traversing any existing sub- directories. (e.g. `ls **.c' will list all the .c files in the current directory tree). If used by itself, it will match zero or more sub-directories (e.g. `ls /usr/include/**/time.h' will list any file named `time.h' in the /usr/include directory tree; whereas `ls /usr/include/**time.h' will match any file in the /usr/include directory tree ending in `time.h'). To prevent problems with recursion, the `**' glob-pattern will not descend into a symbolic link containing a directory. To override this, use `***' group (+) The user's group name. highlight If set, the incremental search match (in i-search-back and i- search-fwd) and the region between the mark and the cursor are highlighted in reverse video. Highlighting requires more frequent terminal writes, which introduces extra overhead. If you care about terminal performance, you may want to leave this unset. histchars A string value determining the characters used in History substitution (q.v.). The first character of its value is used as the history substitution character, replacing the default character `!'. The second character of its value replaces the character `^' in quick substitutions. histdup (+) Controls handling of duplicate entries in the history list. If set to `all' only unique history events are entered in the history list. If set to `prev' and the last history event is the same as the current command, then the current command is not entered in the history. If set to `erase' and the same event is found in the history list, that old event gets erased and the current one gets inserted. Note that the `prev' and `all' options renumber history events so there are no gaps. histfile (+) The default location in which `history -S' and `history -L' look for a history file. If unset, ~/.history is used. histfile is useful when sharing the same home directory between different machines, or when saving separate histories on different terminals. Because only ~/.tcshrc is normally sourced before ~/.history, histfile should be set in ~/.tcshrc rather than ~/.login. histlit (+) If set, builtin and editor commands and the savehist mechanism use the literal (unexpanded) form of lines in the history list. See also the toggle-literal-history editor command. history The first word indicates the number of history events to save. The optional second word (+) indicates the format in which history is printed; if not given, `%h\t%T\t%R\n' is used. The format sequences are described below under prompt; note the variable meaning of `%R'. Set to `100' by default. home Initialized to the home directory of the invoker. The filename expansion of `~' refers to this variable. ignoreeof If set to the empty string or `0' and the input device is a terminal, the end-of-file command (usually generated by the user by typing `^D' on an empty line) causes the shell to print `Use "exit" to leave tcsh.' instead of exiting. This prevents the shell from accidentally being killed. Historically this setting exited after 26 successive EOF's to avoid infinite loops. If set to a number n, the shell ignores n - 1 consecutive end-of-files and exits on the nth. (+) If unset, `1' is used, i.e., the shell exits on a single `^D'. implicitcd (+) If set, the shell treats a directory name typed as a command as though it were a request to change to that directory. If set to verbose, the change of directory is echoed to the standard output. This behavior is inhibited in non-interactive shell scripts, or for command strings with more than one word. Changing directory takes precedence over executing a like-named command, but it is done after alias substitutions. Tilde and variable expansions work as expected. inputmode (+) If set to `insert' or `overwrite', puts the editor into that input mode at the beginning of each line. killdup (+) Controls handling of duplicate entries in the kill ring. If set to `all' only unique strings are entered in the kill ring. If set to `prev' and the last killed string is the same as the current killed string, then the current string is not entered in the ring. If set to `erase' and the same string is found in the kill ring, the old string is erased and the current one is inserted. killring (+) Indicates the number of killed strings to keep in memory. Set to `30' by default. If unset or set to less than `2', the shell will only keep the most recently killed string. Strings are put in the killring by the editor commands that delete (kill) strings of text, e.g. backward-delete-word, kill-line, etc, as well as the copy-region-as-kill command. The yank editor command will yank the most recently killed string into the command-line, while yank-pop (see Editor commands) can be used to yank earlier killed strings. listflags (+) If set to `x', `a' or `A', or any combination thereof (e.g., `xA'), they are used as flags to ls-F, making it act like `ls -xF', `ls -Fa', `ls -FA' or a combination (e.g., `ls -FxA'): `a' shows all files (even if they start with a `.'), `A' shows all files but `.' and `..', and `x' sorts across instead of down. If the second word of listflags is set, it is used as the path to `ls(1)'. listjobs (+) If set, all jobs are listed when a job is suspended. If set to `long', the listing is in long format. listlinks (+) If set, the ls-F builtin command shows the type of file to which each symbolic link points. listmax (+) The maximum number of items which the list-choices editor command will list without asking first. listmaxrows (+) The maximum number of rows of items which the list-choices editor command will list without asking first. loginsh (+) Set by the shell if it is a login shell. Setting or unsetting it within a shell has no effect. See also shlvl. logout (+) Set by the shell to `normal' before a normal logout, `automatic' before an automatic logout, and `hangup' if the shell was killed by a hangup signal (see Signal handling). See also the autologout shell variable. mail A list of files and directories to check for incoming mail, optionally preceded by a numeric word. Before each prompt, if 10 minutes have passed since the last check, the shell checks each file and says `You have new mail.' (or, if mail contains multiple files, `You have new mail in name.') if the filesize is greater than zero in size and has a modification time greater than its access time. If you are in a login shell, then no mail file is reported unless it has been modified after the time the shell has started up, to prevent redundant notifications. Most login programs will tell you whether or not you have mail when you log in. If a file specified in mail is a directory, the shell will count each file within that directory as a separate message, and will report `You have n mails.' or `You have n mails in name.' as appropriate. This functionality is provided primarily for those systems which store mail in this manner, such as the Andrew Mail System. If the first word of mail is numeric it is taken as a different mail checking interval, in seconds. Under very rare circumstances, the shell may report `You have mail.' instead of `You have new mail.' matchbeep (+) If set to `never', completion never beeps. If set to `nomatch', it beeps only when there is no match. If set to `ambiguous', it beeps when there are multiple matches. If set to `notunique', it beeps when there is one exact and other longer matches. If unset, `ambiguous' is used. nobeep (+) If set, beeping is completely disabled. See also visiblebell. noclobber If set, restrictions are placed on output redirection to insure that files are not accidentally destroyed and that `>>' redirections refer to existing files, as described in the Input/output section. noding If set, disable the printing of `DING!' in the prompt time specifiers at the change of hour. noglob If set, Filename substitution and Directory stack substitution (q.v.) are inhibited. This is most useful in shell scripts which do not deal with filenames, or after a list of filenames has been obtained and further expansions are not desirable. nokanji (+) If set and the shell supports Kanji (see the version shell variable), it is disabled so that the meta key can be used. nonomatch If set, a Filename substitution or Directory stack substitution (q.v.) which does not match any existing files is left untouched rather than causing an error. It is still an error for the substitution to be malformed, e.g., `echo [' still gives an error. nostat (+) A list of directories (or glob-patterns which match directories; see Filename substitution) that should not be stat(2)ed during a completion operation. This is usually used to exclude directories which take too much time to stat(2), for example /afs. notify If set, the shell announces job completions asynchronously. The default is to present job completions just before printing a prompt. oid (+) The user's real organization ID. (Domain/OS only) owd (+) The old working directory, equivalent to the `-' used by cd and pushd. See also the cwd and dirstack shell variables. padhour If set, enable the printing of padding '0' for hours, in 24 and 12 hour formats. E.G.: 07:45:42 vs. 7:45:42. parseoctal To retain compatibily with older versions numeric variables starting with 0 are not interpreted as octal. Setting this variable enables proper octal parsing. path A list of directories in which to look for executable commands. A null word specifies the current directory. If there is no path variable then only full path names will execute. path is set by the shell at startup from the PATH environment variable or, if PATH does not exist, to a system-dependent default something like `(/usr/local/bin /usr/bsd /bin /usr/bin .)'. The shell may put `.' first or last in path or omit it entirely depending on how it was compiled; see the version shell variable. A shell which is given neither the -c nor the -t option hashes the contents of the directories in path after reading ~/.tcshrc and each time path is reset. If one adds a new command to a directory in path while the shell is active, one may need to do a rehash for the shell to find it. printexitvalue (+) If set and an interactive program exits with a non-zero status, the shell prints `Exit status'. prompt The string which is printed before reading each command from the terminal. prompt may include any of the following formatting sequences (+), which are replaced by the given information: %/ The current working directory. %~ The current working directory, but with one's home directory represented by `~' and other users' home directories represented by `~user' as per Filename substitution. `~user' substitution happens only if the shell has already used `~user' in a pathname in the current session. %c[[0]n], %.[[0]n] The trailing component of the current working directory, or n trailing components if a digit n is given. If n begins with `0', the number of skipped components precede the trailing component(s) in the format `/<skipped>trailing'. If the ellipsis shell variable is set, skipped components are represented by an ellipsis so the whole becomes `...trailing'. `~' substitution is done as in `%~' above, but the `~' component is ignored when counting trailing components. %C Like %c, but without `~' substitution. %h, %!, ! The current history event number. %M The full hostname. %m The hostname up to the first `.'. %S (%s) Start (stop) standout mode. %B (%b) Start (stop) boldfacing mode. %U (%u) Start (stop) underline mode. %t, %@ The time of day in 12-hour AM/PM format. %T Like `%t', but in 24-hour format (but see the ampm shell variable). %p The `precise' time of day in 12-hour AM/PM format, with seconds. %P Like `%p', but in 24-hour format (but see the ampm shell variable). \c c is parsed as in bindkey. ^c c is parsed as in bindkey. %% A single `%'. %n The user name. %N The effective user name. %j The number of jobs. %d The weekday in `Day' format. %D The day in `dd' format. %w The month in `Mon' format. %W The month in `mm' format. %y The year in `yy' format. %Y The year in `yyyy' format. %l The shell's tty. %L Clears from the end of the prompt to end of the display or the end of the line. %$ Expands the shell or environment variable name immediately after the `$'. %# `>' (or the first character of the promptchars shell variable) for normal users, `#' (or the second character of promptchars) for the superuser. %{string%} Includes string as a literal escape sequence. It should be used only to change terminal attributes and should not move the cursor location. This cannot be the last sequence in prompt. %? The return code of the command executed just before the prompt. %R In prompt2, the status of the parser. In prompt3, the corrected string. In history, the history string. `%B', `%S', `%U' and `%{string%}' are available in only eight- bit-clean shells; see the version shell variable. The bold, standout and underline sequences are often used to distinguish a superuser shell. For example, > set prompt = "%m [%h] %B[%@]%b [%/] you rang? " tut [37] [2:54pm] [/usr/accts/sys] you rang? _ If `%t', `%@', `%T', `%p', or `%P' is used, and noding is not set, then print `DING!' on the change of hour (i.e, `:00' minutes) instead of the actual time. Set by default to `%# ' in interactive shells. prompt2 (+) The string with which to prompt in while and foreach loops and after lines ending in `\'. The same format sequences may be used as in prompt (q.v.); note the variable meaning of `%R'. Set by default to `%R? ' in interactive shells. prompt3 (+) The string with which to prompt when confirming automatic spelling correction. The same format sequences may be used as in prompt (q.v.); note the variable meaning of `%R'. Set by default to `CORRECT>%R (y|n|e|a)? ' in interactive shells. promptchars (+) If set (to a two-character string), the `%#' formatting sequence in the prompt shell variable is replaced with the first character for normal users and the second character for the superuser. pushdtohome (+) If set, pushd without arguments does `pushd ~', like cd. pushdsilent (+) If set, pushd and popd do not print the directory stack. recexact (+) If set, completion completes on an exact match even if a longer match is possible. recognize_only_executables (+) If set, command listing displays only files in the path that are executable. Slow. rmstar (+) If set, the user is prompted before `rm *' is executed. rprompt (+) The string to print on the right-hand side of the screen (after the command input) when the prompt is being displayed on the left. It recognizes the same formatting characters as prompt. It will automatically disappear and reappear as necessary, to ensure that command input isn't obscured, and will appear only if the prompt, command input, and itself will fit together on the first line. If edit isn't set, then rprompt will be printed after the prompt and before the command input. savedirs (+) If set, the shell does `dirs -S' before exiting. If the first word is set to a number, at most that many directory stack entries are saved. savehist If set, the shell does `history -S' before exiting. If the first word is set to a number, at most that many lines are saved. (The number should be less than or equal to the number history entries; if it is set to greater than the number of history settings, only history entries will be saved) If the second word is set to `merge', the history list is merged with the existing history file instead of replacing it (if there is one) and sorted by time stamp and the most recent events are retained. If the second word of savehist is `merge' and the third word is set to `lock', the history file update will be serialized with other shell sessions that would possibly like to merge history at exactly the same time. (+) sched (+) The format in which the sched builtin command prints scheduled events; if not given, `%h\t%T\t%R\n' is used. The format sequences are described above under prompt; note the variable meaning of `%R'. shell The file in which the shell resides. This is used in forking shells to interpret files which have execute bits set, but which are not executable by the system. (See the description of Builtin and non-builtin command execution.) Initialized to the (system-dependent) home of the shell. shlvl (+) The number of nested shells. Reset to 1 in login shells. See also loginsh. status The exit status from the last command or backquote expansion, or any command in a pipeline is propagated to status. (This is also the default csh behavior.) This default does not match what POSIX mandates (to return the status of the last command only). To match the POSIX behavior, you need to unset anyerror. If the anyerror variable is unset, the exit status of a pipeline is determined only from the last command in the pipeline, and the exit status of a backquote expansion is not propagated to status. If a command terminated abnormally, then 0200 is added to the status. Builtin commands which fail return exit status `1', all other builtin commands return status `0'. symlinks (+) Can be set to several different values to control symbolic link (`symlink') resolution: If set to `chase', whenever the current directory changes to a directory containing a symbolic link, it is expanded to the real name of the directory to which the link points. This does not work for the user's home directory; this is a bug. If set to `ignore', the shell tries to construct a current directory relative to the current directory before the link was crossed. This means that cding through a symbolic link and then `cd ..'ing returns one to the original directory. This affects only builtin commands and filename completion. If set to `expand', the shell tries to fix symbolic links by actually expanding arguments which look like path names. This affects any command, not just builtins. Unfortunately, this does not work for hard-to-recognize filenames, such as those embedded in command options. Expansion may be prevented by quoting. While this setting is usually the most convenient, it is sometimes misleading and sometimes confusing when it fails to recognize an argument which should be expanded. A compromise is to use `ignore' and use the editor command normalize-path (bound by default to ^X-n) when necessary. Some examples are in order. First, let's set up some play directories: > cd /tmp > mkdir from from/src to > ln -s from/src to/dst Here's the behavior with symlinks unset, > cd /tmp/to/dst; echo $cwd /tmp/to/dst > cd ..; echo $cwd /tmp/from here's the behavior with symlinks set to `chase', > cd /tmp/to/dst; echo $cwd /tmp/from/src > cd ..; echo $cwd /tmp/from here's the behavior with symlinks set to `ignore', > cd /tmp/to/dst; echo $cwd /tmp/to/dst > cd ..; echo $cwd /tmp/to and here's the behavior with symlinks set to `expand'. > cd /tmp/to/dst; echo $cwd /tmp/to/dst > cd ..; echo $cwd /tmp/to > cd /tmp/to/dst; echo $cwd /tmp/to/dst > cd ".."; echo $cwd /tmp/from > /bin/echo .. /tmp/to > /bin/echo ".." .. Note that `expand' expansion 1) works just like `ignore' for builtins like cd, 2) is prevented by quoting, and 3) happens before filenames are passed to non-builtin commands. tcsh (+) The version number of the shell in the format `R.VV.PP', where `R' is the major release number, `VV' the current version and `PP' the patchlevel. term The terminal type. Usually set in ~/.login as described under Startup and shutdown. time If set to a number, then the time builtin (q.v.) executes automatically after each command which takes more than that many CPU seconds. If there is a second word, it is used as a format string for the output of the time builtin. (u) The following sequences may be used in the format string: %U The time the process spent in user mode in cpu seconds. %S The time the process spent in kernel mode in cpu seconds. %E The elapsed (wall clock) time in seconds. %P The CPU percentage computed as (%U + %S) / %E. %W Number of times the process was swapped. %X The average amount in (shared) text space used in Kbytes. %D The average amount in (unshared) data/stack space used in Kbytes. %K The total space used (%X + %D) in Kbytes. %M The maximum memory the process had in use at any time in Kbytes. %F The number of major page faults (page needed to be brought from disk). %R The number of minor page faults. %I The number of input operations. %O The number of output operations. %r The number of socket messages received. %s The number of socket messages sent. %k The number of signals received. %w The number of voluntary context switches (waits). %c The number of involuntary context switches. Only the first four sequences are supported on systems without BSD resource limit functions. The default time format is `%Uu %Ss %E %P %X+%Dk %I+%Oio %Fpf+%Ww' for systems that support resource usage reporting and `%Uu %Ss %E %P' for systems that do not. Under Sequent's DYNIX/ptx, %X, %D, %K, %r and %s are not available, but the following additional sequences are: %Y The number of system calls performed. %Z The number of pages which are zero-filled on demand. %i The number of times a process's resident set size was increased by the kernel. %d The number of times a process's resident set size was decreased by the kernel. %l The number of read system calls performed. %m The number of write system calls performed. %p The number of reads from raw disk devices. %q The number of writes to raw disk devices. and the default time format is `%Uu %Ss %E %P %I+%Oio %Fpf+%Ww'. Note that the CPU percentage can be higher than 100% on multi-processors. tperiod (+) The period, in minutes, between executions of the periodic special alias. tty (+) The name of the tty, or empty if not attached to one. uid (+) The user's real user ID. user The user's login name. verbose If set, causes the words of each command to be printed, after history substitution (if any). Set by the -v command line option. version (+) The version ID stamp. It contains the shell's version number (see tcsh), origin, release date, vendor, operating system and machine (see VENDOR, OSTYPE and MACHTYPE) and a comma-separated list of options which were set at compile time. Options which are set by default in the distribution are noted. 8b The shell is eight bit clean; default 7b The shell is not eight bit clean wide The shell is multibyte encoding clean (like UTF-8) nls The system's NLS is used; default for systems with NLS lf Login shells execute /etc/csh.login before instead of after /etc/csh.cshrc and ~/.login before instead of after ~/.tcshrc and ~/.history. dl `.' is put last in path for security; default nd `.' is omitted from path for security vi vi(1)-style editing is the default rather than emacs(1)-style dtr Login shells drop DTR when exiting bye bye is a synonym for logout and log is an alternate name for watchlog al autologout is enabled; default kan Kanji is used if appropriate according to locale settings, unless the nokanji shell variable is set sm The system's malloc(3) is used hb The `#!<program> <args>' convention is emulated when executing shell scripts ng The newgrp builtin is available rh The shell attempts to set the REMOTEHOST environment variable afs The shell verifies your password with the kerberos server if local authentication fails. The afsuser shell variable or the AFSUSER environment variable override your local username if set. An administrator may enter additional strings to indicate differences in the local version. vimode (+) If unset, various key bindings change behavior to be more emacs(1)-style: word boundaries are determined by wordchars versus other characters. If set, various key bindings change behavior to be more vi(1)-style: word boundaries are determined by wordchars versus whitespace versus other characters; cursor behavior depends upon current vi mode (command, delete, insert, replace). This variable is unset by bindkey -e and set by bindkey -v. vimode may be explicitly set or unset by the user after those bindkey operations if required. visiblebell (+) If set, a screen flash is used rather than the audible bell. See also nobeep. watch (+) A list of user/terminal pairs to watch for logins and logouts. If either the user is `any' all terminals are watched for the given user and vice versa. Setting watch to `(any any)' watches all users and terminals. For example, set watch = (george ttyd1 any console $user any) reports activity of the user `george' on ttyd1, any user on the console, and oneself (or a trespasser) on any terminal. Logins and logouts are checked every 10 minutes by default, but the first word of watch can be set to a number to check every so many minutes. For example, set watch = (1 any any) reports any login/logout once every minute. For the impatient, the log builtin command triggers a watch report at any time. All current logins are reported (as with the log builtin) when watch is first set. The who shell variable controls the format of watch reports. who (+) The format string for watch messages. The following sequences are replaced by the given information: %n The name of the user who logged in/out. %a The observed action, i.e., `logged on', `logged off' or `replaced olduser on'. %l The terminal (tty) on which the user logged in/out. %M The full hostname of the remote host, or `local' if the login/logout was from the local host. %m The hostname of the remote host up to the first `.'. The full name is printed if it is an IP address or an X Window System display. %M and %m are available on only systems that store the remote hostname in /etc/utmp. If unset, `%n has %a %l from %m.' is used, or `%n has %a %l.' on systems which don't store the remote hostname. wordchars (+) A list of non-alphanumeric characters to be considered part of a word by the forward-word, backward-word etc., editor commands. If unset, the default value is determined based on the state of vimode: if vimode is unset, `*?_-.[]~=' is used as the default; if vimode is set, `_' is used as the default. ENVIRONMENT AFSUSER (+) Equivalent to the afsuser shell variable. COLUMNS The number of columns in the terminal. See Terminal management. DISPLAY Used by X Window System (see X(1)). If set, the shell does not set autologout (q.v.). EDITOR The pathname to a default editor. Used by the run-fg-editor editor command if the the editors shell variable is unset. See also the VISUAL environment variable. GROUP (+) Equivalent to the group shell variable. HOME Equivalent to the home shell variable. HOST (+) Initialized to the name of the machine on which the shell is running, as determined by the gethostname(2) system call. HOSTTYPE (+) Initialized to the type of machine on which the shell is running, as determined at compile time. This variable is obsolete and will be removed in a future version. HPATH (+) A colon-separated list of directories in which the run-help editor command looks for command documentation. LANG Gives the preferred character environment. See Native Language System support. LC_CTYPE If set, only ctype character handling is changed. See Native Language System support. LINES The number of lines in the terminal. See Terminal management. LS_COLORS The format of this variable is reminiscent of the termcap(5) file format; a colon-separated list of expressions of the form "xx=string", where "xx" is a two-character variable name. The variables with their associated defaults are: no 0 Normal (non-filename) text fi 0 Regular file di 01;34 Directory ln 01;36 Symbolic link pi 33 Named pipe (FIFO) so 01;35 Socket do 01;35 Door bd 01;33 Block device cd 01;32 Character device ex 01;32 Executable file mi (none) Missing file (defaults to fi) or (none) Orphaned symbolic link (defaults to ln) lc ^[[ Left code rc m Right code ec (none) End code (replaces lc+no+rc) You need to include only the variables you want to change from the default. File names can also be colorized based on filename extension. This is specified in the LS_COLORS variable using the syntax "*ext=string". For example, using ISO 6429 codes, to color all C-language source files blue you would specify "*.c=34". This would color all files ending in .c in blue (34) color. Control characters can be written either in C-style-escaped notation, or in stty-like ^-notation. The C-style notation adds ^[ for Escape, _ for a normal space character, and ? for Delete. In addition, the ^[ escape character can be used to override the default interpretation of ^[, ^, : and =. Each file will be written as <lc> <color-code> <rc> <filename> <ec>. If the <ec> code is undefined, the sequence <lc> <no> <rc> will be used instead. This is generally more convenient to use, but less general. The left, right and end codes are provided so you don't have to type common parts over and over again and to support weird terminals; you will generally not need to change them at all unless your terminal does not use ISO 6429 color sequences but a different system. If your terminal does use ISO 6429 color codes, you can compose the type codes (i.e., all except the lc, rc, and ec codes) from numerical commands separated by semicolons. The most common commands are: 0 to restore default color 1 for brighter colors 4 for underlined text 5 for flashing text 30 for black foreground 31 for red foreground 32 for green foreground 33 for yellow (or brown) foreground 34 for blue foreground 35 for purple foreground 36 for cyan foreground 37 for white (or gray) foreground 40 for black background 41 for red background 42 for green background 43 for yellow (or brown) background 44 for blue background 45 for purple background 46 for cyan background 47 for white (or gray) background Not all commands will work on all systems or display devices. A few terminal programs do not recognize the default end code properly. If all text gets colorized after you do a directory listing, try changing the no and fi codes from 0 to the numerical codes for your standard fore- and background colors. MACHTYPE (+) The machine type (microprocessor class or machine model), as determined at compile time. NOREBIND (+) If set, printable characters are not rebound to self-insert- command. See Native Language System support. OSTYPE (+) The operating system, as determined at compile time. PATH A colon-separated list of directories in which to look for executables. Equivalent to the path shell variable, but in a different format. PWD (+) Equivalent to the cwd shell variable, but not synchronized to it; updated only after an actual directory change. REMOTEHOST (+) The host from which the user has logged in remotely, if this is the case and the shell is able to determine it. Set only if the shell was so compiled; see the version shell variable. SHLVL (+) Equivalent to the shlvl shell variable. SYSTYPE (+) The current system type. (Domain/OS only) TERM Equivalent to the term shell variable. TERMCAP The terminal capability string. See Terminal management. USER Equivalent to the user shell variable. VENDOR (+) The vendor, as determined at compile time. VISUAL The pathname to a default full-screen editor. Used by the run- fg-editor editor command if the the editors shell variable is unset. See also the EDITOR environment variable. FILES /etc/csh.cshrc Read first by every shell. ConvexOS, Stellix and Intel use /etc/cshrc and NeXTs use /etc/cshrc.std. A/UX, AMIX, Cray and IRIX have no equivalent in csh(1), but read this file in tcsh anyway. Solaris 2.x does not have it either, but tcsh reads /etc/.cshrc. (+) /etc/csh.login Read by login shells after /etc/csh.cshrc. ConvexOS, Stellix and Intel use /etc/login, NeXTs use /etc/login.std, Solaris 2.x uses /etc/.login and A/UX, AMIX, Cray and IRIX use /etc/cshrc. ~/.tcshrc (+) Read by every shell after /etc/csh.cshrc or its equivalent. ~/.cshrc Read by every shell, if ~/.tcshrc doesn't exist, after /etc/csh.cshrc or its equivalent. This manual uses `~/.tcshrc' to mean `~/.tcshrc or, if ~/.tcshrc is not found, ~/.cshrc'. ~/.history Read by login shells after ~/.tcshrc if savehist is set, but see also histfile. ~/.login Read by login shells after ~/.tcshrc or ~/.history. The shell may be compiled to read ~/.login before instead of after ~/.tcshrc and ~/.history; see the version shell variable. ~/.cshdirs (+) Read by login shells after ~/.login if savedirs is set, but see also dirsfile. /etc/csh.logout Read by login shells at logout. ConvexOS, Stellix and Intel use /etc/logout and NeXTs use /etc/logout.std. A/UX, AMIX, Cray and IRIX have no equivalent in csh(1), but read this file in tcsh anyway. Solaris 2.x does not have it either, but tcsh reads /etc/.logout. (+) ~/.logout Read by login shells at logout after /etc/csh.logout or its equivalent. /bin/sh Used to interpret shell scripts not starting with a `#'. /tmp/sh* Temporary file for `<<'. /etc/passwd Source of home directories for `~name' substitutions. The order in which startup files are read may differ if the shell was so compiled; see Startup and shutdown and the version shell variable. NEW FEATURES (+) This manual describes tcsh as a single entity, but experienced csh(1) users will want to pay special attention to tcsh's new features. A command-line editor, which supports emacs(1)-style or vi(1)-style key bindings. See The command-line editor and Editor commands. Programmable, interactive word completion and listing. See Completion and listing and the complete and uncomplete builtin commands. Spelling correction (q.v.) of filenames, commands and variables. Editor commands (q.v.) which perform other useful functions in the middle of typed commands, including documentation lookup (run-help), quick editor restarting (run-fg-editor) and command resolution (which- command). An enhanced history mechanism. Events in the history list are time- stamped. See also the history command and its associated shell variables, the previously undocumented `#' event specifier and new modifiers under History substitution, the *-history, history-search-*, i-search-*, vi-search-* and toggle-literal-history editor commands and the histlit shell variable. Enhanced directory parsing and directory stack handling. See the cd, pushd, popd and dirs commands and their associated shell variables, the description of Directory stack substitution, the dirstack, owd and symlinks shell variables and the normalize-command and normalize-path editor commands. Negation in glob-patterns. See Filename substitution. New File inquiry operators (q.v.) and a filetest builtin which uses them. A variety of Automatic, periodic and timed events (q.v.) including scheduled events, special aliases, automatic logout and terminal locking, command timing and watching for logins and logouts. Support for the Native Language System (see Native Language System support), OS variant features (see OS variant support and the echo_style shell variable) and system-dependent file locations (see FILES). Extensive terminal-management capabilities. See Terminal management. New builtin commands including builtins, hup, ls-F, newgrp, printenv, which and where (q.v.). New variables that make useful information easily available to the shell. See the gid, loginsh, oid, shlvl, tcsh, tty, uid and version shell variables and the HOST, REMOTEHOST, VENDOR, OSTYPE and MACHTYPE environment variables. A new syntax for including useful information in the prompt string (see prompt), and special prompts for loops and spelling correction (see prompt2 and prompt3). Read-only variables. See Variable substitution. BUGS When a suspended command is restarted, the shell prints the directory it started in if this is different from the current directory. This can be misleading (i.e., wrong) as the job may have changed directories internally. Shell builtin functions are not stoppable/restartable. Command sequences of the form `a ; b ; c' are also not handled gracefully when stopping is attempted. If you suspend `b', the shell will then immediately execute `c'. This is especially noticeable if this expansion results from an alias. It suffices to place the sequence of commands in ()'s to force it to a subshell, i.e., `( a ; b ; c )'. Control over tty output after processes are started is primitive; perhaps this will inspire someone to work on a good virtual terminal interface. In a virtual terminal interface much more interesting things could be done with output control. Alias substitution is most often used to clumsily simulate shell procedures; shell procedures should be provided rather than aliases. Control structures should be parsed rather than being recognized as built-in commands. This would allow control commands to be placed anywhere, to be combined with `|', and to be used with `&' and `;' metasyntax. foreach doesn't ignore here documents when looking for its end. It should be possible to use the `:' modifiers on the output of command substitutions. The screen update for lines longer than the screen width is very poor if the terminal cannot move the cursor up (i.e., terminal type `dumb'). HPATH and NOREBIND don't need to be environment variables. Glob-patterns which do not use `?', `*' or `[]' or which use `{}' or `~' are not negated correctly. The single-command form of if does output redirection even if the expression is false and the command is not executed. ls-F includes file identification characters when sorting filenames and does not handle control characters in filenames well. It cannot be interrupted. Command substitution supports multiple commands and conditions, but not cycles or backward gotos. Report bugs at https://bugs.astron.com/, preferably with fixes. If you want to help maintain and test tcsh, add yourself to the mailing list in https://mailman.astron.com/. THE T IN TCSH In 1964, DEC produced the PDP-6. The PDP-10 was a later re- implementation. It was re-christened the DECsystem-10 in 1970 or so when DEC brought out the second model, the KI10. TENEX was created at Bolt, Beranek & Newman (a Cambridge, Massachusetts think tank) in 1972 as an experiment in demand-paged virtual memory operating systems. They built a new pager for the DEC PDP-10 and created the OS to go with it. It was extremely successful in academia. In 1975, DEC brought out a new model of the PDP-10, the KL10; they intended to have only a version of TENEX, which they had licensed from BBN, for the new box. They called their version TOPS-20 (their capitalization is trademarked). A lot of TOPS-10 users (`The OPerating System for PDP-10') objected; thus DEC found themselves supporting two incompatible systems on the same hardware--but then there were 6 on the PDP-11! TENEX, and TOPS-20 to version 3, had command completion via a user- code-level subroutine library called ULTCMD. With version 3, DEC moved all that capability and more into the monitor (`kernel' for you Unix types), accessed by the COMND% JSYS (`Jump to SYStem' instruction, the supervisor call mechanism [are my IBM roots also showing?]). The creator of tcsh was impressed by this feature and several others of TENEX and TOPS-20, and created a version of csh which mimicked them. LIMITATIONS The system limits argument lists to ARG_MAX characters. The number of arguments to a command which involves filename expansion is limited to 1/6th the number of characters allowed in an argument list. Command substitutions may substitute no more characters than are allowed in an argument list. To detect looping, the shell restricts the number of alias substitutions on a single line to 20. SEE ALSO csh(1), emacs(1), ls(1), newgrp(1), sh(1), setpath(1), stty(1), su(1), tset(1), vi(1), x(1), access(2), execve(2), fork(2), killpg(2), pipe(2), setrlimit(2), sigvec(2), stat(2), umask(2), vfork(2), wait(2), malloc(3), setlocale(3), tty(4), a.out(5), termcap(5), environ(7), termio(7), Introduction to the C Shell VERSION This manual documents tcsh 6.21.00 (Astron) 2019-05-08. AUTHORS William Joy Original author of csh(1) J.E. Kulp, IIASA, Laxenburg, Austria Job control and directory stack features Ken Greer, HP Labs, 1981 File name completion Mike Ellis, Fairchild, 1983 Command name recognition/completion Paul Placeway, Ohio State CIS Dept., 1983-1993 Command line editor, prompt routines, new glob syntax and numerous fixes and speedups Karl Kleinpaste, CCI 1983-4 Special aliases, directory stack extraction stuff, login/logout watch, scheduled events, and the idea of the new prompt format Rayan Zachariassen, University of Toronto, 1984 ls-F and which builtins and numerous bug fixes, modifications and speedups Chris Kingsley, Caltech Fast storage allocator routines Chris Grevstad, TRW, 1987 Incorporated 4.3BSD csh into tcsh Christos S. Zoulas, Cornell U. EE Dept., 1987-94 Ports to HPUX, SVR2 and SVR3, a SysV version of getwd.c, SHORT_STRINGS support and a new version of sh.glob.c James J Dempsey, BBN, and Paul Placeway, OSU, 1988 A/UX port Daniel Long, NNSC, 1988 wordchars Patrick Wolfe, Kuck and Associates, Inc., 1988 vi mode cleanup David C Lawrence, Rensselaer Polytechnic Institute, 1989 autolist and ambiguous completion listing Alec Wolman, DEC, 1989 Newlines in the prompt Matt Landau, BBN, 1989 ~/.tcshrc Ray Moody, Purdue Physics, 1989 Magic space bar history expansion Mordechai ????, Intel, 1989 printprompt() fixes and additions Kazuhiro Honda, Dept. of Computer Science, Keio University, 1989 Automatic spelling correction and prompt3 Per Hedeland, Ellemtel, Sweden, 1990- Various bugfixes, improvements and manual updates Hans J. Albertsson (Sun Sweden) ampm, settc and telltc Michael Bloom Interrupt handling fixes Michael Fine, Digital Equipment Corp Extended key support Eric Schnoebelen, Convex, 1990 Convex support, lots of csh bug fixes, save and restore of directory stack Ron Flax, Apple, 1990 A/UX 2.0 (re)port Dan Oscarsson, LTH Sweden, 1990 NLS support and simulated NLS support for non NLS sites, fixes Johan Widen, SICS Sweden, 1990 shlvl, Mach support, correct-line, 8-bit printing Matt Day, Sanyo Icon, 1990 POSIX termio support, SysV limit fixes Jaap Vermeulen, Sequent, 1990-91 Vi mode fixes, expand-line, window change fixes, Symmetry port Martin Boyer, Institut de recherche d'Hydro-Quebec, 1991 autolist beeping options, modified the history search to search for the whole string from the beginning of the line to the cursor. Scott Krotz, Motorola, 1991 Minix port David Dawes, Sydney U. Australia, Physics Dept., 1991 SVR4 job control fixes Jose Sousa, Interactive Systems Corp., 1991 Extended vi fixes and vi delete command Marc Horowitz, MIT, 1991 ANSIfication fixes, new exec hashing code, imake fixes, where Bruce Sterling Woodcock, sterling@netcom.com, 1991-1995 ETA and Pyramid port, Makefile and lint fixes, ignoreeof=n addition, and various other portability changes and bug fixes Jeff Fink, 1992 complete-word-fwd and complete-word-back Harry C. Pulley, 1992 Coherent port Andy Phillips, Mullard Space Science Lab U.K., 1992 VMS-POSIX port Beto Appleton, IBM Corp., 1992 Walking process group fixes, csh bug fixes, POSIX file tests, POSIX SIGHUP Scott Bolte, Cray Computer Corp., 1992 CSOS port Kaveh R. Ghazi, Rutgers University, 1992 Tek, m88k, Titan and Masscomp ports and fixes. Added autoconf support. Mark Linderman, Cornell University, 1992 OS/2 port Mika Liljeberg, liljeber@kruuna.Helsinki.FI, 1992 Linux port Tim P. Starrin, NASA Langley Research Center Operations, 1993 Read-only variables Dave Schweisguth, Yale University, 1993-4 New man page and tcsh.man2html Larry Schwimmer, Stanford University, 1993 AFS and HESIOD patches Luke Mewburn, RMIT University, 1994-6 Enhanced directory printing in prompt, added ellipsis and rprompt. Edward Hutchins, Silicon Graphics Inc., 1996 Added implicit cd. Martin Kraemer, 1997 Ported to Siemens Nixdorf EBCDIC machine Amol Deshpande, Microsoft, 1997 Ported to WIN32 (Windows/95 and Windows/NT); wrote all the missing library and message catalog code to interface to Windows. Taga Nayuta, 1998 Color ls additions. THANKS TO Bryan Dunlap, Clayton Elwell, Karl Kleinpaste, Bob Manson, Steve Romig, Diana Smetters, Bob Sutterfield, Mark Verber, Elizabeth Zwicky and all the other people at Ohio State for suggestions and encouragement All the people on the net, for putting up with, reporting bugs in, and suggesting new additions to each and every version Richard M. Alderson III, for writing the `T in tcsh' section Astron 6.21.00 8 May 2019 TCSH(1)
tcsh - C shell with file name completion and command line editing
tcsh [-bcdefFimnqstvVxX] [-Dname[=value]] [arg ...] tcsh -l
null
null
dd
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 to n bytes, 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. fillchar=c When padding a block in conversion mode or due to use of noerror and sync modes, fill with the specified ASCII character, rather than using a space or NUL. 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. iflag=value[,value ...] Where value is one of the symbols from the following list. fullblock Reading from the input file may not obtain a full block. When a read returns short, continue reading to fill the block. Without this flag, count limits the number of times read(2) is called on the input rather than the number of blocks copied in full. May not be combined with conv=sync. direct Set F_NOCACHE on the input file to make reads bypass any local caching. iseek=n Seek on the input file n blocks. This is synonymous with skip=n. 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 seeked past (see the oseek operand), the output file is truncated at that point. oflag=value[,value ...] Where value is one of the symbols from the following list. fsync Set the O_FSYNC flag on the output file to make writes synchronous. sync Set the O_SYNC flag on the output file to make writes synchronous. This is synonymous with the fsync value. direct Set F_NOCACHE on the output file to make writes bypass any local caching. oseek=n Seek on the output file n blocks. This is synonymous with seek=n. seek=n Seek n blocks from the beginning of the output before copying. On non-tape devices, an 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, an 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. speed=n Limit the copying speed to n bytes per second. status=value Where value is one of the symbols from the following list. noxfer Do not print the transfer statistics as the last line of status output. none Do not print the status output. Error messages are shown; informational messages are not. progress Print basic transfer statistics once per second. 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 EBCDIC 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 AT&T System V UNIX. The value oldascii specifies the one used in historic AT&T UNIX and pre-4.3BSD-Reno systems. block Treats the input as a sequence of newline or end-of- file 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. 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 UNIX and pre-4.3BSD-Reno systems. fsync Perform an fsync(2) on the output file before closing it. lcase Transform uppercase characters into lowercase characters. pareven, parnone, parodd, parset Output data with the specified parity. The parity bit on input is stripped unless EBCDIC to ASCII conversions is also specified. 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 fillchar option is specified, the fill character provided on the command line will override the automatic selection of the fill character. 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. sparse If one or more output blocks would consist solely of NUL bytes, try to seek the output file by the required space instead of filling them with NULs, resulting in a sparse file. 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 or speed are specified, a decimal, octal, or hexadecimal number of bytes is expected. If the number ends with a “b”, “k”, “m”, “g”, “t”, “p”, or “w”, the number is multiplied by 512, 1024 (1K), 1048576 (1M), 1073741824 (1G), 1099511627776 (1T), 1125899906842624 (1P) 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. EXIT STATUS The dd utility exits 0 on success, and >0 if an error occurs.
dd – convert and copy a file
dd [operands ...]
null
Check that a disk drive contains no bad blocks: dd if=/dev/ada0 of=/dev/null bs=1m Do a refresh of a disk drive, in order to prevent presently recoverable read errors from progressing into unrecoverable read errors: dd if=/dev/ada0 of=/dev/ada0 bs=1m Remove parity bit from a file: dd if=file conv=parnone of=file.txt Check for (even) parity errors on a file: dd if=file conv=pareven | cmp -x - file To create an image of a Mode-1 CD-ROM, which is a commonly used format for data CD-ROM disks, use a block size of 2048 bytes: dd if=/dev/cd0 of=filename.iso bs=2048 Write a filesystem image to a memory stick, padding the end with zeros, if necessary, to a 1MiB boundary: dd if=memstick.img of=/dev/da0 bs=1m conv=noerror,sync SEE ALSO cp(1), tr(1) STANDARDS The dd utility is expected to be a superset of the IEEE Std 1003.2 (“POSIX.2”) standard. The files and status operands and the ascii, ebcdic, ibm, oldascii, oldebcdic and oldibm values are extensions to the POSIX standard. HISTORY A dd command appeared in Version 5 AT&T UNIX. macOS 14.5 May 19, 2021 macOS 14.5
mkdir
The mkdir utility creates the directories named as operands, in the order specified, using mode “rwxrwxrwx” (0777) as modified by the current umask(2). The options are as follows: -m mode Set the file permission bits of the final created directory to the specified mode. The mode argument can be in any of the formats specified to the chmod(1) command. If a symbolic mode is specified, the operation characters ‘+’ and ‘-’ are interpreted relative to an initial mode of “a=rwx”. -p Create intermediate directories as required. If this option is not specified, the full path prefix of each operand must already exist. On the other hand, with this option specified, no error will be reported if a directory given as an operand already exists. Intermediate directories are created with permission bits of “rwxrwxrwx” (0777) as modified by the current umask, plus write and search permission for the owner. -v Be verbose when creating directories, listing them as they are created. The user must have write permission in the parent directory. EXIT STATUS The mkdir utility exits 0 on success, and >0 if an error occurs.
mkdir – make directories
mkdir [-pv] [-m mode] directory_name ...
null
Create a directory named foobar: $ mkdir foobar Create a directory named foobar and set its file mode to 700: $ mkdir -m 700 foobar Create a directory named cow/horse/monkey, creating any non-existent intermediate directories as necessary: $ mkdir -p cow/horse/monkey COMPATIBILITY The -v option is non-standard and its use in scripts is not recommended. SEE ALSO rmdir(1) STANDARDS The mkdir utility is expected to be IEEE Std 1003.2 (“POSIX.2”) compatible. HISTORY A mkdir command appeared in Version 1 AT&T UNIX. macOS 14.5 March 15, 2013 macOS 14.5
ksh
Ksh is a command and programming language that executes commands read from a terminal or a file. Rksh is a restricted version of the command interpreter ksh; it is used to set up login names and execution environments whose capabilities are more controlled than those of the standard shell. Rpfksh is a profile shell version of the command interpreter ksh; it is used to to execute commands with the attributes specified by the user's profiles (see pfexec(1)). See Invocation below for the meaning of arguments to the shell. Definitions. A metacharacter is one of the following characters: ; & ( ) ⎪ < > new-line space tab A blank is a tab or a space. An identifier is a sequence of letters, digits, or underscores starting with a letter or underscore. Identifiers are used as components of variable names. A vname is a sequence of one or more identifiers separated by a . and optionally preceded by a .. Vnames are used as function and variable names. A word is a sequence of characters from the character set defined by the current locale, excluding non-quoted metacharacters. A command is a sequence of characters in the syntax of the shell language. The shell reads each command and carries out the desired action either directly or by invoking separate utilities. A built-in command is a command that is carried out by the shell itself without creating a separate process. Some commands are built-in purely for convenience and are not documented here. Built-ins that cause side effects in the shell environment and built-ins that are found before performing a path search (see Execution below) are documented here. For historical reasons, some of these built-ins behave differently than other built-ins and are called special built-ins. Commands. A simple-command is a list of variable assignments (see Variable Assignments below) or a sequence of blank separated words which may be preceded by a list of variable assignments (see Environment below). The first word specifies the name of the command to be executed. Except as specified below, the remaining words are passed as arguments to the invoked command. The command name is passed as argument 0 (see exec(2)). The value of a simple-command is its exit status; 0-255 if it terminates normally; 256+signum if it terminates abnormally (the name of the signal corresponding to the exit status can be obtained via the -l option of the kill built-in utility). A pipeline is a sequence of one or more commands separated by ⎪. The standard output of each command but the last is connected by a pipe(2) to the standard input of the next command. Each command, except possibly the last, is run as a separate process; the shell waits for the last command to terminate. The exit status of a pipeline is the exit status of the last command unless the pipefail option is enabled. Each pipeline can be preceded by the reserved word ! which causes the exit status of the pipeline to become 0 if the exit status of the last command is non-zero, and 1 if the exit status of the last command is 0. A list is a sequence of one or more pipelines separated by ;, &, ⎪&, &&, or ⎪⎪, and optionally terminated by ;, &, or ⎪&. Of these five symbols, ;, &, and ⎪& have equal precedence, which is lower than that of && and ⎪⎪. The symbols && and ⎪⎪ also have equal precedence. A semicolon (;) causes sequential execution of the preceding pipeline; an ampersand (&) causes asynchronous execution of the preceding pipeline (i.e., the shell does not wait for that pipeline to finish). The symbol ⎪& causes asynchronous execution of the preceding pipeline with a two-way pipe established to the parent shell; the standard input and output of the spawned pipeline can be written to and read from by the parent shell by applying the redirection operators <& and >& with arg p to commands and by using -p option of the built-in commands read and print described later. The symbol && (⎪⎪) causes the list following it to be executed only if the preceding pipeline returns a zero (non-zero) value. One or more new-lines may appear in a list instead of a semicolon, to delimit a command. The first item of the first pipeline of a list that is a simple command not beginning with a redirection, and not occurring within a while, until, or if list, can be preceded by a semicolon. This semicolon is ignored unless the showme option is enabled as described with the set built-in below. A command is either a simple-command or one of the following. Unless otherwise stated, the value returned by a command is that of the last simple-command executed in the command. for vname [ in word ... ] ;do list ;done Each time a for command is executed, vname is set to the next word taken from the in word list. If in word ... is omitted, then the for command executes the do list once for each positional parameter that is set starting from 1 (see Parameter Expansion below). Execution ends when there are no more words in the list. for (( [expr1] ; [expr2] ; [expr3] )) ;do list ;done The arithmetic expression expr1 is evaluated first (see Arithmetic evaluation below). The arithmetic expression expr2 is repeatedly evaluated until it evaluates to zero and when non- zero, list is executed and the arithmetic expression expr3 evaluated. If any expression is omitted, then it behaves as if it evaluated to 1. select vname [ in word ... ] ;do list ;done A select command prints on standard error (file descriptor 2) the set of words, each preceded by a number. If in word ... is omitted, then the positional parameters starting from 1 are used instead (see Parameter Expansion below). The PS3 prompt is printed and a line is read from the standard input. If this line consists of the number of one of the listed words, then the value of the variable vname 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 variable vname is set to null. The contents of the line read from standard input is saved in the variable REPLY. The list is executed for each selection until a break or end-of-file is encountered. If the REPLY variable is set to null by the execution of list, then the selection list is printed before displaying the PS3 prompt for the next selection. case word in [ [(]pattern [ ⎪ pattern ] ... ) list ;; ] ... esac A case command executes the list associated with the first pattern that matches word. The form of the patterns is the same as that used for file-name generation (see File Name Generation below). The ;; operator causes execution of case to terminate. If ;& is used in place of ;; the next subsequent list, if any, is executed. if list ;then list [ ;elif list ;then list ] ... [ ;else list ] ;fi The list following if is executed and, if it returns a zero exit status, the list following the first then is executed. Otherwise, the list following elif is executed and, if its value is zero, the list following the next then is executed. Failing each successive elif list, the else list is executed. If the if list has non-zero exit status and there is no else list, then the if command returns a zero exit status. while list ;do list ;done until list ;do list ;done A while command repeatedly executes the while list and, if the exit status of the last command in the list is zero, executes the do list; otherwise the loop terminates. If no commands in the do list are executed, then the while command returns a zero exit status; until may be used in place of while to negate the loop termination test. ((expression)) The expression is evaluated using the rules for arithmetic evaluation described below. If the value of the arithmetic expression is non-zero, the exit status is 0, otherwise the exit status is 1. (list) Execute list in a separate environment. Note, that if two adjacent open parentheses are needed for nesting, a space must be inserted to avoid evaluation as an arithmetic command as described above. { list;} list is simply executed. Note that unlike the metacharacters ( and ), { and } are reserved words and must occur at the beginning of a line or after a ; in order to be recognized. [[ expression ]] Evaluates expression and returns a zero exit status when expression is true. See Conditional Expressions below, for a description of expression. function varname { list ;} varname () { list ;} Define a function which is referenced by varname. A function whose varname contains a . is called a discipline function and the portion of the varname preceding the last . must refer to an existing variable. The body of the function is the list of commands between { and }. A function defined with the function varname syntax can also be used as an argument to the . special built-in command to get the equivalent behavior as if the varname() syntax were used to define it. (See Functions below.) namespace identifier { list ;} Defines or uses the name space identifier and runs the commands in list in this name space. (See Name Spaces below.) & [ name [ arg... ] ] Causes subsequent list commands terminated by & to be placed in the background job pool name. If name is omitted a default unnamed pool is used. Commands in a named background pool may be executed remotely. time [ pipeline ] If pipeline is omitted the user and system time for the current shell and completed child processes is printed on standard error. Otherwise, pipeline is executed and the elapsed time as well as the user and system time are printed on standard error. The TIMEFORMAT variable may be set to a format string that specifies how the timing information should be displayed. See Shell Variables below for a description of the TIMEFORMAT variable. The following reserved words are recognized as reserved only when they are the first word of a command and are not quoted: if then else elif fi case esac for while until do done { } function select time [[ ]] ! Variable Assignments. One or more variable assignments can start a simple command or can be arguments to the typeset, enum, export, or readonly special built-in commands as well as to other declaration commands created as types. The syntax for an assignment is of the form: varname=word varname[word]=word No space is permitted between varname and the = or between = and word. varname=(assign_list) No space is permitted between varname and the =. The variable varname is unset before the assignment. An assign_list can be one of the following: word ... Indexed array assignment. [word]=word ... Associative array assignment. If preceded by typeset -a this will create an indexed array instead. assignment ... Compound variable assignment. This creates a compound variable varname with sub-variables of the form varname.name, where name is the name portion of assignment. The value of varname will contain all the assignment elements. Additional assignments made to sub-variables of varname will also be displayed as part of the value of varname. If no assignments are specified, varname will be a compound variable allowing subsequence child elements to be defined. typeset [options] assignment ... Nested variable assignment. Multiple assignments can be specified by separating each of them with a ;. The previous value is unset before the assignment. Other declaration commands such as readonly, enum, and other declaration commands can be used in place of typeset. . filename Include the assignment commands contained in filename. In addition, a += can be used in place of the = to signify adding to or appending to the previous value. When += is applied to an arithmetic type, word is evaluated as an arithmetic expression and added to the current value. When applied to a string variable, the value defined by word is appended to the value. For compound assignments, the previous value is not unset and the new values are appended to the current ones provided that the types are compatible. The right hand side of a variable assignment undergoes all the expansion listed below except word splitting, brace expansion, and file name generation. When the left hand side is an assignment is a compound variable and the right hand is the name of a compound variable, the compound variable on the right will be copied or appended to the compound variable on the left. Comments. A word beginning with # causes that word and all the following characters up to a new-line to be ignored. Aliasing. The first word of each command is replaced by the text of an alias if an alias for this word has been defined. An alias name consists of any number of characters excluding metacharacters, quoting characters, file expansion characters, parameter expansion and command substitution characters, the characters / and =. The replacement string can contain any valid shell script including the metacharacters listed above. The first word of each command in the replaced text, other than any that are in the process of being replaced, will be tested for aliases. If the last character of the alias value is a blank then the word following the alias will also be checked for alias substitution. Aliases can be used to redefine built-in commands but cannot be used to redefine the reserved words listed above. Aliases can be created and listed with the alias command and can be removed with the unalias command. Aliasing is performed when scripts are read, not while they are executed. Therefore, for an alias to take effect, the alias definition command has to be executed before the command which references the alias is read. The following aliases are compiled into the shell but can be unset or redefined: autoload=′typeset -fu′ command=′command ′ compound=′typeset -C′ fc=hist float=′typeset -lE′ functions=′typeset -f′ hash=′alias -t --′ history=′hist -l′ integer=′typeset -li′ nameref=′typeset -n′ nohup=′nohup ′ r=′hist -s′ redirect=′command exec′ source=′command .′ stop=′kill -s STOP′ suspend=′kill -s STOP $$′ times=′{ { time;} 2>&1;}′ type=′whence -v′ Tilde Substitution. After alias substitution is performed, each word is checked to see if it begins with an unquoted ∼. For tilde substitution, word also refers to the word portion of parameter expansion (see Parameter Expansion below). If it does, then the word up to a / is checked to see if it matches a user name in the password database (See getpwname(3).) If a match is found, the ∼ and the matched login name are replaced by the login directory of the matched user. If no match is found, the original text is left unchanged. A ∼ by itself, or in front of a /, is replaced by $HOME. A ∼ followed by a + or - is replaced by the value of $PWD and $OLDPWD respectively. In addition, when expanding a variable assignment, tilde substitution is attempted when the value of the assignment begins with a ∼, and when a ∼ appears after a :. The : also terminates a ∼ login name. Command Substitution. The standard output from a command list enclosed in parentheses preceded by a dollar sign ( $(list) ), or in a brace group preceded by a dollar sign ( ${ list;} ), or in a pair of grave accents (``) may be used as part or all of a word; trailing new-lines are removed. In the second case, the { and } are treated as a reserved words so that { must be followed by a blank and } must appear at the beginning of the line or follow a ;. In the third (obsolete) form, the string between the quotes is processed for special quoting characters before the command is executed (see Quoting below). The command substitution $(cat file) can be replaced by the equivalent but faster $(<file). The command substitution $(n<#) will expand to the current byte offset for file descriptor n. Except for the second form, the command list is run in a subshell so that no side effects are possible. For the second form, the final } will be recognized as a reserved word after any token. Arithmetic Substitution. An arithmetic expression enclosed in double parentheses preceded by a dollar sign ( $(()) ) is replaced by the value of the arithmetic expression within the double parentheses. Process Substitution. Each command argument of the form <(list) or >(list) will run process list asynchronously connected to some file in /dev/fd if this directory exists, or else a fifo a temporary directory. The name of this file will become the argument to the command. If the form with > is selected then writing on this file will provide input for list. If < is used, then the file passed as an argument will contain the output of the list process. For example, paste <(cut -f1 file1) <(cut -f3 file2) | tee >(process1) >(process2) 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, as well as putting it onto the standard output. Note that the file, which is passed as an argument to the command, is a UNIX pipe(2) so programs that expect to lseek(2) on the file will not work. Process substitution of the form <(list) can also be used with the < redirection operator which causes the output of list to be standard input or the input for whatever file descriptor is specified. Parameter Expansion. A parameter is a variable, one or more digits, or any of the characters ∗, @, #, ?, -, $, and !. A variable is denoted by a vname. To create a variable whose vname contains a ., a variable whose vname consists of everything before the last . must already exist. A variable has a value and zero or more attributes. Variables can be assigned values and attributes by using the typeset special built-in command. The attributes supported by the shell are described later with the typeset special built-in command. Exported variables pass values and attributes to the environment. The shell supports both indexed and associative arrays. An element of an array variable is referenced by a subscript. A subscript for an indexed array is denoted by an arithmetic expression (see Arithmetic evaluation below) between a [ and a ]. To assign values to an indexed array, use vname=(value ...) or set -A vname value ... . The value of all non-negative subscripts must be in the range of 0 through 4,194,303. A negative subscript is treated as an offset from the maximum current index +1 so that -1 refers to the last element. Indexed arrays can be declared with the -a option to typeset. Indexed arrays need not be declared. Any reference to a variable with a valid subscript is legal and an array will be created if necessary. An associative array is created with the -A option to typeset. A subscript for an associative array is denoted by a string enclosed between [ and ]. Referencing any array without a subscript is equivalent to referencing the array with subscript 0. The value of a variable may be assigned by writing: vname=value [ vname=value ] ... or vname[subscript]=value [ vname[subscript]=value ] ... Note that no space is allowed before or after the =. Attributes assigned by the typeset special built-in command apply to all elements of the array. An array element can be a simple variable, a compound variable or an array variable. An element of an indexed array can be either an indexed array or an associative array. An element of an associative array can also be either. To refer to an array element that is part of an array element, concatenate the subscript in brackets. For example, to refer to the foobar element of an associative array that is defined as the third element of the indexed array, use ${vname[3][foobar]} A nameref is a variable that is a reference to another variable. A nameref is created with the -n attribute of typeset. The value of the variable at the time of the typeset command becomes the variable that will be referenced whenever the nameref variable is used. The name of a nameref cannot contain a .. When a variable or function name contains a ., and the portion of the name up to the first . matches the name of a nameref, the variable referred to is obtained by replacing the nameref portion with the name of the variable referenced by the nameref. If a nameref is used as the index of a for loop, a name reference is established for each item in the list. A nameref provides a convenient way to refer to the variable inside a function whose name is passed as an argument to a function. For example, if the name of a variable is passed as the first argument to a function, the command typeset -n var=$1 inside the function causes references and assignments to var to be references and assignments to the variable whose name has been passed to the function. If any of the floating point attributes, -E, -F, or -X, or the integer attribute, -i, is set for vname, then the value is subject to arithmetic evaluation as described below. Positional parameters, parameters denoted by a number, may be assigned values with the set special built-in command. Parameter $0 is set from argument zero when the shell is invoked. The character $ is used to introduce substitutable parameters. ${parameter} The shell reads all the characters from ${ to the matching } as part of the same word even if it contains braces or metacharacters. The value, if any, of the parameter is substituted. The braces are required when parameter is followed by a letter, digit, or underscore that is not to be interpreted as part of its name, when the variable name contains a .. The braces are also required when a variable is subscripted unless it is part of an Arithmetic Expression or a Conditional Expression. If parameter is one or more digits then it is a positional parameter. A positional parameter of more than one digit must be enclosed in braces. If parameter is ∗ or @, then all the positional parameters, starting with $1, are substituted (separated by a field separator character). If an array vname with last subscript ∗ @, or for index arrays of the form sub1 .. sub2. is used, then the value for each of the elements between sub1 and sub2 inclusive (or all elements for ∗ and @) is substituted, separated by the first character of the value of IFS. ${#parameter} If parameter is ∗ or @, the number of positional parameters is substituted. Otherwise, the length of the value of the parameter is substituted. ${#vname[*]} ${#vname[@]} The number of elements in the array vname is substituted. ${@vname} Expands to the type name (See Type Variables below) or attributes of the variable referred to by vname. ${!vname} Expands to the name of the variable referred to by vname. This will be vname except when vname is a name reference. ${!vname[subscript]} Expands to name of the subscript unless subscript is *, @. or of the form sub1 .. sub2. When subscript is *, the list of array subscripts for vname is generated. For a variable that is not an array, the value is 0 if the variable is set. Otherwise it is null. When subscript is @, same as above, except that when used in double quotes, each array subscript yields a separate argument. When subscript is of the form sub1 .. sub2 it expands to the list of subscripts between sub1 and sub2 inclusive using the same quoting rules as @. ${!prefix*} Expands to the names of the variables whose names begin with prefix. ${parameter:-word} If parameter is set and is non-null then substitute its value; otherwise substitute word. ${parameter:=word} If parameter is not set or is null then set it to word; the value of the parameter is then substituted. Positional parameters may not be assigned to in this way. ${parameter:?word} If parameter is set and is non-null then substitute its value; otherwise, print word and exit from the shell (if not interactive). If word is omitted then a standard message is printed. ${parameter:+word} If parameter is set and is non-null then substitute word; otherwise substitute nothing. In the above, word is not evaluated unless it is to be used as the substituted string, so that, in the following example, pwd is executed only if d is not set or is null: print ${d:-$(pwd)} If the colon ( : ) is omitted from the above expressions, then the shell only checks whether parameter is set or not. ${parameter:offset:length} ${parameter:offset} Expands to the portion of the value of parameter starting at the character (counting from 0) determined by expanding offset as an arithmetic expression and consisting of the number of characters determined by the arithmetic expression defined by length. In the second form, the remainder of the value is used. If A negative offset counts backwards from the end of parameter. Note that one or more blanks is required in front of a minus sign to prevent the shell from interpreting the operator as :-. If parameter is ∗ or @, or is an array name indexed by ∗ or @, then offset and length refer to the array index and number of elements respectively. A negative offset is taken relative to one greater than the highest subscript for indexed arrays. The order for associate arrays is unspecified. ${parameter#pattern} ${parameter##pattern} If the shell pattern matches the beginning of the value of parameter, then the value of this expansion is the value of the parameter with the matched portion deleted; otherwise the value of this parameter is substituted. In the first form the smallest matching pattern is deleted and in the second form the largest matching pattern is deleted. When parameter is @, *, or an array variable with subscript @ or *, the substring operation is applied to each element in turn. ${parameter%pattern} ${parameter%%pattern} If the shell pattern matches the end of the value of parameter, then the value of this expansion is the value of the parameter with the matched part deleted; otherwise substitute the value of parameter. In the first form the smallest matching pattern is deleted and in the second form the largest matching pattern is deleted. When parameter is @, *, or an array variable with subscript @ or *, the substring operation is applied to each element in turn. ${parameter/pattern/string} ${parameter//pattern/string} ${parameter/#pattern/string} ${parameter/%pattern/string} Expands parameter and replaces the longest match of pattern with the given string. Each occurrence of \n in string is replaced by the portion of parameter that matches the n-th sub-pattern. In the first form, only the first occurrence of pattern is replaced. In the second form, each match for pattern is replaced by the given string. The third form restricts the pattern match to the beginning of the string while the fourth form restricts the pattern match to the end of the string. When string is null, the pattern will be deleted and the / in front of string may be omitted. When parameter is @, *, or an array variable with subscript @ or *, the substitution operation is applied to each element in turn. In this case, the string portion of word will be re-evaluated for each element. The following parameters are automatically set by the shell: # The number of positional parameters in decimal. - Options supplied to the shell on invocation or by the set command. ? The decimal value returned by the last executed command. $ The process number of this shell. _ Initially, the value of _ is an absolute pathname of the shell or script being executed as passed in the environment. Subsequently it is assigned the last argument of the previous command. This parameter is not set for commands which are asynchronous. This parameter is also used to hold the name of the matching MAIL file when checking for mail. While defining a compound variable or a type, _ is initialized as a reference to the compound variable or type. When a discipline function is invoked, _ is initialized as a reference to the variable associated with the call to this function. Finally when _ is used as the name of the first variable of a type definition, the new type is derived from the type of the first variable (See Type Variables below.). ! The process id or the pool name and job number of the last background command invoked or the most recent job put in the background with the bg built-in command. Background jobs started in a named pool will be in the form pool.number where pool is the pool name and number is the job number within that pool. .sh.command When processing a DEBUG trap, this variable contains the current command line that is about to run. .sh.edchar This variable contains the value of the keyboard character (or sequence of characters if the first character is an ESC, ascii 033) that has been entered when processing a KEYBD trap (see Key Bindings below). If the value is changed as part of the trap action, then the new value replaces the key (or key sequence) that caused the trap. .sh.edcol The character position of the cursor at the time of the most recent KEYBD trap. .sh.edmode The value is set to ESC when processing a KEYBD trap while in vi insert mode. (See Vi Editing Mode below.) Otherwise, .sh.edmode is null when processing a KEYBD trap. .sh.edtext The characters in the input buffer at the time of the most recent KEYBD trap. The value is null when not processing a KEYBD trap. .sh.file The pathname of the file than contains the current command. .sh.fun The name of the current function that is being executed. .sh.level Set to the current function depth. This can be changed inside a DEBUG trap and will set the context to the specified level. .sh.lineno Set during a DEBUG trap to the line number for the caller of each function. .sh.match An indexed array which stores the most recent match and sub-pattern matches after conditional pattern matches that match and after variables expansions using the operators #, %, or /. The 0-th element stores the complete match and the i-th. element stores the i-th submatch. The .sh.match variable becomes unset when the variable that has expanded is assigned a new value. .sh.math Used for defining arithmetic functions (see Arithmetic evaluation below). and stores the list of user defined arithmetic functions. .sh.name Set to the name of the variable at the time that a discipline function is invoked. .sh.subscript Set to the name subscript of the variable at the time that a discipline function is invoked. .sh.subshell The current depth for subshells and command substitution. .sh.value Set to the value of the variable at the time that the set or append discipline function is invoked. When a user defined arithmetic function is invoked, the value of .sh.value is saved and .sh.value is set to long double precision floating point. .sh.value is restored when the function returns. .sh.version Set to a value that identifies the version of this shell. KSH_VERSION A name reference to .sh.version. LINENO The current line number within the script or function being executed. OLDPWD The previous working directory set by the cd command. OPTARG The value of the last option argument processed by the getopts built-in command. OPTIND The index of the last option argument processed by the getopts built-in command. PPID The process number of the parent of the shell. PWD The present working directory set by the cd command. RANDOM Each time this variable is referenced, a random integer, uniformly distributed between 0 and 32767, is generated. The sequence of random numbers can be initialized by assigning a numeric value to RANDOM. REPLY This variable is set by the select statement and by the read built-in command when no arguments are supplied. SECONDS Each time this variable is referenced, the number of seconds since shell invocation is returned. If this variable 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. SHLVL An integer variable the is incremented each time the shell is invoked and is exported. If SHLVL is not in the environment when the shell is invoked, it is set to 1. The following variables are used by the shell: CDPATH The search path for the cd command. COLUMNS If this variable is set, the value is used to define the width of the edit window for the shell edit modes and for printing select lists. EDITOR If the VISUAL variable is not set, the value of this variable will be checked for the patterns as described with VISUAL below and the corresponding editing option (see Special Command set below) will be turned on. ENV If this variable is set, then parameter expansion, command substitution, and arithmetic substitution are performed on the value to generate the pathname of the script that will be executed when the shell is invoked interactively (see Invocation below). This file is typically used for alias and function definitions. The default value is $HOME/.kshrc. On systems that support a system wide /etc/ksh.kshrc initialization file, if the filename generated by the expansion of ENV begins with /./ or ././ the system wide initialization file will not be executed. FCEDIT Obsolete name for the default editor name for the hist command. FCEDIT is not used when HISTEDIT is set. FIGNORE A pattern that defines the set of filenames that will be ignored when performing filename matching. FPATH The search path for function definitions. The directories in this path are searched for a file with the same name as the function or command when a function with the -u attribute is referenced and when a command is not found. If an executable file with the name of that command is found, then it is read and executed in the current environment. Unlike PATH, the current directory must be represented explicitly by . rather than by adjacent : characters or a beginning or ending :. HISTCMD Number of the current command in the history file. HISTEDIT Name for the default editor name for the hist command. HISTFILE If this variable is set when the shell is invoked, then the value is the pathname of the file that will be used to store the command history (see Command Re-entry below). HISTSIZE If this variable is set when the shell is invoked, then the number of previously entered commands that are accessible by this shell will be greater than or equal to this number. The default is 512. HOME The default argument (home directory) for the cd command. IFS Internal field separators, normally space, tab, and new-line that are used to separate the results of command substitution or parameter expansion and to separate fields with the built-in command read. The first character of the IFS variable is used to separate arguments for the "$∗" substitution (see Quoting below). Each single occurrence of an IFS character in the string to be split, that is not in the isspace character class, and any adjacent characters in IFS that are in the isspace character class, delimit a field. One or more characters in IFS that belong to the isspace character class, delimit a field. In addition, if the same isspace character appears consecutively inside IFS, this character is treated as if it were not in the isspace class, so that if IFS consists of two tab characters, then two adjacent tab characters delimit a null field. JOBMAX This variable defines the maximum number running background jobs that can run at a time. When this limit is reached, the shell will wait for a job to complete before staring a new job. LANG This variable determines the locale category for any category not specifically selected with a variable starting with LC_ or LANG. LC_ALL This variable overrides the value of the LANG variable and any other LC_ variable. LC_COLLATE This variable determines the locale category for character collation information. LC_CTYPE This variable determines the locale category for character handling functions. It determines the character classes for pattern matching (see File Name Generation below). LC_NUMERIC This variable determines the locale category for the decimal point character. LINES If this variable is set, the value is used to determine the column length for printing select lists. Select lists will print vertically until about two-thirds of LINES lines are filled. MAIL If this variable is set to the name of a mail file and the MAILPATH variable is not set, then the shell informs the user of arrival of mail in the specified file. MAILCHECK This variable specifies how often (in seconds) the shell will check for changes in the modification time of any of the files specified by the MAILPATH or MAIL variables. The default value is 600 seconds. When the time has elapsed the shell will check before issuing the next prompt. MAILPATH A colon ( : ) separated list of file names. If this variable is set, then the shell informs the user of any modifications to the specified files that have occurred within the last MAILCHECK seconds. Each file name can be followed by a ? and a message that will be printed. The message will undergo parameter expansion, command substitution, and arithmetic substitution with the variable $_ defined as the name of the file that has changed. The default message is you have mail in $_. PATH The search path for commands (see Execution below). The user may not change PATH if executing under rksh (except in .profile). PS1 The value of this variable is expanded for parameter expansion, command substitution, and arithmetic substitution to define the primary prompt string which by default is ``$''. The character ! in the primary prompt string is replaced by the command number (see Command Re-entry below). Two successive occurrences of ! will produce a single ! when the prompt string is printed. PS2 Secondary prompt string, by default ``> ''. PS3 Selection prompt string used within a select loop, by default ``#? ''. PS4 The value of this variable is expanded for parameter evaluation, command substitution, and arithmetic substitution and precedes each line of an execution trace. By default, PS4 is ``+ ''. In addition when PS4 is unset, the execution trace prompt is also ``+ ''. SHELL The pathname of the shell is kept in the environment. At invocation, if the basename of this variable is rsh, rksh, or krsh, then the shell becomes restricted. If it is pfsh or pfksh, then the shell becomes a profile shell (see pfexec(1)). TIMEFORMAT The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The % character introduces a format sequence that is expanded to a time value or other information. The format sequences and their meanings are as follows. %% A literal %. %[p][l]R The elapsed time in seconds. %[p][l]U The number of CPU seconds spent in user mode. %[p][l]S The number of CPU seconds spent in system mode. %P The CPU percentage, computed as (U + S) / R. The brackets denote optional portions. The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point can be displayed; values of p greater than 3 are treated as 3. If p is not specified, the value 3 is used. The optional l specifies a longer format, including hours if greater than zero, minutes, and seconds of the form HHhMMmSS.FFs. The value of p determines whether or not the fraction is included. All other characters are output without change and a trailing newline is added. If unset, the default value, $'\nreal\t%2lR\nuser\t%2lU\nsys%2lS', is used. If the value is null, no timing information is displayed. TMOUT If set to a value greater than zero, TMOUT will be the default timeout value for the read built-in command. The select compound command terminates after TMOUT seconds when input is from a terminal. Otherwise, the shell will terminate if a line is not entered within the prescribed number of seconds while reading from a terminal. (Note that the shell can be compiled with a maximum bound for this value which cannot be exceeded.) VISUAL If the value of this variable matches the pattern *[Vv][Ii]*, then the vi option (see Special Command set below) is turned on. If the value matches the pattern *gmacs* , the gmacs option is turned on. If the value matches the pattern *macs*, then the emacs option will be turned on. The value of VISUAL overrides the value of EDITOR. The shell gives default values to PATH, PS1, PS2, PS3, PS4, MAILCHECK, FCEDIT, TMOUT and IFS, while HOME, SHELL, ENV, and MAIL are not set at all by the shell (although HOME is set by login(1)). On some systems MAIL and SHELL are also set by login(1). Field Splitting. After parameter expansion and command substitution, the results of substitutions are scanned for the field separator characters (those found in IFS) and split into distinct fields where such characters are found. Explicit null fields ("" or ′′) are retained. Implicit null fields (those resulting from parameters that have no values or command substitutions with no output) are removed. If the braceexpand (-B) option is set then each of the fields resulting from IFS are checked to see if they contain one or more of the brace patterns {*,*}, {l1..l2} , {n1..n2} , {n1..n2% fmt} , {n1..n2 ..n3} , or {n1..n2 ..n3%fmt} , where * represents any character, l1,l2 are letters and n1,n2,n3 are signed numbers and fmt is a format specified as used by printf. In each case, fields are created by prepending the characters before the { and appending the characters after the } to each of the strings generated by the characters between the { and }. The resulting fields are checked to see if they have any brace patterns. In the first form, a field is created for each string between { and ,, between , and ,, and between , and }. The string represented by * can contain embedded matching { and } without quoting. Otherwise, each { and } with * must be quoted. In the seconds form, l1 and l2 must both be either upper case or both be lower case characters in the C locale. In this case a field is created for each character from l1 thru l2. In the remaining forms, a field is created for each number starting at n1 and continuing until it reaches n2 incrementing n1 by n3. The cases where n3 is not specified behave as if n3 where 1 if n1<=n2 and -1 otherwise. If forms which specify %fmt any format flags, widths and precisions can be specified and fmt can end in any of the specifiers cdiouxX. For example, {a,z}{1..5..3%02d}{b..c}x expands to the 8 fields, a01bx, a01cx, a04bx, a04cx, z01bx, z01cx, z04bx and z4cx. File Name Generation. Following splitting, each field is scanned for the characters ∗, ?, (, and [ unless the -f option has been set. If one of these characters appears, then the word is regarded as a pattern. Each file name component that contains any pattern character is replaced with a lexicographically sorted set of names that matches the pattern from that directory. If no file name is found that matches the pattern, then that component of the filename is left unchanged unless the pattern is prefixed with ∼(N) in which case it is removed as described below. If FIGNORE is set, then each file name component that matches the pattern defined by the value of FIGNORE is ignored when generating the matching filenames. The names . and .. are also ignored. If FIGNORE is not set, the character . at the start of each file name component will be ignored unless the first character of the pattern corresponding to this component is the character . itself. Note, that for other uses of pattern matching the / and . are not treated specially. ∗ Matches any string, including the null string. When used for filename expansion, if the globstar option is on, two adjacent ∗'s by itself will match all files and zero or more directories and subdirectories. If followed by a / then only directories and subdirectories will match. ? Matches any single character. [...] Matches any one of the enclosed characters. A pair of characters separated by - matches any character lexically between the pair, inclusive. If the first character following the opening [ is a ! or ^ then any character not enclosed is matched. A - can be included in the character set by putting it as the first or last character. Within [ and ], character classes can be specified with the syntax [:class:] where class is one of the following classes defined in the ANSI-C standard: (Note that word is equivalent to alnum plus the character _.) alnum alpha blank cntrl digit graph lower print punct space upper word xdigit Within [ and ], an equivalence class can be specified with the syntax [=c=] which matches all characters with the same primary collation weight (as defined by the current locale) as the character c. Within [ and ], [.symbol.] matches the collating symbol symbol. A pattern-list is a list of one or more patterns separated from each other with a & or ⎪. A & signifies that all patterns must be matched whereas ⎪ requires that only one pattern be matched. Composite patterns can be formed with one or more of the following sub-patterns: ?(pattern-list) Optionally matches any one of the given patterns. *(pattern-list) Matches zero or more occurrences of the given patterns. +(pattern-list) Matches one or more occurrences of the given patterns. {n}(pattern-list) Matches n occurrences of the given patterns. {m,n}(pattern-list) Matches from m to n occurrences of the given patterns. If m is omitted, 0 will be used. If n is omitted at least m occurrences will be matched. @(pattern-list) Matches exactly one of the given patterns. !(pattern-list) Matches anything except one of the given patterns. By default, each pattern, or sub-pattern will match the longest string possible consistent with generating the longest overall match. If more than one match is possible, the one starting closest to the beginning of the string will be chosen. However, for each of the above compound patterns a - can be inserted in front of the ( to cause the shortest match to the specified pattern-list to be used. When pattern-list is contained within parentheses, the backslash character \ is treated specially even when inside a character class. All ANSI-C character escapes are recognized and match the specified character. In addition the following escape sequences are recognized: \d Matches any character in the digit class. \D Matches any character not in the digit class. \s Matches any character in the space class. \S Matches any character not in the space class. \w Matches any character in the word class. \W Matches any character not in the word class. A pattern of the form %(pattern-pair(s)) is a sub-pattern that can be used to match nested character expressions. Each pattern-pair is a two character sequence which cannot contain & or ⎪. The first pattern-pair specifies the starting and ending characters for the match. Each subsequent pattern-pair represents the beginning and ending characters of a nested group that will be skipped over when counting starting and ending character matches. The behavior is unspecified when the first character of a pattern-pair is alpha-numeric except for the following: D Causes the ending character to terminate the search for this pattern without finding a match. E Causes the ending character to be interpreted as an escape character. L Causes the ending character to be interpreted as a quote character causing all characters to be ignored when looking for a match. Q Causes the ending character to be interpreted as a quote character causing all characters other than any escape character to be ignored when looking for a match. Thus, %({}Q"E\), matches characters starting at { until the matching } is found not counting any { or } that is inside a double quoted string or preceded by the escape character \. Without the {} this pattern matches any C language string. Each sub-pattern in a composite pattern is numbered, starting at 1, by the location of the ( within the pattern. The sequence \n, where n is a single digit and \n comes after the n-th. sub-pattern, matches the same string as the sub-pattern itself. Finally a pattern can contain sub-patterns of the form ∼(options:pattern-list), where either options or :pattern-list can be omitted. Unlike the other compound patterns, these sub-patterns are not counted in the numbered sub-patterns. :pattern-list must be omitted for options F, G, N , and V below. If options is present, it can consist of one or more of the following: + Enable the following options. This is the default. - Disable the following options. E The remainder of the pattern uses extended regular expression syntax like the egrep(1) command. F The remainder of the pattern uses fgrep(1) expression syntax. G The remainder of the pattern uses basic regular expression syntax like the grep(1) command. K The remainder of the pattern uses shell pattern syntax. This is the default. N This is ignored. However, when it is the first letter and is used with file name generation, and no matches occur, the file pattern expands to the empty string. X The remainder of the pattern uses augmented regular expression syntax like the xgrep(1) command. P The remainder of the pattern uses perl(1) regular expression syntax. Not all perl regular expression syntax is currently implemented. V The remainder of the pattern uses System V regular expression syntax. i Treat the match as case insensitive. g File the longest match (greedy). This is the default. l Left anchor the pattern. This is the default for K style patterns. r Right anchor the pattern. This is the default for K style patterns. If both options and :pattern-list are specified, then the options apply only to pattern-list. Otherwise, these options remain in effect until they are disabled by a subsequent ∼(...) or at the end of the sub- pattern containing ∼(...). Quoting. Each of the metacharacters listed earlier (see Definitions above) has a special meaning to the shell and causes termination of a word unless quoted. A character may be quoted (i.e., made to stand for itself) by preceding it with a \. The pair \new-line is removed. All characters enclosed between a pair of single quote marks (′′) that is not preceded by a $ are quoted. A single quote cannot appear within the single quotes. A single quoted string preceded by an unquoted $ is processed as an ANSI-C string except for the following: \0 Causes the remainder of the string to be ignored. \E Equivalent to the escape character (ascii 033), \e Equivalent to the escape character (ascii 033), \cx Expands to the character control-x. \C[.name.] Expands to the collating element name. Inside double quote marks (""), parameter and command substitution occur and \ quotes the characters \, `, ", and $. A $ in front of a double quoted string will be ignored in the "C" or "POSIX" locale, and may cause the string to be replaced by a locale specific string otherwise. The meaning of $∗ and $@ is identical when not quoted or when used as a variable assignment value or as a file name. However, when used as a command argument, "$∗" is equivalent to "$1d$2d...", where d is the first character of the IFS variable, whereas "$@" is equivalent to "$1" "$2" .... Inside grave quote marks (``), \ quotes the characters \, `, and $. If the grave quotes occur within double quotes, then \ also quotes the character ". The special meaning of reserved words or aliases can be removed by quoting any character of the reserved word. The recognition of function names or built-in command names listed below cannot be altered by quoting them. Arithmetic Evaluation. The shell performs arithmetic evaluation for arithmetic substitution, to evaluate an arithmetic command, to evaluate an indexed array subscript, and to evaluate arguments to the built-in commands shift and let. Evaluations are performed using double precision floating point arithmetic or long double precision floating point for systems that provide this data type. Floating point constants follow the ANSI-C programming language floating point conventions. The floating point constants Nan and Inf can be use to represent "not a number" and infinity respectively. Integer constants follow the ANSI-C programming language integer constant conventions although only single byte character constants are recognized and character casts are not recognized. In addition constants can be of the form [base#]n where base is a decimal number between two and sixty-four representing the arithmetic base and n is a number in that base. The digits above 9 are represented by the lower case letters, the upper case letters, @, and _ respectively. For bases less than or equal to 36, upper and lower case characters can be used interchangeably. An arithmetic expression uses the same syntax, precedence, and associativity of expression as the C language. All the C language operators that apply to floating point quantities can be used. In addition, the operator ** can be used for exponentiation. It has higher precedence than multiplication and is left associative. In addition, when the value of an arithmetic variable or sub-expression can be represented as a long integer, all C language integer arithmetic operations can be performed. Variables can be referenced by name within an arithmetic expression without using the parameter expansion syntax. When a variable is referenced, its value is evaluated as an arithmetic expression. Any of the following math library functions that are in the C math library can be used within an arithmetic expression: abs acos acosh asin asinh atan atan2 atanh cbrt ceil copysign cos cosh erf erfc exp exp2 expm1 fabs fpclassify fdim finite floor fma fmax fmin fmod hypot ilogb int isfinite sinf isnan isnormal issubnormal issubordered iszero j0 j1 jn lgamma log log10 log2 logb nearbyint nextafter nexttoward pow remainder rint round scanb signbit sin sinh sqrt tan tanh tgamma trunc y0 y1 yn In addition, arithmetic functions can be define as shell functions with a variant of the function name syntax, function .sh.math.name ident ... { list ;} where name is the function name used in the arithmetic expression and each identifier, ident is a name reference to the long double precision floating point argument. The value of .sh.value when the function returns is the value of this function. User defined functions can take up to 3 arguments and override C math library functions. An internal representation of a variable as a double precision floating point can be specified with the -E [n], -F [n], or -X [n] option of the typeset special built-in command. The -E option causes the expansion of the value to be represented using scientific notation when it is expanded. The optional option argument n defines the number of significant figures. The -F option causes the expansion to be represented as a floating decimal number when it is expanded. The -X option cause the expansion to be represented using the %a format defined by ISO C-99. The optional option argument n defines the number of places after the decimal (or radix) point in this case. An internal integer representation of a variable can be specified with the -i [n] option of the typeset special built-in command. The optional option argument n specifies an arithmetic base to be used when expanding the variable. If you do not specify an arithmetic base, base 10 will be used. Arithmetic evaluation is performed on the value of each assignment to a variable with the -E, -F, -X, or -i attribute. Assigning a floating point number to a variable whose type is an integer causes the fractional part to be truncated. Prompting. When used interactively, the shell prompts with the value of PS1 after expanding it for parameter expansion, command substitution, and arithmetic substitution, before reading a command. In addition, each single ! in the prompt is replaced by the command number. A !! is required to place ! in the prompt. If at any time a new-line is typed and further input is needed to complete a command, then the secondary prompt (i.e., the value of PS2) is issued. Conditional Expressions. A conditional expression is used with the [[ compound command to test attributes of files and to compare strings. Field splitting and file name generation are not performed on the words between [[ and ]]. Each expression can be constructed from one or more of the following unary or binary expressions: string True, if string is not null. -a file Same as -e below. This is obsolete. -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 an ordinary file. -g file True, if file exists and it has its setgid bit set. -k file True, if file exists and it has its sticky bit set. -n string True, if length of string is non-zero. -o ?option True, if option named option is a valid option name. -o option True, if option named option is on. -p file True, if file exists and is a fifo special file or a 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 fildes True, if file descriptor number fildes is open and associated with a terminal device. -u file True, if file exists and it has its setuid bit set. -v name True, if variable name is a valid variable name and is 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 true if 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. -h file True, if file exists and is a symbolic link. -N file True, if file exists and the modification time is greater than the last access time. -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. -R name True if variable name is a name reference. -S file True, if file exists and is a socket. file1 -nt file2 True, if file1 exists and file2 does not, or file1 is newer than file2. file1 -ot file2 True, if file2 exists and file1 does not, or file1 is older than file2. file1 -ef file2 True, if file1 and file2 exist and refer to the same file. string == pattern True, if string matches pattern. Any part of pattern can be quoted to cause it to be matched as a string. With a successful match to a pattern, the .sh.match array variable will contain the match and sub-pattern matches. string = pattern Same as == above, but is obsolete. string != pattern True, if string does not match pattern. When the string matches the pattern the .sh.match array variable will contain the match and sub-pattern matches. string =∼ ere True if string matches the pattern ∼(E)ere where ere is an extended regular expression. 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. The following obsolete arithmetic comparisons are also permitted: exp1 -eq exp2 True, if exp1 is equal to exp2. exp1 -ne exp2 True, if exp1 is not equal to exp2. exp1 -lt exp2 True, if exp1 is less than exp2. exp1 -gt exp2 True, if exp1 is greater than exp2. exp1 -le exp2 True, if exp1 is less than or equal to exp2. exp1 -ge exp2 True, if exp1 is greater than or equal to exp2. In each of the above expressions, if file is of the form /dev/fd/n, where n is an integer, then the test is applied to the open file whose descriptor number is n. A compound expression can be constructed from these primitives by using any of the following, listed in decreasing order of precedence. (expression) True, if expression is true. Used to group expressions. ! expression True if expression is false. expression1 && expression2 True, if expression1 and expression2 are both true. expression1 ⎪⎪ expression2 True, if either expression1 or expression2 is true. Input/Output. Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. The following may appear anywhere in a simple-command or may precede or follow a command and are not passed on to the invoked command. Command substitution, parameter expansion, and arithmetic substitution occur before word or digit is used except as noted below. File name generation occurs only if the shell is interactive and the pattern matches a single file. Field splitting is not performed. In each of the following redirections, if file is of the form /dev/sctp/host/port, /dev/tcp/host/port, or /dev/udp/host/port, where host is a hostname or host address, and port is a service given by name or an integer port number, then the redirection attempts to make a tcp, sctp or udp connection to the corresponding socket. No intervening space is allowed between the characters of redirection operators. <word Use file word as standard input (file descriptor 0). >word Use file word as standard output (file descriptor 1). If the file does not exist then it is created. If the file exists, and the noclobber option is on, this causes an error; otherwise, it is truncated to zero length. >|word Same as >, except that it overrides the noclobber option. >;word Write output to a temporary file. If the command completes successfully rename it to word, otherwise, delete the temporary file. >;word cannot be used with the exec(2). built-in. >>word Use file word as standard output. If the file exists, then output is appended to it (by first seeking to the end-of-file); otherwise, the file is created. <>word Open file word for reading and writing as standard output. <>;word The same as <>word except that if the command completes successfully, word is truncated to the offset at command completion. <>;word cannot be used with the exec(2). built-in. <<[-]word The shell input is read up to a line that is the same as word after any quoting has been removed, or to an end-of- file. No parameter substitution, command substitution, arithmetic substitution or file name generation is performed on word. The resulting document, called a here-document, becomes the standard input. If any character of word is quoted, then no interpretation is placed upon the characters of the document; otherwise, parameter expansion, command substitution, and arithmetic substitution occur, \new-line is ignored, and \ must be used to quote the characters \, $, `. If - is appended to <<, then all leading tabs are stripped from word and from the document. If # is appended to <<, then leading spaces and tabs will be stripped off the first line of the document and up to an equivalent indentation will be stripped from the remaining lines and from word. A tab stop is assumed to occur at every 8 columns for the purposes of determining the indentation. <<<word A short form of here document in which word becomes the contents of the here-document after any parameter expansion, command substitution, and arithmetic substitution occur. <&digit The standard input is duplicated from file descriptor digit (see dup(2)). Similarly for the standard output using >&digit. <&digit- The file descriptor given by digit is moved to standard input. Similarly for the standard output using >&digit-. <&- The standard input is closed. Similarly for the standard output using >&-. <&p The input from the co-process is moved to standard input. >&p The output to the co-process is moved to standard output. <#((expr)) Evaluate arithmetic expression expr and position file descriptor 0 to the resulting value bytes from the start of the file. The variables CUR and EOF evaluate to the current offset and end-of-file offset respectively when evaluating expr. >#((offset)) The same as <# except applies to file descriptor 1. <#pattern Seeks forward to the beginning of the next line containing pattern. <##pattern The same as <# except that the portion of the file that is skipped is copied to standard output. If one of the above is preceded by a digit, with no intervening space, then the file descriptor number referred to is that specified by the digit (instead of the default 0 or 1). If one of the above, other than >&- and the ># and <# forms, is preceded by {varname} with no intervening space, then a file descriptor number > 10 will be selected by the shell and stored in the variable varname. If >&- or the any of the ># and <# forms is preceded by {varname} the value of varname defines the file descriptor to close or position. For example: ... 2>&1 means file descriptor 2 is to be opened for writing as a duplicate of file descriptor 1 and exec {n}<file means open file named file for reading and store the file descriptor number in variable n. 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 (i.e. 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. 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. Environment. The environment (see environ(7)) is a list of name-value pairs that is passed to an executed program in the same way as a normal argument list. The names must be identifiers and the values are character strings. The shell interacts with the environment in several ways. On invocation, the shell scans the environment and creates a variable for each name found, giving it the corresponding value and attributes and marking it export. Executed commands inherit the environment. If the user modifies the values of these variables or creates new ones, using the export or typeset -x commands, they become part of the environment. The environment seen by any executed command is thus composed of any name-value pairs originally inherited by the shell, whose values may be modified by the current shell, plus any additions which must be noted in export or typeset -x commands. The environment for any simple-command or function may be augmented by prefixing it with one or more variable assignments. A variable assignment argument is a word of the form identifier=value. Thus: TERM=450 cmd args and (export TERM; TERM=450; cmd args) are equivalent (as far as the above execution of cmd is concerned except for special built-in commands listed below - those that are preceded with a dagger). If the obsolete -k option is set, all variable assignment arguments are placed in the environment, even if they occur after the command name. The following first prints a=b c and then c: echo a=b c set -k echo a=b c This feature is intended for use with scripts written for early versions of the shell and its use in new scripts is strongly discouraged. It is likely to disappear someday. Functions. For historical reasons, there are two ways to define functions, the name() syntax and the function name syntax, described in the Commands section above. 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 Execution below.) Functions defined by the function name syntax and called by name execute in the same process as the caller and share all files and present working directory with the caller. Traps caught by the caller are reset to their default action inside the function. A trap condition that is not caught or ignored by the function causes the function to terminate and the condition to be passed on to the caller. A trap on EXIT set inside a function is executed in the environment of the caller after the function completes. Ordinarily, variables are shared between the calling program and the function. However, the typeset special built-in command used within a function defines local variables whose scope includes the current function. They can be passed to functions that they call in the variable assignment list that precedes the call or as arguments passed as name references. Errors within functions return control to the caller. Functions defined with the name() syntax and functions defined with the function name syntax that are invoked with the . special built-in are executed in the caller's environment and share all variables and traps with the caller. Errors within these function executions cause the script that contains them to abort. The special built-in command return is used to return from function calls. Function names can be listed with the -f or +f option of the typeset special built-in command. The text of functions, when available, will also be listed with -f. Functions can be undefined with the -f option of the unset special built-in command. Ordinarily, functions are unset when the shell executes a shell script. Functions that need to be defined across separate invocations of the shell should be placed in a directory and the FPATH variable should contain the name of this directory. They may also be specified in the ENV file. Discipline Functions. Each variable can have zero or more discipline functions associated with it. The shell initially understands the discipline names get, set, append, and unset but can be added when defining new types. On most systems others can be added at run time via the C programming interface extension provided by the builtin built-in utility. If the get discipline is defined for a variable, it is invoked whenever the given variable is referenced. If the variable .sh.value is assigned a value inside the discipline function, the referenced variable will evaluate to this value instead. If the set discipline is defined for a variable, it is invoked whenever the given variable is assigned a value. If the append discipline is defined for a variable, it is invoked whenever a value is appended to the given variable. The variable .sh.value is given the value of the variable before invoking the discipline, and the variable will be assigned the value of .sh.value after the discipline completes. If .sh.value is unset inside the discipline, then that value is unchanged. If the unset discipline is defined for a variable, it is invoked whenever the given variable is unset. The variable will not be unset unless it is unset explicitly from within this discipline function. The variable .sh.name contains the name of the variable for which the discipline function is called, .sh.subscript is the subscript of the variable, and .sh.value will contain the value being assigned inside the set discipline function. The variable _ is a reference to the variable including the subscript if any. For the set discipline, changing .sh.value will change the value that gets assigned. Finally, the expansion ${var.name}, when name is the name of a discipline, and there is no variable of this name, is equivalent to the command substitution ${ var.name;}. Name Spaces. Commands and functions that are executed as part of the list of a namespace command that modify variables or create new ones, create a new variable whose name is the name of the name space as given by identifier preceded by .. When a variable whose name is name is referenced, it is first searched for using .identifier.name. Similarly, a function defined by a command in the namespace list is created using the name space name preceded by a .. When the list of a namespace command contains a namespace command, the names of variables and functions that are created consist of the variable or function name preceded by the list of identifiers each preceded by .. Outside of a name space, a variable or function created inside a name space can be referenced by preceding it with the name space name. By default, variables staring with .sh are in the sh name space. Type Variables. Typed variables provide a way to create data structure and objects. A type can be defined either by a shared library, by the enum built-in command described below, or by using the new -T option of the typeset built-in command. With the -T option of typeset, the type name, specified as an option argument to -T, is set with a compound variable assignment that defines the type. Function definitions can appear inside the compound variable assignment and these become discipline functions for this type and can be invoked or redefined by each instance of the type. The function name create is treated specially. It is invoked for each instance of the type that is created but is not inherited and cannot be redefined for each instance. When a type is defined a special built-in command of that name is added. These built-ins are declaration commands and follow the same expansion rules as all the special built-in commands defined below that are preceded by ††. These commands can subsequently be used inside further type definitions. The man page for these commands can be generated by using the --man option or any of the other -- options described with getopts. The -r, -a, -A, -h, and -S options of typeset are permitted with each of these new built-ins. An instance of a type is created by invoking the type name followed by one or more instance names. Each instance of the type is initialized with a copy of the sub-variables except for sub-variables that are defined with the -S option. Variables defined with the -S are shared by all instances of the type. Each instance can change the value of any sub-variable and can also define new discipline functions of the same names as those defined by the type definition as well as any standard discipline names. No additional sub-variables can be defined for any instance. When defining a type, if the value of a sub-variable is not set and the -r attribute is specified, it causes the sub-variable to be a required sub-variable. Whenever an instance of a type is created, all required sub-variables must be specified. These sub-variables become readonly in each instance. When unset is invoked on a sub-variable within a type, and the -r attribute has not been specified for this field, the value is reset to the default value associative with the type. Invoking unset on a type instance not contained within another type deletes all sub-variables and the variable itself. A type definition can be derived from another type definition by defining the first sub-variable name as _ and defining its type as the base type. Any remaining definitions will be additions and modifications that apply to the new type. If the new type name is the same is that of the base type, the type will be replaced and the original type will no longer be accessible. The typeset command with the -T and no option argument or operands will write all the type definitions to standard output in a form that that can be read in to create all they types. Jobs. If the monitor option of the set command is turned on, 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 (top-level) process, whose process id was 1234. This paragraph and the next require features that are not in all versions of UNIX and may not apply. If you are running a job and wish to do something else you may hit the key ^Z (control-Z) which sends a STOP signal to the current job. The shell will then normally indicate that the job has been `Stopped', 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 stop 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 stop when they try to produce output like they do when they try to read input. A job pool is a collection of jobs started with list & associated with a name. 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. pool All the jobs in the job pool named by pool. pool.number The job number number in the job pool named by pool. %string Any job whose command line begins with string. %?string Any job whose command line contains string. %% Current job. %+ Equivalent to %%. %- Previous job. In addition, unless noted otherwise, wherever a job can be specified, the name of a background job pool can be used to represent all the jobs in that pool. 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, but only just before it prints a prompt. This is done so that it does not otherwise disturb your work. The notify option of the set command causes the shell to print these job change messages as soon as they occur. When the monitor option 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 stopped, you will be warned that `You have stopped(running) jobs.' You may use the jobs command to see what they are. If you immediately try to exit again, the shell will not warn you a second time, and the stopped jobs will be terminated. When a login shell receives a HUP signal, it sends a HUP signal to each job that has not been disowned with the disown built-in command described below. 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 also the trap built-in command below). Execution. Each time a command is read, the above substitutions are carried out. If the command name matches one of the Special Built-in Commands listed below, it is executed within the current shell process. Next, the command name is checked to see if it matches a user defined function. If it does, the positional parameters are saved and then reset to the arguments of the function call. A function is also executed in the current shell process. When the function completes or issues a return, the positional parameter list is restored. For functions defined with the function name syntax, any trap set on EXIT within the function is executed. The exit value of a function is the value of the last command executed. If a command name is not a special built-in command or a user defined function, but it is one of the built-in commands listed below, it is executed in the current shell process. The shell variables PATH followed by the variable FPATH defines the list of directories to search for the command name. Alternative directory names are separated by a colon (:). The default path is /bin:/usr/bin: (specifying /bin, /usr/bin, and the current directory in that order). The current directory can be specified by two or more adjacent colons, or by a colon at the beginning or end of the path list. If the command name contains a /, then the search path is not used. Otherwise, each directory in the list of directories defined by PATH and FPATH is checked in order. If the directory being searched is contained in FPATH and contains a file whose name matches the command being searched, then this file is loaded into the current shell environment as if it were the argument to the . command except that only preset aliases are expanded, and a function of the given name is executed as described above. If this directory is not in FPATH the shell first determines whether there is a built-in version of a command corresponding to a given pathname and if so it is invoked in the current process. If no built- in is found, the shell checks for a file named .paths in this directory. If found and there is a line of the form FPATH=path where path names an existing directory then that directory is searched after immediately after the current directory as if it were found in the FPATH variable. If path does not begin with /, it is checked for relative to the directory being searched. The .paths file is then checked for a line of the form PLUGIN_LIB=libname [ : libname ] ... . Each library named by libname will be searched for as if it were an option argument to builtin -f, and if it contains a built-in of the specified name this will be executed instead of a command by this name. Any built-in loaded from a library found this way will be associated with the directory containing the .paths file so it will only execute if not found in an earlier directory. Finally, the directory will be checked for a file of the given name. If the file has execute permission but is not an a.out file, it is assumed to be a file containing shell commands. A separate shell is spawned to read it. All non-exported variables are removed in this case. If the shell command file doesn't have read permission, or if the setuid and/or setgid bits are set on the file, then the shell executes an agent whose job it is to set up the permissions and execute the shell with the shell command file passed down as an open file. If the .paths contains a line of the form name=value in the first or second line, then the environment variable name is modified by prepending the directory specified by value to the directory list. If value is not an absolute directory, then it specifies a directory relative to the directory that the executable was found. If the environment variable name does not already exist it will be added to the environment list for the specified command. A parenthesized command is executed in a sub-shell without removing non-exported variables. Command Re-entry. The text of the last HISTSIZE (default 512) commands entered from a terminal device is saved in a history file. The file $HOME/.sh_history is used if the HISTFILE variable is not set or if the file it names is not writable. A shell can access the commands of all interactive shells which use the same named HISTFILE. The built-in command hist is used to list or edit a portion of this file. The portion of the file to be edited or listed can be selected by number or by giving the first character or characters of the command. A single command or range of commands can be specified. If you do not specify an editor program as an argument to hist then the value of the variable HISTEDIT is used. If HISTEDIT is unset, the obsolete variable FCEDIT is used. If FCEDIT is not defined, then /bin/ed is used. The edited command(s) is printed and re-executed upon leaving the editor unless you quit without writing. The -s option (and in obsolete versions, the editor name -) is used to skip the editing phase and to re-execute the command. In this case a substitution parameter of the form old=new can be used to modify the command before execution. For example, with the preset alias r, which is aliased to ′hist -s′, typing `r bad=good c' will re- execute the most recent command which starts with the letter c, replacing the first occurrence of the string bad with the string good. In-line Editing Options. Normally, each command line entered from a terminal device is simply typed followed by a new-line (`RETURN' or `LINE FEED'). If either the emacs, gmacs, or vi option is active, the user can edit the command line. To be in either of these edit modes set the corresponding option. An editing option is automatically selected each time the VISUAL or EDITOR variable is assigned a value ending in either of these option names. The editing features require that the user's terminal accept `RETURN' as carriage return without line feed and that a space (` ') must overwrite the current character on the screen. Unless the multiline option is on, the editing modes implement a concept where the user is looking through a window at the current line. The window width is the value of COLUMNS if it is defined, otherwise 80. If the window width is too small to display the prompt and leave at least 8 columns to enter input, the prompt is truncated from the left. If the line is longer than the window width minus two, a mark is displayed at the end of the window to notify the user. As the cursor moves and reaches the window boundaries the window will be centered about the cursor. The mark is a > (<, *) if the line extends on the right (left, both) side(s) of the window. The search commands in each edit mode provide access to the history file. Only strings are matched, not patterns, although a leading ^ in the string restricts the match to begin at the first character in the line. Each of the edit modes has an operation to list the files or commands that match a partially entered word. When applied to the first word on the line, or the first word after a ;, ⎪, &, or (, and the word does not begin with ∼ or contain a /, the list of aliases, functions, and executable commands defined by the PATH variable that could match the partial word is displayed. Otherwise, the list of files that match the given word is displayed. If the partially entered word does not contain any file expansion characters, a * is appended before generating these lists. After displaying the generated list, the input line is redrawn. These operations are called command name listing and file name listing, respectively. There are additional operations, referred to as command name completion and file name completion, which compute the list of matching commands or files, but instead of printing the list, replace the current word with a complete or partial match. For file name completion, if the match is unique, a / is appended if the file is a directory and a space is appended if the file is not a directory. Otherwise, the longest common prefix for all the matching files replaces the word. For command name completion, only the portion of the file names after the last / are used to find the longest command prefix. If only a single name matches this prefix, then the word is replaced with the command name followed by a space. When using a tab for completion that does not yield a unique match, a subsequent tab will provide a numbered list of matching alternatives. A specific selection can be made by entering the selection number followed by a tab. Key Bindings. The KEYBD trap can be used to intercept keys as they are typed and change the characters that are actually seen by the shell. This trap is executed after each character (or sequence of characters when the first character is ESC) is entered while reading from a terminal. The variable .sh.edchar contains the character or character sequence which generated the trap. Changing the value of .sh.edchar in the trap action causes the shell to behave as if the new value were entered from the keyboard rather than the original value. The variable .sh.edcol is set to the input column number of the cursor at the time of the input. The variable .sh.edmode is set to ESC when in vi insert mode (see below) and is null otherwise. By prepending ${.sh.editmode} to a value assigned to .sh.edchar it will cause the shell to change to control mode if it is not already in this mode. This trap is not invoked for characters entered as arguments to editing directives, or while reading input for a character search. Emacs Editing Mode. This mode is entered by enabling either the emacs or gmacs option. The only difference between these two modes is the way they handle ^T. To edit, the user moves the cursor to the point needing correction and then inserts or deletes characters or words as needed. All the editing commands are control characters or escape sequences. The notation for control characters is caret (^) followed by the character. For example, ^F is the notation for control F. This is entered by depressing `f' while holding down the `CTRL' (control) key. The `SHIFT' key is not depressed. (The notation ^? indicates the DEL (delete) key.) The notation for escape sequences is M- followed by a character. For example, M-f (pronounced Meta f) is entered by depressing ESC (ascii 033) followed by `f'. (M-F would be the notation for ESC followed by `SHIFT' (capital) `F'.) All edit commands operate from any place on the line (not just at the beginning). Neither the `RETURN' nor the `LINE FEED' key is entered after edit commands except when noted. ^F Move cursor forward (right) one character. M-[C Move cursor forward (right) one character. M-f Move cursor forward one word. (The emacs editor's idea of a word is a string of characters consisting of only letters, digits and underscores.) ^B Move cursor backward (left) one character. M-[D Move cursor backward (left) one character. M-b Move cursor backward one word. ^A Move cursor to start of line. M-[H Move cursor to start of line. ^E Move cursor to end of line. M-[Y Move cursor to end of line. ^]char Move cursor forward to character char on current line. M-^]char Move cursor backward to character char on current line. ^X^X Interchange the cursor and mark. erase (User defined erase character as defined by the stty(1) command, usually ^H or #.) Delete previous character. lnext (User defined literal next character as defined by the stty(1) command, or ^V if not defined.) Removes the next character's editing features (if any). ^D Delete current character. M-d Delete current word. M-^H (Meta-backspace) Delete previous word. M-h Delete previous word. M-^? (Meta-DEL) Delete previous word (if your interrupt character is ^? (DEL, the default) then this command will not work). ^T Transpose current character with previous character and advance the cursor in emacs mode. Transpose two previous characters in gmacs mode. ^C Capitalize current character. M-c Capitalize current word. M-l Change the current word to lower case. ^K Delete from the cursor to the end of the line. If preceded by a numerical parameter whose value is less than the current cursor position, then delete from given position up to the cursor. If preceded by a numerical parameter whose value is greater than the current cursor position, then delete from cursor up to given cursor position. ^W Kill from the cursor to the mark. M-p Push the region from the cursor to the mark on the stack. kill (User defined kill character as defined by the stty command, usually ^G or @.) Kill the entire current line. If two kill characters are entered in succession, all kill characters from then on cause a line feed (useful when using paper terminals). ^Y Restore last item removed from line. (Yank item back to the line.) ^L Line feed and print current line. M-^L Clear the screen. ^@ (Null character) Set mark. M-space (Meta space) Set mark. ^J (New line) Execute the current line. ^M (Return) Execute the current line. eof End-of-file character, normally ^D, is processed as an End- of-file only if the current line is null. ^P Fetch previous command. Each time ^P is entered the previous command back in time is accessed. Moves back one line when not on the first line of a multi-line command. M-[A If the cursor is at the end of the line, it is equivalent to ^R with string set to the contents of the current line. Otherwise, it is equivalent to ^P. M-< Fetch the least recent (oldest) history line. M-> Fetch the most recent (youngest) history line. ^N Fetch next command line. Each time ^N is entered the next command line forward in time is accessed. M-[B Equivalent to ^N. ^Rstring Reverse search history for a previous command line containing string. If a parameter of zero is given, the search is forward. String is terminated by a `RETURN' or `NEW LINE'. If string is preceded by a ^, the matched line must begin with string. If string is omitted, then the next command line containing the most recent string is accessed. In this case a parameter of zero reverses the direction of the search. ^O Operate - Execute the current line and fetch the next line relative to current line from the history file. M-digits (Escape) Define numeric parameter, the digits are taken as a parameter to the next command. The commands that accept a parameter are ^F, ^B, erase, ^C, ^D, ^K, ^R, ^P, ^N, ^], M-., M-^], M-_, M-=, M-b, M-c, M-d, M-f, M-h, M-l and M-^H. M-letter Soft-key - Your alias list is searched for an alias by the name _letter and if an alias of this name is defined, its value will be inserted on the input queue. The letter must not be one of the above meta-functions. M-[letter Soft-key - Your alias list is searched for an alias by the name __letter and if an alias of this name is defined, its value will be inserted on the input queue. This can be used to program function keys on many terminals. M-. The last word of the previous command is inserted on the line. If preceded by a numeric parameter, the value of this parameter determines which word to insert rather than the last word. M-_ Same as M-.. M-* Attempt file name generation on the current word. An asterisk is appended if the word doesn't match any file or contain any special pattern characters. M-ESC Command or file name completion as described above. ^I tab Attempts command or file name completion as described above. If a partial completion occurs, repeating this will behave as if M-= were entered. If no match is found or entered after space, a tab is inserted. M-= If not preceded by a numeric parameter, it generates the list of matching commands or file names as described above. Otherwise, the word under the cursor is replaced by the item corresponding to the value of the numeric parameter from the most recently generated command or file list. If the cursor is not on a word, it is inserted instead. ^U Multiply parameter of next command by 4. \ Escape next character. Editing characters, the user's erase, kill and interrupt (normally ^?) characters may be entered in a command line or in a search string if preceded by a \. The \ removes the next character's editing features (if any). M-^V Display version of the shell. M-# If the line does not begin with a #, a # is inserted at the beginning of the line and after each new-line, and the line is entered. This causes a comment to be inserted in the history file. If the line begins with a #, the # is deleted and one # after each new-line is also deleted. Vi Editing Mode. There are two typing modes. Initially, when you enter a command you are in the input mode. To edit, the user enters control mode by typing ESC (033) and moves the cursor to the point needing correction and then inserts or deletes characters or words as needed. Most control commands accept an optional repeat count prior to the command. When in vi mode on most systems, canonical processing is initially enabled and the command will be echoed again if the speed is 1200 baud or greater and it contains any control characters or less than one second has elapsed since the prompt was printed. The ESC character terminates canonical processing for the remainder of the command and the user can then modify the command line. This scheme has the advantages of canonical processing with the type-ahead echoing of raw mode. If the option viraw is also set, the terminal will always have canonical processing disabled. This mode is implicit for systems that do not support two alternate end of line delimiters, and may be helpful for certain terminals. Input Edit Commands By default the editor is in input mode. erase (User defined erase character as defined by the stty command, usually ^H or #.) Delete previous character. ^W Delete the previous blank separated word. On some systems the viraw option may be required for this to work. eof As the first character of the line causes the shell to terminate unless the ignoreeof option is set. Otherwise this character is ignored. lnext (User defined literal next character as defined by the stty(1) or ^V if not defined.) Removes the next character's editing features (if any). On some systems the viraw option may be required for this to work. \ Escape the next erase or kill character. ^I tab Attempts command or file name completion as described above and returns to input mode. If a partial completion occurs, repeating this will behave as if = were entered from control mode. If no match is found or entered after space, a tab is inserted. Motion Edit Commands These commands will move the cursor. [count]l Cursor forward (right) one character. [count][C Cursor forward (right) one character. [count]w Cursor forward one alpha-numeric word. [count]W Cursor to the beginning of the next word that follows a blank. [count]e Cursor to end of word. [count]E Cursor to end of the current blank delimited word. [count]h Cursor backward (left) one character. [count][D Cursor backward (left) one character. [count]b Cursor backward one word. [count]B Cursor to preceding blank separated word. [count]⎪ Cursor to column count. [count]fc Find the next character c in the current line. [count]Fc Find the previous character c in the current line. [count]tc Equivalent to f followed by h. [count]Tc Equivalent to F followed by l. [count]; Repeats count times, the last single character find command, f, F, t, or T. [count], Reverses the last single character find command count times. 0 Cursor to start of line. ^ Cursor to start of line. [H Cursor to first non-blank character in line. $ Cursor to end of line. [Y Cursor to end of line. % Moves to balancing (, ), {, }, [, or ]. If cursor is not on one of the above characters, the remainder of the line is searched for the first occurrence of one of the above characters first. Search Edit Commands These commands access your command history. [count]k Fetch previous command. Each time k is entered the previous command back in time is accessed. [count]- Equivalent to k. [count][A If cursor is at the end of the line it is equivalent to / with string^set to the contents of the current line. Otherwise, it is equivalent to k. [count]j Fetch next command. Each time j is entered the next command forward in time is accessed. [count]+ Equivalent to j. [count][B Equivalent to j. [count]G The command number count is fetched. The default is the least recent history command. /string Search backward through history for a previous command containing string. String is terminated by a `RETURN' or `NEW LINE'. If string is preceded by a ^, the matched line must begin with string. If string is null, the previous string will be used. ?string Same as / except that search will be in the forward direction. n Search for next match of the last pattern to / or ? commands. N Search for next match of the last pattern to / or ?, but in reverse direction. Text Modification Edit Commands These commands will modify the line. a Enter input mode and enter text after the current character. A Append text to the end of the line. Equivalent to $a. [count]cmotion c[count]motion Delete current character through the character that motion would move the cursor to and enter input mode. If motion is c, the entire line will be deleted and input mode entered. C Delete the current character through the end of line and enter input mode. Equivalent to c$. S Equivalent to cc. [count]s Replace characters under the cursor in input mode. D Delete the current character through the end of line. Equivalent to d$. [count]dmotion d[count]motion Delete current character through the character that motion would move to. If motion is d , the entire line will be deleted. i Enter input mode and insert text before the current character. I Insert text before the beginning of the line. Equivalent to 0i. [count]P Place the previous text modification before the cursor. [count]p Place the previous text modification after the cursor. R Enter input mode and replace characters on the screen with characters you type overlay fashion. [count]rc Replace the count character(s) starting at the current cursor position with c, and advance the cursor. [count]x Delete current character. [count]X Delete preceding character. [count]. Repeat the previous text modification command. [count]∼ Invert the case of the count character(s) starting at the current cursor position and advance the cursor. [count]_ Causes the count word of the previous command to be appended and input mode entered. The last word is used if count is omitted. * Causes an * to be appended to the current word and file name generation attempted. If no match is found, it rings the bell. Otherwise, the word is replaced by the matching pattern and input mode is entered. \ Command or file name completion as described above. Other Edit Commands Miscellaneous commands. [count]ymotion y[count]motion Yank current character through character that motion would move the cursor to and puts them into the delete buffer. The text and cursor are unchanged. yy Yanks the entire line. Y Yanks from current position to end of line. Equivalent to y$. u Undo the last text modifying command. U Undo all the text modifying commands performed on the line. [count]v Returns the command hist -e ${VISUAL:-${EDITOR:-vi}} count in the input buffer. If count is omitted, then the current line is used. ^L Line feed and print current line. Has effect only in control mode. ^J (New line) Execute the current line, regardless of mode. ^M (Return) Execute the current line, regardless of mode. # If the first character of the command is a #, then this command deletes this # and each # that follows a newline. Otherwise, sends the line after inserting a # in front of each line in the command. Useful for causing the current line to be inserted in the history as a comment and uncommenting previously commented commands in the history file. [count]= If count is not specified, it generates the list of matching commands or file names as described above. Otherwise, the word under the the cursor is replaced by the count item from the most recently generated command or file list. If the cursor is not on a word, it is inserted instead. @letter Your alias list is searched for an alias by the name _letter and if an alias of this name is defined, its value will be inserted on the input queue for processing. ^V Display version of the shell. Built-in Commands. The following simple-commands are executed in the shell process. Input/Output redirection is permitted. Unless otherwise indicated, the output is written on file descriptor 1 and the exit status, when there is no syntax error, is zero. Except for :, true, false, echo, newgrp, and login, all built-in commands accept -- to indicate end of options. They also interpret the option --man as a request to display the man page onto standard error and -? as a help request which prints a usage message on standard error. Commands that are preceded by one or two † symbols are special built-in commands and are treated specially in the following ways: 1. Variable assignment lists preceding the command remain in effect when the command completes. 2. I/O redirections are processed after variable assignments. 3. Errors cause a script that contains them to abort. 4. They are not valid function names. 5. Words following a command preceded by †† that are in the format of a variable assignment are expanded with the same rules as a variable assignment. This means that tilde substitution is performed after the = sign and field splitting and file name generation are not performed. These are called declaration built-ins. † : [ arg ... ] The command only expands parameters. † . name [ arg ... ] If name is a function defined with the function name reserved word syntax, the function is executed in the current environment (as if it had been defined with the name() syntax.) Otherwise if name refers to a file, the file is read in its entirety and the commands are executed in the current shell environment. The search path specified by PATH is used to find the directory containing the file. If any arguments arg are given, they become the positional parameters while processing the . command and the original positional parameters are restored upon completion. Otherwise the positional parameters are unchanged. The exit status is the exit status of the last command executed. †† alias [ -ptx ] [ name[ =value ] ] ... alias with no arguments prints the list of aliases in the form name=value on standard output. The -p option causes the word alias to be inserted before each one. When one or more arguments are given, an alias is defined for each name whose value is given. A trailing space in value causes the next word to be checked for alias substitution. The obsolete -t option is used to set and list tracked aliases. The value of a tracked alias is the full pathname corresponding to the given name. The value becomes undefined when the value of PATH is reset but the alias remains tracked. Without the -t option, for each name in the argument list for which no value is given, the name and value of the alias is printed. The obsolete -x option has no effect. The exit status is non-zero if a name is given, but no value, and no alias has been defined for the name. bg [ job... ] This command is only on systems that support job control. Puts each specified job into the background. The current job is put in the background if job is not specified. See Jobs for a description of the format of job. † break [ n ] Exit from the enclosing for, while, until, or select loop, if any. If n is specified, then break n levels. builtin [ -ds ] [ -f file ] [ name ... ] If name is not specified, and no -f option is specified, the built-ins are printed on standard output. The -s option prints only the special built-ins. Otherwise, each name represents the pathname whose basename is the name of the built-in. The entry point function name is determined by prepending b_ to the built- in name. A built-in specified by a pathname will only be executed when that pathname would be found during the path search. Built-ins found in libraries loaded via the .paths file will be associate with the pathname of the directory containing the .paths file. The ISO C/C++ prototype is b_mycommand(int argc, char *argv[], void *context) for the builtin command mycommand where argv is array an of argc elements and context is an optional pointer to a Shell_t structure as described in <ast/shell.h>. Special built-ins cannot be bound to a pathname or deleted. The -d option deletes each of the given built-ins. On systems that support dynamic loading, the -f option names a shared library containing the code for built-ins. The shared library prefix and/or suffix, which depend on the system, can be omitted. Once a library is loaded, its symbols become available for subsequent invocations of builtin. Multiple libraries can be specified with separate invocations of the builtin command. Libraries are searched in the reverse order in which they are specified. When a library is loaded, it looks for a function in the library whose name is lib_init() and invokes this function with an argument of 0. cd [ -LP ] [ arg ] cd [ -LP ] old new This command can be in either of two forms. In the first form it changes the current directory to arg. If arg is - the directory is changed to the previous directory. The shell variable HOME is the default arg. The variable PWD is set to the current directory. The shell variable CDPATH defines the search path for the directory containing arg. Alternative directory names are separated by a colon (:). The default path is <null> (specifying the current directory). Note that the current directory is specified by a null path name, which can appear immediately after the equal sign or between the colon delimiters anywhere else in the path list. If arg begins with a / then the search path is not used. Otherwise, each directory in the path is searched for arg. The second form of cd substitutes the string new for the string old in the current directory name, PWD, and tries to change to this new directory. By default, symbolic link names are treated literally when finding the directory name. This is equivalent to the -L option. The -P option causes symbolic links to be resolved when determining the directory. The last instance of -L or -P on the command line determines which method is used. The cd command may not be executed by rksh. rksh93. command [ -pvxV ] name [ arg ... ] Without the -v or -V options, command executes name with the arguments given by arg. The -p option causes a default path to be searched rather than the one defined by the value of PATH. Functions will not be searched for when finding name. In addition, if name refers to a special built-in, none of the special properties associated with the leading daggers will be honored. (For example, the predefined alias redirect=′command exec′ prevents a script from terminating when an invalid redirection is given.) With the -x option, if command execution would result in a failure because there are too many arguments, errno E2BIG, the shell will invoke command name multiple times with a subset of the arguments on each invocation. Arguments that occur prior to the first word that expands to multiple arguments and after the last word that expands to multiple arguments will be passed on each invocation. The exit status will be the maximum invocation exit status. With the -v option, command is equivalent to the built-in whence command described below. The -V option causes command to act like whence -v. † continue [ n ] Resume the next iteration of the enclosing for, while, until, or select loop. If n is specified, then resume at the n-th enclosing loop. disown [ job... ] Causes the shell not to send a HUP signal to each given job, or all active jobs if job is omitted, when a login shell terminates. echo [ arg ... ] When the first arg does not begin with a -, and none of the arguments contain a \, then echo prints each of its arguments separated by a space and terminated by a new-line. Otherwise, the behavior of echo is system dependent and print or printf described below should be used. See echo(1) for usage and description. †† enum [ -i ] type[=(value ...) ] Creates a declaration command named type that is an integer type that allows one of the specified values as enumeration names. If =(value_...) is omitted, then type must be an indexed array variable with at least two elements and the values are taken from this array variable. If -i is specified the values are case insensitive. † eval [ arg ... ] The arguments are read as input to the shell and the resulting command(s) executed. † exec [ -c ] [ -a name ] [ arg ... ] If arg is given, the command specified by the arguments is executed in place of this shell without creating a new process. The -c option causes the environment to be cleared before applying variable assignments associated with the exec invocation. The -a option causes name rather than the first arg, to become argv[0] for the new process. Input/output arguments may appear and affect the current process. If arg is not given, the effect of this command is to modify file descriptors as prescribed by the input/output redirection list. In this case, any file descriptor numbers greater than 2 that are opened with this mechanism are closed when invoking another program. † exit [ n ] Causes the shell to exit with the exit status specified by n. The value will be the least significant 8 bits of the specified status. If n is omitted, then the exit status is that of the last command executed. An end-of-file will also cause the shell to exit except for a shell which has the ignoreeof option (see set below) turned on. †† export [ -p ] [ name[=value] ] ... If name is not given, the names and values of each variable with the export attribute are printed with the values quoted in a manner that allows them to be re-input. The export command is the same as typeset -x except that if you use export within a function, no local variable is created. The -p option causes the word export to be inserted before each one. Otherwise, the given names are marked for automatic export to the environment of subsequently-executed commands. false Does nothing, and exits 1. Used with until for infinite loops. fg [ job... ] This command is only on systems that support job control. Each job specified is brought to the foreground and waited for in the specified order. Otherwise, the current job is brought into the foreground. See Jobs for a description of the format of job. getconf [ name [ pathname ] ] Prints the current value of the configuration parameter given by name. The configuration parameters are defined by the IEEE POSIX 1003.1 and IEEE POSIX 1003.2 standards. (See pathconf(2) and sysconf(2).) The pathname argument is required for parameters whose value depends on the location in the file system. If no arguments are given, getconf prints the names and values of the current configuration parameters. The pathname / is used for each of the parameters that requires pathname. getopts [ -a name ] optstring vname [ arg ... ] Checks arg for legal options. If arg is omitted, the positional parameters are used. An option argument begins with a + or a -. An option not beginning with + or - or the argument -- ends the options. Options beginning with + are only recognized when optstring begins with a +. 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. The option -? causes getopts to generate a usage message on standard error. The -a argument can be used to specify the name to use for the usage message, which defaults to $0. getopts places the next option letter it finds inside variable vname each time it is invoked. The option letter will be prepended with a + when arg begins with a +. The index of the next arg is stored in OPTIND. The option argument, if any, gets stored in OPTARG. A leading : in optstring causes getopts to store the letter of an invalid option in OPTARG, and to set vname to ? for an unknown option and to : when a required option argument is missing. Otherwise, getopts prints an error message. The exit status is non-zero when there are no more options. There is no way to specify any of the options :, +, -, ?, [, and ]. The option # can only be specified as the first option. hist [ -e ename ] [ -nlr ] [ first [ last ] ] hist -s [ old=new ] [ command ] In the first form, a range of commands from first to last is selected from the last HISTSIZE commands that were typed at the terminal. The arguments first and last may be specified as a number or as a string. A string is used to locate the most recent command starting with the given string. A negative number is used as an offset to the current command number. If the -l option is selected, the commands are listed on standard output. Otherwise, the editor program ename is invoked on a file containing these keyboard commands. If ename is not supplied, then the value of the variable HISTEDIT is used. If HISTEDIT is not set, then FCEDIT (default /bin/ed) is used as the editor. When editing is complete, the edited command(s) is executed if the changes have been saved. If last is not specified, then it will be set to first. If first is not specified, the default is the previous command for editing and -16 for listing. The option -r reverses the order of the commands and the option -n suppresses command numbers when listing. In the second form, command is interpreted as first described above and defaults to the last command executed. The resulting command is executed after the optional substitution old=new is performed. jobs [ -lnp ] [ job ... ] Lists information about each given job; or all active jobs if job is omitted. The -l option lists process ids in addition to the normal information. The -n option only displays jobs that have stopped or exited since last notified. The -p option causes only the process group to be listed. See Jobs for a description of the format of job. kill [ -s signame ] job ... kill [ -n signum ] job ... kill -Ll [ sig ... ] Sends either the TERM (terminate) signal or the specified signal to the specified jobs or processes. Signals are either given by number with the -n option or by name with the -s option (as given in <signal.h>, stripped of the prefix ``SIG'' with the exception that SIGCLD is named CHLD). For backward compatibility, the n and s can be omitted and the number or name placed immediately after the -. If the signal being sent is TERM (terminate) or HUP (hangup), then the job or process will be sent a CONT (continue) signal if it is stopped. The argument job can be the process id of a process that is not a member of one of the active jobs. See Jobs for a description of the format of job. In the third form, kill -l, or kill -L, if sig is not specified, the signal names are listed. The -l option list only the signal names. -L options lists each signal name and corresponding number. Otherwise, for each sig that is a name, the corresponding signal number is listed. For each sig that is a number, the signal name corresponding to the least significant 8 bits of sig is listed. let arg ... Each arg is a separate arithmetic expression to be evaluated. let only recognizes octal constants starting with 0 when the set option letoctal is on. See Arithmetic Evaluation above, for a description of arithmetic expression evaluation. The exit status is 0 if the value of the last expression is non- zero, and 1 otherwise. † newgrp [ arg ... ] Equivalent to exec /bin/newgrp arg .... print [ -CRenprsv ] [ -u unit] [ -f format ] [ arg ... ] With no options or with option - or --, each arg is printed on standard output. The -f option causes the arguments to be printed as described by printf. In this case, any e, n, r, R options are ignored. Otherwise, unless the -C, -R, -r, or -v are specified, the following escape conventions will be applied: \a The alert character (ascii 07). \b The backspace character (ascii 010). \c Causes print to end without processing more arguments and not adding a new-line. \f The formfeed character (ascii 014). \n The new-line character (ascii 012). \r The carriage return character (ascii 015). \t The tab character (ascii 011). \v The vertical tab character (ascii 013). \E The escape character (ascii 033). \\ The backslash character \. \0x The character defined by the 1, 2, or 3-digit octal string given by x. The -R option will print all subsequent arguments and options other than -n. The -e causes the above escape conventions to be applied. This is the default behavior. It reverses the effect of an earlier -r. The -p option causes the arguments to be written onto the pipe of the process spawned with ⎪& instead of standard output. The -v option treats each arg as a variable name and writes the value in the printf %B format. The -C option treats each arg as a variable name and writes the value in the printf %#B format. The -s option causes the arguments to be written onto the history file instead of standard output. The -u option can be used to specify a one digit file descriptor unit number unit on which the output will be placed. The default is 1. If the option -n is used, no new-line is added to the output. printf format [ arg ... ] The arguments arg are printed on standard output in accordance with the ANSI-C formatting rules associated with the format string format. If the number of arguments exceeds the number of format specifications, the format string is reused to format remaining arguments. The following extensions can also be used: %b A %b format can be used instead of %s to cause escape sequences in the corresponding arg to be expanded as described in print. %B A %B option causes each of the arguments to be treated as variable names and the binary value of variable will be printed. The alternate flag # causes a compound variable to be output on a single line. This is most useful for compound variables and variables whose attribute is -b. %H A %H format can be used instead of %s to cause characters in arg that are special in HTML and XML to be output as their entity name. The alternate flag # formats the output for use as a URI. %P A %P format can be used instead of %s to cause arg to be interpreted as an extended regular expression and be printed as a shell pattern. %R A %R format can be used instead of %s to cause arg to be interpreted as a shell pattern and to be printed as an extended regular expression. %q A %q format can be used instead of %s to cause the resulting string to be quoted in a manner than can be reinput to the shell. When q is preceded by the alternative format specifier, #, the string is quoted in manner suitable as a field in a .csv format file. %(date-format)T A %(date-format)T format can be use to treat an argument as a date/time string and to format the date/time according to the date-format as defined for the date(1) command. %Z A %Z format will output a byte whose value is 0. %d The precision field of the %d format can be followed by a . and the output base. In this case, the # flag character causes base# to be prepended. # The # flag, when used with the %d format without an output base, displays the output in powers of 1000 indicated by one of the following suffixes: k M G T P E, and when used with the %i format displays the output in powers of 1024 indicated by one of the following suffixes: Ki Mi Gi Ti Pi Ei. = The = flag centers the output within the specified field width. L The L flag, when used with the %c or %s formats, treats precision as character width instead of byte count. , The , flag, when used with the %d or %f formats, separates groups of digits with the grouping delimiter (, on groups of 3 in the C locale.) pwd [ -LP ] Outputs the value of the current working directory. The -L option is the default; it prints the logical name of the current directory. If the -P option is given, all symbolic links are resolved from the name. The last instance of -L or -P on the command line determines which method is used. read [ -ACSprsv ] [ -d delim] [ -n n] [ [ -N n] [ [ -t timeout] [ -u unit] [ vname?prompt ] [ vname ... ] The shell input mechanism. One line is read and is broken up into fields using the characters in IFS as separators. The escape character, \, is used to remove any special meaning for the next character and for line continuation. The -d option causes the read to continue to the first character of delim rather than new-line. The -n option causes at most n bytes to read rather a full line but will return when reading from a slow device as soon as any characters have been read. The -N option causes exactly n to be read unless an end-of-file has been encountered or the read times out because of the -t option. In raw mode, -r, the \ character is not treated specially. The first field is assigned to the first vname, the second field to the second vname, etc., with leftover fields assigned to the last vname. When vname has the binary attribute and -n or -N is specified, the bytes that are read are stored directly into the variable. If the -v is specified, then the value of the first vname will be used as a default value when reading from a terminal device. The -A option causes the variable vname to be unset and each field that is read to be stored in successive elements of the indexed array vname. The -C option causes the variable vname to be read as a compound variable. Blanks will be ignored when finding the beginning open parenthesis. The -S option causes the line to be treated like a record in a .csv format file so that double quotes can be used to allow the delimiter character and the new-line character to appear within a field. The -p option causes the input line to be taken from the input pipe of a process spawned by the shell using ⎪&. If the -s option is present, the input will be saved as a command in the history file. The option -u can be used to specify a one digit file descriptor unit unit to read from. The file descriptor can be opened with the exec special built-in command. The default value of unit n is 0. The option -t is used to specify a timeout in seconds when reading from a terminal or pipe. If vname is omitted, then REPLY is used as the default vname. An end-of-file with the -p option causes cleanup for this process so that another can be spawned. 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 exit status is 0 unless an end-of-file is encountered or read has timed out. †† readonly [ -p ] [ vname[=value] ] ... If vname is not given, the names and values of each variable with the readonly attribute is printed with the values quoted in a manner that allows them to be re-inputted. The -p option causes the word readonly to be inserted before each one. Otherwise, the given vnames are marked readonly and these names cannot be changed by subsequent assignment. When defining a type, if the value of a readonly sub-variable is not defined the value is required when creating each instance. † return [ n ] Causes a shell function or . script to return to the invoking script with the exit status specified by n. The value will be the least significant 8 bits of the specified status. If n is omitted, then the return status is that of the last command executed. If return is invoked while not in a function or a . script, then it behaves the same as exit. † set [ ±BCGabefhkmnoprstuvx ] [ ±o [ option ] ] ... [ ±A vname ] [ arg ... ] The options for this command have meaning as follows: -A Array assignment. Unset the variable vname and assign values sequentially from the arg list. If +A is used, the variable vname is not unset first. -B Enable brace pattern field generation. This is the default behavior. -B Enable brace group expansion. On by default. -C Prevents redirection > from truncating existing files. Files that are created are opened with the O_EXCL mode. Requires >⎪ to truncate a file when turned on. -G Causes the pattern ∗∗ by itself to match files and zero or more directories and sub-directories when used for file name generation. If followed by a / only directories and sub-directories are matched. -a All subsequent variables that are defined are automatically exported. -b Prints job completion messages as soon as a background job changes state rather than waiting for the next prompt. -e Unless contained in a ⎪⎪ or && command, or the command following an if while or until command or in the pipeline following !, if a command has a non-zero exit status, execute the ERR trap, if set, and exit. This mode is disabled while reading profiles. -f Disables file name generation. -h Each command becomes a tracked alias when first encountered. -k (Obsolete). All variable assignment arguments are placed in the environment for a command, not just those that precede the command name. -m Background jobs will run in a separate process group and a line will print upon completion. The exit status of background jobs is reported in a completion message. On systems with job control, this option is turned on automatically for interactive shells. -n Read commands and check them for syntax errors, but do not execute them. Ignored for interactive shells. -o The following argument can be one of the following option names: allexport Same as -a. errexit Same as -e. bgnice All background jobs are run at a lower priority. This is the default mode. braceexpand Same as -B. emacs Puts you in an emacs style in-line editor for command entry. globstar Same as -G. gmacs Puts you in a gmacs style in-line editor for command entry. ignoreeof The shell will not exit on end-of-file. The command exit must be used. keyword Same as -k. letoctal The let command allows octal constants starting with 0. markdirs All directory names resulting from file name generation have a trailing / appended. monitor Same as -m. multiline The built-in editors will use multiple lines on the screen for lines that are longer than the width of the screen. This may not work for all terminals. noclobber Same as -C. noexec Same as -n. noglob Same as -f. nolog Do not save function definitions in the history file. notify Same as -b. nounset Same as -u. pipefail A pipeline will not complete until all components of the pipeline have completed, and the return value will be the value of the last non-zero command to fail or zero if no command has failed. showme When enabled, simple commands or pipelines preceded by a semicolon (;) will be displayed as if the xtrace option were enabled but will not be executed. Otherwise, the leading ; will be ignored. privileged Same as -p. verbose Same as -v. trackall Same as -h. vi Puts you in insert mode of a vi style in-line editor until you hit the escape character 033. This puts you in control mode. A return sends the line. viraw Each character is processed as it is typed in vi mode. xtrace Same as -x. If no option name is supplied, then the current option settings are printed. -p Disables processing of the $HOME/.profile file and uses the file /etc/suid_profile instead of the ENV file. This mode is on whenever the effective uid (gid) is not equal to the real uid (gid). Turning this off causes the effective uid and gid to be set to the real uid and gid. -r Enables the restricted shell. This option cannot be unset once set. -s Sort the positional parameters lexicographically. -t (Obsolete). Exit after reading and executing one command. -u Treat unset parameters as an error when substituting. -v Print shell input lines as they are read. -x Print commands and their arguments as they are executed. -- Do not change any of the options; useful in setting $1 to a value beginning with -. If no arguments follow this option then the positional parameters are unset. As an obsolete feature, if the first arg is - then the -x and -v options are turned off and the next arg is treated as the first argument. Using + rather than - causes these options to be turned off. These options can also be used upon invocation of the shell. The current set of options may be found in $-. Unless -A is specified, the remaining arguments are positional parameters and are assigned, in order, to $1 $2 .... If no arguments are given, then the names and values of all variables are printed on the standard output. † shift [ n ] The positional parameters from $n+1 ... are renamed $1 ... , default n is 1. The parameter n can be any arithmetic expression that evaluates to a non-negative number less than or equal to $#. sleep seconds Suspends execution for the number of decimal seconds or fractions of a second given by seconds. † trap [ -p ] [ action ] [ sig ] ... The -p option causes the trap action associated with each trap as specified by the arguments to be printed with appropriate quoting. Otherwise, action will be processed as if it were an argument to eval when the shell receives signal(s) sig. Each sig can be given as a number or as the name of the signal. Trap commands are executed in order of signal number. Any attempt to set a trap on a signal that was ignored on entry to the current shell is ineffective. If action is omitted and the first sig is a number, or if action is -, then the trap(s) for each sig are reset to their original values. If action is the null string then this signal is ignored by the shell and by the commands it invokes. If sig is ERR then action will be executed whenever a command has a non-zero exit status. If sig is DEBUG then action will be executed before each command. The variable .sh.command will contain the contents of the current command line when action is running. If the exit status of the trap is 2 the command will not be executed. If the exit status of the trap is 255 and inside a function or a dot script, the function or dot script will return. If sig is 0 or EXIT and the trap statement is executed inside the body of a function defined with the function name syntax, then the command action is executed after the function completes. If sig is 0 or EXIT for a trap set outside any function then the command action is executed on exit from the shell. If sig is KEYBD, then action will be executed whenever a key is read while in emacs, gmacs, or vi mode. The trap command with no arguments prints a list of commands associated with each signal number. An exit or return without an argument in a trap action will preserve the exit status of the command that invoked the trap. true Does nothing, and exits 0. Used with while for infinite loops. †† typeset [ ±ACHSfblmnprtux ] [ ±EFLRXZi[n] ] [ +-M [ mapname ] ] [ -T [ tname=(assign_list) ] ] [ -h str ] [ -a [type] ] [ vname[=value ] ] ... Sets attributes and values for shell variables and functions. When invoked inside a function defined with the function name syntax, a new instance of the variable vname is created, and the variable's value and type are restored when the function completes. The following list of attributes may be specified: -A Declares vname to be an associative array. Subscripts are strings rather than arithmetic expressions. -C causes each vname to be a compound variable. value names a compound variable it is copied into vname. Otherwise, it unsets each vname. -a Declares vname to be an indexed array. If type is specified, it must be the name of an enumeration type created with the enum command and it allows enumeration constants to be used as subscripts. -E Declares vname to be a double precision floating point number. If n is non-zero, it defines the number of significant figures that are used when expanding vname. Otherwise, ten significant figures will be used. -F Declares vname to be a double precision floating point number. If n is non-zero, it defines the number of places after the decimal point that are used when expanding vname. Otherwise ten places after the decimal point will be used. -H This option provides UNIX to host-name file mapping on non-UNIX machines. -L Left justify and remove leading blanks from value. If n is non-zero, it defines the width of the field, otherwise it is determined by the width of the value of first assignment. When the variable is assigned to, it is filled on the right with blanks or truncated, if necessary, to fit into the field. The -R option is turned off. -M Use the character mapping mapping defined by wctrans(3). such as tolower and toupper when assigning a value to each of the specified operands. When mapping is specified and there are not operands, all variables that use this mapping are written to standard output. When mapping is omitted and there are no operands, all mapped variables are written to standard output. -R Right justify and fill with leading blanks. If n is non- zero, it defines the width of the field, otherwise it is determined by the width of the value of first assignment. The field is left filled with blanks or truncated from the end if the variable is reassigned. The -L option is turned off. -S When used within the assign_list of a type definition, it causes the specified sub-variable to be shared by all instances of the type. When used inside a function defined with the function reserved word, the specified variables will have function static scope. Otherwise, the variable is unset prior to processing the assignment list. -T If followed by tname, it creates a type named by tname using the compound assignment assign_list to tname. Otherwise, it writes all the type definitions to standard output. -X Declares vname to be a double precision floating point number and expands using the %a format of ISO-C99. If n is non-zero, it defines the number of hex digits after the radix point that is used when expanding vname. The default is 10. -Z Right justify and fill with leading zeros if the first non-blank character is a digit and the -L option has not been set. Remove leading zeros if the -L option is also set. If n is non-zero, it defines the width of the field, otherwise it is determined by the width of the value of first assignment. -f The names refer to function names rather than variable names. No assignments can be made and the only other valid options are -S, -t, -u and -x. The -S can be used with discipline functions defined in a type to indicate that the function is static. For a static function, the same method will be used by all instances of that type no matter which instance references it. In addition, it can only use value of variables from the original type definition. These discipline functions cannot be redefined in any type instance. The -t option turns on execution tracing for this function. The -u option causes this function to be marked undefined. The FPATH variable will be searched to find the function definition when the function is referenced. If no options other than -f is specified, then the function definition will be displayed on standard output. If +f is specified, then a line containing the function name followed by a shell comment containing the line number and path name of the file where this function was defined, if any, is displayed. The exit status can be used to determine whether the function is defined so that typeset -f .sh.math.name will return 0 when math function name is defined and non-zero otherwise. -b The variable can hold any number of bytes of data. The data can be text or binary. The value is represented by the base64 encoding of the data. If -Z is also specified, the size in bytes of the data in the buffer will be determined by the size associated with the -Z. If the base64 string assigned results in more data, it will be truncated. Otherwise, it will be filled with bytes whose value is zero. The printf format %B can be used to output the actual data in this buffer instead of the base64 encoding of the data. -h Used within type definitions to add information when generating information about the sub-variable on the man page. It is ignored when used outside of a type definition. When used with -f the information is associated with the corresponding discipline function. -i Declares vname to be represented internally as integer. The right hand side of an assignment is evaluated as an arithmetic expression when assigning to an integer. If n is non-zero, it defines the output arithmetic base, otherwise the output base will be ten. -l Used with -i, -E or -F, to indicate long integer, or long float. Otherwise, all upper-case characters are converted to lower-case. The upper-case option, -u, is turned off. Equivalent to -M tolower . -m moves or renames the variable. The value is the name of a variable whose value will be moved to vname. The original variable will be unset. Cannot be used with any other options. -n Declares vname to be a reference to the variable whose name is defined by the value of variable vname. This is usually used to reference a variable inside a function whose name has been passed as an argument. Cannot be used with any other options. -p The name, attributes and values for the given vnames are written on standard output in a form that can be used as shell input. If +p is specified, then the values are not displayed. -r The given vnames are marked readonly and these names cannot be changed by subsequent assignment. -t Tags the variables. Tags are user definable and have no special meaning to the shell. -u When given along with -i, specifies unsigned integer. Otherwise, all lower-case characters are converted to upper-case. The lower-case option, -l, is turned off. Equivalent to -M toupper . -x The given vnames are marked for automatic export to the environment of subsequently-executed commands. Variables whose names contain a . cannot be exported. The -i attribute cannot be specified along with -R, -L, -Z, or -f. Using + rather than - causes these options to be turned off. If no vname arguments are given, a list of vnames (and optionally the values) of the variables is printed. (Using + rather than - keeps the values from being printed.) The -p option causes typeset followed by the option letters to be printed before each name rather than the names of the options. If any option other than -p is given, only those variables which have all of the given options are printed. Otherwise, the vnames and attributes of all variables that have attributes are printed. ulimit [ -HSacdfmnpstv ] [ limit ] Set or display a resource limit. The available resource limits are listed below. Many systems do not support one or more of these limits. The limit for a specified resource is set when limit is specified. The value of limit can be a number in the unit specified below with each resource, or the value unlimited. The -H and -S options specify whether the hard limit or the soft limit for the given resource is set. A hard limit cannot be increased once it is set. A soft limit can be increased up to the value of the hard limit. If neither the H nor S option is specified, the limit applies to both. The current resource limit is printed when limit is omitted. In this case, the soft limit is printed unless H is specified. When more than one resource is specified, then the limit name and unit is printed before the value. -a Lists all of the current resource limits. -c The number of 512-byte blocks on the size of core dumps. -d The number of K-bytes on the size of the data area. -f The number of 512-byte blocks on files that can be written by the current process or by child processes (files of any size may be read). -m The number of K-bytes on the size of physical memory. -n The number of file descriptors plus 1. -p The number of 512-byte blocks for pipe buffering. -s The number of K-bytes on the size of the stack area. -t The number of CPU seconds to be used by each process. -v The number of K-bytes for virtual memory. If no option is given, -f is assumed. umask [ -S ] [ mask ] The user file-creation mask is set to mask (see umask(2)). mask can either be an octal number or a symbolic value as described in chmod(1). If a symbolic value is given, the new umask value is the complement of the result of applying mask to the complement of the previous umask value. If mask is omitted, the current value of the mask is printed. The -S option causes the mode to be printed as a symbolic value. Otherwise, the mask is printed in octal. † unalias [ -a ] name ... The aliases given by the list of names are removed from the alias list. The -a option causes all the aliases to be unset. †unset [ -fnv ] vname ... The variables given by the list of vnames are unassigned, i.e., except for sub-variables within a type, their values and attributes are erased. For sub-variables of a type, the values are reset to the default value from the type definition. Readonly variables cannot be unset. If the -f option is set, then the names refer to function names. If the -v option is set, then the names refer to variable names. The -f option overrides -v. If -n is set and name is a name reference, then name will be unset rather than the variable that it references. The default is equivalent to -v. Unsetting LINENO, MAILCHECK, OPTARG, OPTIND, RANDOM, SECONDS, TMOUT, and _ removes their special meaning even if they are subsequently assigned to. wait [ job ... ] Wait for the specified job and report its termination status. If job is not given, then all currently active child processes are waited for. The exit status from this command is that of the last process waited for if job is specified; otherwise it is zero. See Jobs for a description of the format of job. whence [ -afpv ] name ... For each name, indicate how it would be interpreted if used as a command name. The -v option produces a more verbose report. The -f option skips the search for functions. The -p option does a path search for name even if name is an alias, a function, or a reserved word. The -p option turns off the -v option. The -a option is similar to the -v option but causes all interpretations of the given name to be reported. Invocation. If the shell is invoked by exec(2), and the first character of argument zero ($0) is -, then the shell is assumed to be a login shell and commands are read from /etc/profile and then from either .profile in the current directory or $HOME/.profile, if either file exists. Next, for interactive shells, commands are read from the file named by performing parameter expansion, command substitution, and arithmetic substitution on the value of the environment variable ENV if the file exists. If the -s option is not present and arg and a file by the name of arg exists, then it reads and executes this script. Otherwise, if the first arg does not contain a /, a path search is performed on the first arg to determine the name of the script to execute. The script arg must have execute permission and any setuid and setgid settings will be ignored. If the script is not found on the path, arg is processed as if it named a built-in command or function. Commands are then read as described below; the following options are interpreted by the shell when it is invoked: -D Do not execute the script, but output the set of double quoted strings preceded by a $. These strings are needed for localization of the script to different locales. -E Reads the file named by the ENV variable or by $HOME/.kshrc if not defined after the profiles. -c If the -c option is present, then commands are read from the first arg. Any remaining arguments become positional parameters starting at 0. -s If the -s option is present or if no arguments remain, then commands are read from the standard input. Shell output, except for the output of the Special Commands listed above, is written to file descriptor 2. -i If the -i option is present or if the shell input and output are attached to a terminal (as told by tcgetattr(2)), then this shell is interactive. In this case TERM is ignored (so that kill 0 does not kill an interactive shell) and INTR is caught and ignored (so that wait is ). In all cases, QUIT is ignored by the shell. -r If the -r option is present, the shell is a restricted shell. -D A list of all double quoted strings that are preceded by a $ will be printed on standard output and the shell will exit. This set of strings will be subject to language translation when the locale is not C or POSIX. No commands will be executed. -P If -P or -o profile is present, the shell is a profile shell (see pfexec(1)). -R filename The -R filename option is used to generate a cross reference database that can be used by a separate utility to find definitions and references for variables and commands. The remaining options and arguments are described under the set command above. An optional - as the first argument is ignored. Rksh Only. Rksh is used to set up login names and execution environments whose capabilities are more controlled than those of the standard shell. The actions of rksh are identical to those of ksh, except that the following are disallowed: Unsetting the restricted option. changing directory (see cd(1)), setting or unsetting the value or attributes of SHELL, ENV, FPATH, or PATH, specifying path or command names containing /, redirecting output (>, >|, <>, and >>). adding or deleting built-in commands. using command -p to invoke a command. The restrictions above are enforced after .profile and the ENV files are interpreted. When a command to be executed is found to be a shell procedure, rksh invokes ksh to execute it. Thus, it is possible to provide to the end- user shell procedures that have access to the full power of the standard shell, while imposing a limited menu of commands; this scheme assumes that the end-user does not have write and execute permissions in the same directory. The net effect of these rules is that the writer of the .profile has complete control over user actions, by performing guaranteed setup actions and leaving the user in an appropriate directory (probably not the login directory). The system administrator often sets up a directory of commands (e.g., /usr/rbin) that can be safely invoked by rksh. EXIT STATUS Errors detected by the shell, such as syntax errors, cause the shell to return a non-zero exit status. If the shell is being used non- interactively, then execution of the shell file is abandoned unless the error occurs inside a subshell in which case the subshell is abandoned. Otherwise, the shell returns the exit status of the last command executed (see also the exit command above). Run time errors detected by the shell are reported by printing the command or function name and the error condition. If the line number that the error occurred on is greater than one, then the line number is also printed in square brackets ([]) after the command or function name. FILES /etc/profile The system wide initialization file, executed for login shells. $HOME/.profile The personal initialization file, executed for login shells after /etc/profile. $HOME/..kshrc Default personal initialization file, executed for interactive shells when ENV is not set. /etc/suid_profile Alternative initialization file, executed instead of the personal initialization file when the real and effective user or group id do not match. /dev/null NULL device SEE ALSO cat(1), cd(1), chmod(1), cut(1), egrep(1), echo(1), emacs(1), env(1), fgrep(1), gmacs(1), grep(1), newgrp(1), pfexec(1), stty(1), test(1), umask(1), vi(1), dup(2), exec(2), fork(2), getpwnam(3), ioctl(2), lseek(2), paste(1), pathconf(2), pipe(2), sysconf(2), umask(2), ulimit(2), wait(2), wctrans(3), rand(3), a.out(5), profile(5), environ(7). Morris I. Bolsky and David G. Korn, The New KornShell Command and Programming Language, Prentice Hall, 1995. POSIX - Part 2: Shell and Utilities, IEEE Std 1003.2-1992, ISO/IEC 9945-2, IEEE, 1993. CAVEATS If a command is executed, and then a command with the same name is installed in a directory in the search path before the directory where the original command was found, the shell will continue to exec the original command. Use the -t option of the alias command to correct this situation. Some very old shell scripts contain a ^ as a synonym for the pipe character ⎪. Using the hist built-in command within a compound command will cause the whole command to disappear from the history file. The built-in command . file reads the whole file before any commands are executed. Therefore, alias and unalias commands in the file will not apply to any commands defined in the file. Traps are not processed while a job is waiting for a foreground process. Thus, a trap on CHLD won't be executed until the foreground job terminates. It is a good idea to leave a space after the comma operator in arithmetic expressions to prevent the comma from being interpreted as the decimal point character in certain locales. KSH(1)
ksh, rksh, pfksh - KornShell, a standard/restricted command and programming language NOTE Currently, rksh and pfksh are not available on Mac OS X / Darwin.
ksh [ ±abcefhikmnoprstuvxBCDP ] [ -R file ] [ ±o option ] ... [ - ] [ arg ... ] rksh [ ±abcefhikmnoprstuvxBCD ] [ -R file ] [ ±o option ] ... [ - ] [ arg ... ]
null
null
hostname
The hostname utility prints the name of the current host. The super-user can set the hostname by supplying an argument. To keep the hostname between reboots, run ‘scutil --set HostName name-of-host’. Options: -f Include domain information in the printed name. This is the default behavior. -s Trim off any domain information from the printed name. -d Only print domain information.
hostname – set or print name of current host system
hostname [-f] [-s | -d] [name-of-host]
null
Set the host name of the machine and check the result: $ hostname beastie.localdomain.org $ hostname beastie.localdomain.org Do not show domain information: $ hostname -s beastie Show only domain information: $ hostname -d localdomain.org SEE ALSO gethostname(3), scutil(8) HISTORY The hostname command appeared in 4.2BSD. macOS 14.5 October 5, 2020 macOS 14.5
dash
dash is the standard command interpreter for the system. The current version of dash is in the process of being changed to conform with the POSIX 1003.2 and 1003.2a specifications for the shell. This version has many features which make it appear similar in some respects to the Korn shell, but it is not a Korn shell clone (see ksh(1)). Only features designated by POSIX, plus a few Berkeley extensions, are being incorporated into this shell. This man page is not intended to be a tutorial or a complete specification of the shell. Overview The shell is a command that reads lines from either a file or the terminal, interprets them, and generally executes other commands. It is the program that is running when a user logs into the system (although a user can select a different shell with the chsh(1) command). The shell implements a language that has flow control constructs, a macro facility that provides a variety of features in addition to data storage, along with built in history and line editing capabilities. It incorporates many features to aid interactive use and has the advantage that the interpretative language is common to both interactive and non-interactive use (shell scripts). That is, commands can be typed directly to the running shell or can be put into a file and the file can be executed directly by the shell. Invocation If no args are present and if the standard input of the shell is connected to a terminal (or if the -i flag is set), and the -c option is not present, the shell is considered an interactive shell. An interactive shell generally prompts before each command and handles programming and command errors differently (as described below). When first starting, the shell inspects argument 0, and if it begins with a dash ‘-’, the shell is also considered a login shell. This is normally done automatically by the system when the user first logs in. A login shell first reads commands from the files /etc/profile and .profile if they exist. If the environment variable ENV is set on entry to an interactive shell, or is set in the .profile of a login shell, the shell next reads commands from the file named in ENV. Therefore, a user should place commands that are to be executed only at login time in the .profile file, and commands that are executed for every interactive shell inside the ENV file. To set the ENV variable to some file, place the following line in your .profile of your home directory ENV=$HOME/.shinit; export ENV substituting for “.shinit” any filename you wish. If command line arguments besides the options have been specified, then the shell treats the first argument as the name of a file from which to read commands (a shell script), and the remaining arguments are set as the positional parameters of the shell ($1, $2, etc). Otherwise, the shell reads commands from its standard input. Argument List Processing All of the single letter options that have a corresponding name can be used as an argument to the -o option. The set -o name is provided next to the single letter option in the description below. Specifying a dash “-” turns the option on, while using a plus “+” disables the option. The following options can be set from the command line or with the set builtin (described later). -a allexport Export all variables assigned to. -c Read commands from the command_string operand instead of from the standard input. Special parameter 0 will be set from the command_name operand and the positional parameters ($1, $2, etc.) set from the remaining argument operands. -C noclobber Don't overwrite existing files with “>”. -e errexit If not interactive, exit immediately if any untested command fails. The exit status of a command is considered to be explicitly tested if the command is used to control an if, elif, while, or until; or if the command is the left hand operand of an “&&” or “||” operator. -f noglob Disable pathname expansion. -n noexec If not interactive, read commands but do not execute them. This is useful for checking the syntax of shell scripts. -u nounset Write a message to standard error when attempting to expand a variable that is not set, and if the shell is not interactive, exit immediately. -v verbose The shell writes its input to standard error as it is read. Useful for debugging. -x xtrace Write each command to standard error (preceded by a ‘+ ’) before it is executed. Useful for debugging. -I ignoreeof Ignore EOF's from input when interactive. -i interactive Force the shell to behave interactively. -l Make dash act as if it had been invoked as a login shell. -m monitor Turn on job control (set automatically when interactive). -s stdin Read commands from standard input (set automatically if no file arguments are present). This option has no effect when set after the shell has already started running (i.e. with set). -V vi Enable the built-in vi(1) command line editor (disables -E if it has been set). -E emacs Enable the built-in emacs(1) command line editor (disables -V if it has been set). -b notify Enable asynchronous notification of background job completion. (UNIMPLEMENTED for 4.4alpha) Lexical Structure The shell reads input in terms of lines from a file and breaks it up into words at whitespace (blanks and tabs), and at certain sequences of characters that are special to the shell called “operators”. There are two types of operators: control operators and redirection operators (their meaning is discussed later). Following is a list of operators: Control operators: & && ( ) ; ;; | || <newline> Redirection operators: < > >| << >> <& >& <<- <> Quoting Quoting is used to remove the special meaning of certain characters or words to the shell, such as operators, whitespace, or keywords. There are three types of quoting: matched single quotes, matched double quotes, and backslash. Backslash A backslash preserves the literal meaning of the following character, with the exception of ⟨newline⟩. A backslash preceding a ⟨newline⟩ is treated as a line continuation. Single Quotes Enclosing characters in single quotes preserves the literal meaning of all the characters (except single quotes, making it impossible to put single-quotes in a single-quoted string). Double Quotes Enclosing characters within double quotes preserves the literal meaning of all characters except dollarsign ($), backquote (`), and backslash (\). The backslash inside double quotes is historically weird, and serves to quote only the following characters: $ ` " \ <newline>. Otherwise it remains literal. Reserved Words Reserved words are words that have special meaning to the shell and are recognized at the beginning of a line and after a control operator. The following are reserved words: ! elif fi while case else for then { } do done until if esac Their meaning is discussed later. Aliases An alias is a name and corresponding value set using the alias(1) builtin command. Whenever a reserved word may occur (see above), and after checking for reserved words, the shell checks the word to see if it matches an alias. If it does, it replaces it in the input stream with its value. For example, if there is an alias called “lf” with the value “ls -F”, then the input: lf foobar ⟨return⟩ would become ls -F foobar ⟨return⟩ Aliases provide a convenient way for naive users to create shorthands for commands without having to learn how to create functions with arguments. They can also be used to create lexically obscure code. This use is discouraged. Commands The shell interprets the words it reads according to a language, the specification of which is outside the scope of this man page (refer to the BNF in the POSIX 1003.2 document). Essentially though, a line is read and if the first word of the line (or after a control operator) is not a reserved word, then the shell has recognized a simple command. Otherwise, a complex command or some other special construct may have been recognized. Simple Commands If a simple command has been recognized, the shell performs the following actions: 1. Leading words of the form “name=value” are stripped off and assigned to the environment of the simple command. Redirection operators and their arguments (as described below) are stripped off and saved for processing. 2. The remaining words are expanded as described in the section called “Expansions”, and the first remaining word is considered the command name and the command is located. The remaining words are considered the arguments of the command. If no command name resulted, then the “name=value” variable assignments recognized in item 1 affect the current shell. 3. Redirections are performed as described in the next section. Redirections Redirections are used to change where a command reads its input or sends its output. In general, redirections open, close, or duplicate an existing reference to a file. The overall format used for redirection is: [n] redir-op file where redir-op is one of the redirection operators mentioned previously. Following is a list of the possible redirections. The [n] is an optional number between 0 and 9, as in ‘3’ (not ‘[3]’), that refers to a file descriptor. [n]> file Redirect standard output (or n) to file. [n]>| file Same, but override the -C option. [n]>> file Append standard output (or n) to file. [n]< file Redirect standard input (or n) from file. [n1]<&n2 Copy file descriptor n2 as stdout (or fd n1). fd n2. [n]<&- Close standard input (or n). [n1]>&n2 Copy file descriptor n2 as stdin (or fd n1). fd n2. [n]>&- Close standard output (or n). [n]<> file Open file for reading and writing on standard input (or n). The following redirection is often called a “here-document”. [n]<< delimiter here-doc-text ... delimiter All the text on successive lines up to the delimiter is saved away and made available to the command on standard input, or file descriptor n if it is specified. If the delimiter as specified on the initial line is quoted, then the here-doc-text is treated literally, otherwise the text is subjected to parameter expansion, command substitution, and arithmetic expansion (as described in the section on “Expansions”). If the operator is “<<-” instead of “<<”, then leading tabs in the here-doc-text are stripped. Search and Execution There are three types of commands: shell functions, builtin commands, and normal programs -- and the command is searched for (by name) in that order. They each are executed in a different way. When a shell function is executed, all of the shell positional parameters (except $0, which remains unchanged) are set to the arguments of the shell function. The variables which are explicitly placed in the environment of the command (by placing assignments to them before the function name) are made local to the function and are set to the values given. Then the command given in the function definition is executed. The positional parameters are restored to their original values when the command completes. This all occurs within the current shell. Shell builtins are executed internally to the shell, without spawning a new process. Otherwise, if the command name doesn't match a function or builtin, the command is searched for as a normal program in the file system (as described in the next section). When a normal program is executed, the shell runs the program, passing the arguments and the environment to the program. If the program is not a normal executable file (i.e., if it does not begin with the "magic number" whose ASCII representation is "#!", so execve(2) returns ENOEXEC then) the shell will interpret the program in a subshell. The child shell will reinitialize itself in this case, so that the effect will be as if a new shell had been invoked to handle the ad-hoc shell script, except that the location of hashed commands located in the parent shell will be remembered by the child. Note that previous versions of this document and the source code itself misleadingly and sporadically refer to a shell script without a magic number as a "shell procedure". Path Search When locating a command, the shell first looks to see if it has a shell function by that name. Then it looks for a builtin command by that name. If a builtin command is not found, one of two things happen: 1. Command names containing a slash are simply executed without performing any searches. 2. The shell searches each entry in PATH in turn for the command. The value of the PATH variable should be a series of entries separated by colons. Each entry consists of a directory name. The current directory may be indicated implicitly by an empty directory name, or explicitly by a single period. Command Exit Status Each command has an exit status that can influence the behaviour of other shell commands. The paradigm is that a command exits with zero for normal or success, and non-zero for failure, error, or a false indication. The man page for each command should indicate the various exit codes and what they mean. Additionally, the builtin commands return exit codes, as does an executed shell function. If a command consists entirely of variable assignments then the exit status of the command is that of the last command substitution if any, otherwise 0. Complex Commands Complex commands are combinations of simple commands with control operators or reserved words, together creating a larger complex command. More generally, a command is one of the following: • simple command • pipeline • list or compound-list • compound command • function definition Unless otherwise stated, the exit status of a command is that of the last simple command executed by the command. Pipelines A pipeline is a sequence of one or more commands separated by the control operator |. The standard output of all but the last command is connected to the standard input of the next command. The standard output of the last command is inherited from the shell, as usual. The format for a pipeline is: [!] command1 [| command2 ...] The standard output of command1 is connected to the standard input of command2. The standard input, standard output, or both of a command is considered to be assigned by the pipeline before any redirection specified by redirection operators that are part of the command. If the pipeline is not in the background (discussed later), the shell waits for all commands to complete. If the reserved word ! does not precede the pipeline, the exit status is the exit status of the last command specified in the pipeline. Otherwise, the exit status is the logical NOT of the exit status of the last command. That is, if the last command returns zero, the exit status is 1; if the last command returns greater than zero, the exit status is zero. Because pipeline assignment of standard input or standard output or both takes place before redirection, it can be modified by redirection. For example: $ command1 2>&1 | command2 sends both the standard output and standard error of command1 to the standard input of command2. A ; or ⟨newline⟩ terminator causes the preceding AND-OR-list (described next) to be executed sequentially; a & causes asynchronous execution of the preceding AND-OR-list. Note that unlike some other shells, each process in the pipeline is a child of the invoking shell (unless it is a shell builtin, in which case it executes in the current shell -- but any effect it has on the environment is wiped). Background Commands -- & If a command is terminated by the control operator ampersand (&), the shell executes the command asynchronously -- that is, the shell does not wait for the command to finish before executing the next command. The format for running a command in background is: command1 & [command2 & ...] If the shell is not interactive, the standard input of an asynchronous command is set to /dev/null. Lists -- Generally Speaking A list is a sequence of zero or more commands separated by newlines, semicolons, or ampersands, and optionally terminated by one of these three characters. The commands in a list are executed in the order they are written. If command is followed by an ampersand, the shell starts the command and immediately proceeds onto the next command; otherwise it waits for the command to terminate before proceeding to the next one. Short-Circuit List Operators “&&” and “||” are AND-OR list operators. “&&” executes the first command, and then executes the second command if and only if the exit status of the first command is zero. “||” is similar, but executes the second command if and only if the exit status of the first command is nonzero. “&&” and “||” both have the same priority. Flow-Control Constructs -- if, while, for, case The syntax of the if command is if list then list [ elif list then list ] ... [ else list ] fi The syntax of the while command is while list do list done The two lists are executed repeatedly while the exit status of the first list is zero. The until command is similar, but has the word until in place of while, which causes it to repeat until the exit status of the first list is zero. The syntax of the for command is for variable [ in [ word ... ] ] do list done The words following in are expanded, and then the list is executed repeatedly with the variable set to each word in turn. Omitting in word ... is equivalent to in "$@". The syntax of the break and continue command is break [ num ] continue [ num ] Break terminates the num innermost for or while loops. Continue continues with the next iteration of the innermost loop. These are implemented as builtin commands. The syntax of the case command is case word in [(]pattern) list ;; ... esac The pattern can actually be one or more patterns (see Shell Patterns described later), separated by “|” characters. The “(” character before the pattern is optional. Grouping Commands Together Commands may be grouped by writing either (list) or { list; } The first of these executes the commands in a subshell. Builtin commands grouped into a (list) will not affect the current shell. The second form does not fork another shell so is slightly more efficient. Grouping commands together this way allows you to redirect their output as though they were one program: { printf " hello " ; printf " world\n" ; } > greeting Note that “}” must follow a control operator (here, “;”) so that it is recognized as a reserved word and not as another command argument. Functions The syntax of a function definition is name () command A function definition is an executable statement; when executed it installs a function named name and returns an exit status of zero. The command is normally a list enclosed between “{” and “}”. Variables may be declared to be local to a function by using a local command. This should appear as the first statement of a function, and the syntax is local [variable | -] ... Local is implemented as a builtin command. When a variable is made local, it inherits the initial value and exported and readonly flags from the variable with the same name in the surrounding scope, if there is one. Otherwise, the variable is initially unset. The shell uses dynamic scoping, so that if you make the variable x local to function f, which then calls function g, references to the variable x made inside g will refer to the variable x declared inside f, not to the global variable named x. The only special parameter that can be made local is “-”. Making “-” local any shell options that are changed via the set command inside the function to be restored to their original values when the function returns. The syntax of the return command is return [exitstatus] It terminates the currently executing function. Return is implemented as a builtin command. Variables and Parameters The shell maintains a set of parameters. A parameter denoted by a name is called a variable. When starting up, the shell turns all the environment variables into shell variables. New variables can be set using the form name=value Variables set by the user must have a name consisting solely of alphabetics, numerics, and underscores - the first of which must not be numeric. A parameter can also be denoted by a number or a special character as explained below. Positional Parameters A positional parameter is a parameter denoted by a number (n > 0). The shell sets these initially to the values of its command line arguments that follow the name of the shell script. The set builtin can also be used to set or reset them. Special Parameters A special parameter is a parameter denoted by one of the following special characters. The value of the parameter is listed next to its character. * Expands to the positional parameters, starting from one. When the expansion occurs within a double-quoted string it expands to a single field with the value of each parameter separated by the first character of the IFS variable, or by a ⟨space⟩ if IFS is unset. @ Expands to the positional parameters, starting from one. When the expansion occurs within double-quotes, each positional parameter expands as a separate argument. If there are no positional parameters, the expansion of @ generates zero arguments, even when @ is double-quoted. What this basically means, for example, is if $1 is “abc” and $2 is “def ghi”, then "$@" expands to the two arguments: "abc" "def ghi" # Expands to the number of positional parameters. ? Expands to the exit status of the most recent pipeline. - (Hyphen.) Expands to the current option flags (the single-letter option names concatenated into a string) as specified on invocation, by the set builtin command, or implicitly by the shell. $ Expands to the process ID of the invoked shell. A subshell retains the same value of $ as its parent. ! Expands to the process ID of the most recent background command executed from the current shell. For a pipeline, the process ID is that of the last command in the pipeline. 0 (Zero.) Expands to the name of the shell or shell script. Word Expansions This clause describes the various expansions that are performed on words. Not all expansions are performed on every word, as explained later. Tilde expansions, parameter expansions, command substitutions, arithmetic expansions, and quote removals that occur within a single word expand to a single field. It is only field splitting or pathname expansion that can create multiple fields from a single word. The single exception to this rule is the expansion of the special parameter @ within double- quotes, as was described above. The order of word expansion is: 1. Tilde Expansion, Parameter Expansion, Command Substitution, Arithmetic Expansion (these all occur at the same time). 2. Field Splitting is performed on fields generated by step (1) unless the IFS variable is null. 3. Pathname Expansion (unless set -f is in effect). 4. Quote Removal. The $ character is used to introduce parameter expansion, command substitution, or arithmetic evaluation. Tilde Expansion (substituting a user's home directory) A word beginning with an unquoted tilde character (~) is subjected to tilde expansion. All the characters up to a slash (/) or the end of the word are treated as a username and are replaced with the user's home directory. If the username is missing (as in ~/foobar), the tilde is replaced with the value of the HOME variable (the current user's home directory). Parameter Expansion The format for parameter expansion is as follows: ${expression} where expression consists of all characters until the matching “}”. Any “}” escaped by a backslash or within a quoted string, and characters in embedded arithmetic expansions, command substitutions, and variable expansions, are not examined in determining the matching “}”. The simplest form for parameter expansion is: ${parameter} The value, if any, of parameter is substituted. The parameter name or symbol can be enclosed in braces, which are optional except for positional parameters with more than one digit or when parameter is followed by a character that could be interpreted as part of the name. If a parameter expansion occurs inside double-quotes: 1. Pathname expansion is not performed on the results of the expansion. 2. Field splitting is not performed on the results of the expansion, with the exception of @. In addition, a parameter expansion can be modified by using one of the following formats. ${parameter:-word} Use Default Values. If parameter is unset or null, the expansion of word is substituted; otherwise, the value of parameter is substituted. ${parameter:=word} Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. In all cases, the final value of parameter is substituted. Only variables, not positional parameters or special parameters, can be assigned in this way. ${parameter:?[word]} Indicate Error if Null or Unset. If parameter is unset or null, the expansion of word (or a message indicating it is unset if word is omitted) is written to standard error and the shell exits with a nonzero exit status. Otherwise, the value of parameter is substituted. An interactive shell need not exit. ${parameter:+word} Use Alternative Value. If parameter is unset or null, null is substituted; otherwise, the expansion of word is substituted. In the parameter expansions shown previously, use of the colon in the format results in a test for a parameter that is unset or null; omission of the colon results in a test for a parameter that is only unset. ${#parameter} String Length. The length in characters of the value of parameter. The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Shell Patterns), rather than regular expression notation, is used to evaluate the patterns. If parameter is * or @, the result of the expansion is unspecified. Enclosing the full parameter expansion string in double- quotes does not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces has this effect. ${parameter%word} Remove Smallest Suffix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the suffix matched by the pattern deleted. ${parameter%%word} Remove Largest Suffix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the largest portion of the suffix matched by the pattern deleted. ${parameter#word} Remove Smallest Prefix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pattern deleted. ${parameter##word} Remove Largest Prefix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the largest portion of the prefix matched by the pattern deleted. Command Substitution Command substitution allows the output of a command to be substituted in place of the command name itself. Command substitution occurs when the command is enclosed as follows: $(command) or (“backquoted” version): `command` The shell expands the command substitution by executing command in a subshell environment and replacing the command substitution with the standard output of the command, removing sequences of one or more ⟨newline⟩s at the end of the substitution. (Embedded ⟨newline⟩s before the end of the output are not removed; however, during field splitting, they may be translated into ⟨space⟩s, depending on the value of IFS and quoting that is in effect.) Arithmetic Expansion Arithmetic expansion provides a mechanism for evaluating an arithmetic expression and substituting its value. The format for arithmetic expansion is as follows: $((expression)) The expression is treated as if it were in double-quotes, except that a double-quote inside the expression is not treated specially. The shell expands all tokens in the expression for parameter expansion, command substitution, and quote removal. Next, the shell treats this as an arithmetic expression and substitutes the value of the expression. White Space Splitting (Field Splitting) After parameter expansion, command substitution, and arithmetic expansion the shell scans the results of expansions and substitutions that did not occur in double-quotes for field splitting and multiple fields can result. The shell treats each character of the IFS as a delimiter and uses the delimiters to split the results of parameter expansion and command substitution into fields. Pathname Expansion (File Name Generation) Unless the -f flag is set, file name generation is performed after word splitting is complete. Each word is viewed as a series of patterns, separated by slashes. The process of expansion replaces the word with the names of all existing files whose names can be formed by replacing each pattern with a string that matches the specified pattern. There are two restrictions on this: first, a pattern cannot match a string containing a slash, and second, a pattern cannot match a string starting with a period unless the first character of the pattern is a period. The next section describes the patterns used for both Pathname Expansion and the case command. Shell Patterns A pattern consists of normal characters, which match themselves, and meta-characters. The meta-characters are “!”, “*”, “?”, and “[”. These characters lose their special meanings if they are quoted. When command or variable substitution is performed and the dollar sign or back quotes are not double quoted, the value of the variable or the output of the command is scanned for these characters and they are turned into meta- characters. An asterisk (“*”) matches any string of characters. A question mark matches any single character. A left bracket (“[”) introduces a character class. The end of the character class is indicated by a (“]”); if the “]” is missing then the “[” matches a “[” rather than introducing a character class. A character class matches any of the characters between the square brackets. A range of characters may be specified using a minus sign. The character class may be complemented by making an exclamation point the first character of the character class. To include a “]” in a character class, make it the first character listed (after the “!”, if any). To include a minus sign, make it the first or last character listed. Builtins This section lists the builtin commands which are builtin because they need to perform some operation that can't be performed by a separate process. In addition to these, there are several other commands that may be builtin for efficiency (e.g. printf(1), echo(1), test(1), etc). : true A null command that returns a 0 (true) exit value. . file The commands in the specified file are read and executed by the shell. alias [name[=string ...]] If name=string is specified, the shell defines the alias name with value string. If just name is specified, the value of the alias name is printed. With no arguments, the alias builtin prints the names and values of all defined aliases (see unalias). bg [job] ... Continue the specified jobs (or the current job if no jobs are given) in the background. command [-p] [-v] [-V] command [arg ...] Execute the specified command but ignore shell functions when searching for it. (This is useful when you have a shell function with the same name as a builtin command.) -p search for command using a PATH that guarantees to find all the standard utilities. -V Do not execute the command but search for the command and print the resolution of the command search. This is the same as the type builtin. -v Do not execute the command but search for the command and print the absolute pathname of utilities, the name for builtins or the expansion of aliases. cd - cd [-LP] [directory] Switch to the specified directory (default HOME). If an entry for CDPATH appears in the environment of the cd command or the shell variable CDPATH is set and the directory name does not begin with a slash, then the directories listed in CDPATH will be searched for the specified directory. The format of CDPATH is the same as that of PATH. If a single dash is specified as the argument, it will be replaced by the value of OLDPWD. The cd command will print out the name of the directory that it actually switched to if this is different from the name that the user gave. These may be different either because the CDPATH mechanism was used or because the argument is a single dash. The -P option causes the physical directory structure to be used, that is, all symbolic links are resolved to their respective values. The -L option turns off the effect of any preceding -P options. echo [-n] args... Print the arguments on the standard output, separated by spaces. Unless the -n option is present, a newline is output following the arguments. If any of the following sequences of characters is encountered during output, the sequence is not output. Instead, the specified action is performed: \b A backspace character is output. \c Subsequent output is suppressed. This is normally used at the end of the last argument to suppress the trailing newline that echo would otherwise output. \f Output a form feed. \n Output a newline character. \r Output a carriage return. \t Output a (horizontal) tab character. \v Output a vertical tab. \0digits Output the character whose value is given by zero to three octal digits. If there are zero digits, a nul character is output. \\ Output a backslash. All other backslash sequences elicit undefined behaviour. eval string ... Concatenate all the arguments with spaces. Then re-parse and execute the command. exec [command arg ...] Unless command is omitted, the shell process is replaced with the specified program (which must be a real program, not a shell builtin or function). Any redirections on the exec command are marked as permanent, so that they are not undone when the exec command finishes. exit [exitstatus] Terminate the shell process. If exitstatus is given it is used as the exit status of the shell; otherwise the exit status of the preceding command is used. export name ... export -p The specified names are exported so that they will appear in the environment of subsequent commands. The only way to un-export a variable is to unset it. The shell allows the value of a variable to be set at the same time it is exported by writing export name=value With no arguments the export command lists the names of all exported variables. With the -p option specified the output will be formatted suitably for non-interactive use. fc [-e editor] [first [last]] fc -l [-nr] [first [last]] fc -s [old=new] [first] The fc builtin lists, or edits and re-executes, commands previously entered to an interactive shell. -e editor Use the editor named by editor to edit the commands. The editor string is a command name, subject to search via the PATH variable. The value in the FCEDIT variable is used as a default when -e is not specified. If FCEDIT is null or unset, the value of the EDITOR variable is used. If EDITOR is null or unset, ed(1) is used as the editor. -l (ell) List the commands rather than invoking an editor on them. The commands are written in the sequence indicated by the first and last operands, as affected by -r, with each command preceded by the command number. -n Suppress command numbers when listing with -l. -r Reverse the order of the commands listed (with -l) or edited (with neither -l nor -s). -s Re-execute the command without invoking an editor. first last Select the commands to list or edit. The number of previous commands that can be accessed are determined by the value of the HISTSIZE variable. The value of first or last or both are one of the following: [+]number A positive number representing a command number; command numbers can be displayed with the -l option. -number A negative decimal number representing the command that was executed number of commands previously. For example, -1 is the immediately previous command. string A string indicating the most recently entered command that begins with that string. If the old=new operand is not also specified with -s, the string form of the first operand cannot contain an embedded equal sign. The following environment variables affect the execution of fc: FCEDIT Name of the editor to use. HISTSIZE The number of previous commands that are accessible. fg [job] Move the specified job or the current job to the foreground. getopts optstring var The POSIX getopts command, not to be confused with the Bell Labs -derived getopt(1). The first argument should be a series of letters, each of which may be optionally followed by a colon to indicate that the option requires an argument. The variable specified is set to the parsed option. The getopts command deprecates the older getopt(1) utility due to its handling of arguments containing whitespace. The getopts builtin may be used to obtain options and their arguments from a list of parameters. When invoked, getopts places the value of the next option from the option string in the list in the shell variable specified by var and its index in the shell variable OPTIND. When the shell is invoked, OPTIND is initialized to 1. For each option that requires an argument, the getopts builtin will place it in the shell variable OPTARG. If an option is not allowed for in the optstring, then OPTARG will be unset. optstring is a string of recognized option letters (see getopt(3)). If a letter is followed by a colon, the option is expected to have an argument which may or may not be separated from it by white space. If an option character is not found where expected, getopts will set the variable var to a “?”; getopts will then unset OPTARG and write output to standard error. By specifying a colon as the first character of optstring all errors will be ignored. After the last option getopts will return a non-zero value and set var to “?”. The following code fragment shows how one might process the arguments for a command that can take the options [a] and [b], and the option [c], which requires an argument. while getopts abc: f do case $f in a | b) flag=$f;; c) carg=$OPTARG;; \?) echo $USAGE; exit 1;; esac done shift `expr $OPTIND - 1` This code will accept any of the following as equivalent: cmd -acarg file file cmd -a -c arg file file cmd -carg -a file file cmd -a -carg -- file file hash -rv command ... The shell maintains a hash table which remembers the locations of commands. With no arguments whatsoever, the hash command prints out the contents of this table. Entries which have not been looked at since the last cd command are marked with an asterisk; it is possible for these entries to be invalid. With arguments, the hash command removes the specified commands from the hash table (unless they are functions) and then locates them. With the -v option, hash prints the locations of the commands as it finds them. The -r option causes the hash command to delete all the entries in the hash table except for functions. pwd [-LP] builtin command remembers what the current directory is rather than recomputing it each time. This makes it faster. However, if the current directory is renamed, the builtin version of pwd will continue to print the old name for the directory. The -P option causes the physical value of the current working directory to be shown, that is, all symbolic links are resolved to their respective values. The -L option turns off the effect of any preceding -P options. read [-p prompt] [-r] variable [...] The prompt is printed if the -p option is specified and the standard input is a terminal. Then a line is read from the standard input. The trailing newline is deleted from the line and the line is split as described in the section on word splitting above, and the pieces are assigned to the variables in order. At least one variable must be specified. If there are more pieces than variables, the remaining pieces (along with the characters in IFS that separated them) are assigned to the last variable. If there are more variables than pieces, the remaining variables are assigned the null string. The read builtin will indicate success unless EOF is encountered on input, in which case failure is returned. By default, unless the -r option is specified, the backslash “\” acts as an escape character, causing the following character to be treated literally. If a backslash is followed by a newline, the backslash and the newline will be deleted. readonly name ... readonly -p The specified names are marked as read only, so that they cannot be subsequently modified or unset. The shell allows the value of a variable to be set at the same time it is marked read only by writing readonly name=value With no arguments the readonly command lists the names of all read only variables. With the -p option specified the output will be formatted suitably for non-interactive use. printf format [arguments ...] printf formats and prints its arguments, after the first, under control of the format. The format is a character string which contains three types of objects: plain characters, which are simply copied to standard output, character escape sequences which are converted and copied to the standard output, and format specifications, each of which causes printing of the next successive argument. The arguments after the first are treated as strings if the corresponding format is either b, c or s; otherwise it is evaluated as a C constant, with the following extensions: • A leading plus or minus sign is allowed. • If the leading character is a single or double quote, the value is the ASCII code of the next character. The format string is reused as often as necessary to satisfy the arguments. Any extra format specifications are evaluated with zero or the null string. Character escape sequences are in backslash notation as defined in ANSI X3.159-1989 (“ANSI C89”). The characters and their meanings are as follows: \a Write a <bell> character. \b Write a <backspace> character. \f Write a <form-feed> character. \n Write a <new-line> character. \r Write a <carriage return> character. \t Write a <tab> character. \v Write a <vertical tab> character. \\ Write a backslash character. \num Write an 8-bit character whose ASCII value is the 1-, 2-, or 3-digit octal number num. Each format specification is introduced by the percent character (``%''). The remainder of the format specification includes, in the following order: Zero or more of the following flags: # A `#' character specifying that the value should be printed in an ``alternative form''. For b, c, d, and s formats, this option has no effect. For the o format the precision of the number is increased to force the first character of the output string to a zero. For the x (X) format, a non-zero result has the string 0x (0X) prepended to it. For e, E, f, g, and G formats, the result will always contain a decimal point, even if no digits follow the point (normally, a decimal point only appears in the results of those formats if a digit follows the decimal point). For g and G formats, trailing zeros are not removed from the result as they would otherwise be. - A minus sign `-' which specifies left adjustment of the output in the indicated field; + A `+' character specifying that there should always be a sign placed before the number when using signed formats. ‘ ’ A space specifying that a blank should be left before a positive number for a signed format. A `+' overrides a space if both are used; 0 A zero `0' character indicating that zero-padding should be used rather than blank-padding. A `-' overrides a `0' if both are used; Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left- adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width); Precision: An optional period, ‘.’, followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of bytes to be printed from a string (b and s formats); if the digit string is missing, the precision is treated as zero; Format: A character which indicates the type of format to use (one of diouxXfwEgGbcs). A field width or precision may be ‘*’ instead of a digit string. In this case an argument supplies the field width or precision. The format characters and their meanings are: diouXx The argument is printed as a signed decimal (d or i), unsigned octal, unsigned decimal, or unsigned hexadecimal (X or x), respectively. f The argument is printed in the style [-]ddd.ddd where the number of d's after the decimal point is equal to the precision specification for the argument. If the precision is missing, 6 digits are given; if the precision is explicitly 0, no digits and no decimal point are printed. eE The argument is printed in the style [-]d.ddde±dd where there is one digit before the decimal point and the number after is equal to the precision specification for the argument; when the precision is missing, 6 digits are produced. An upper-case E is used for an `E' format. gG The argument is printed in style f or in style e (E) whichever gives full precision in minimum space. b Characters from the string argument are printed with backslash-escape sequences expanded. The following additional backslash-escape sequences are supported: \c Causes dash to ignore any remaining characters in the string operand containing it, any remaining string operands, and any additional characters in the format operand. \0num Write an 8-bit character whose ASCII value is the 1-, 2-, or 3-digit octal number num. c The first character of argument is printed. s Characters from the string argument are printed until the end is reached or until the number of bytes indicated by the precision specification is reached; if the precision is omitted, all characters in the string are printed. % Print a `%'; no argument is used. In no case does a non-existent or small field width cause truncation of a field; padding takes place only if the specified field width exceeds the actual width. set [{ -options | +options | -- }] arg ... The set command performs three different functions. With no arguments, it lists the values of all shell variables. If options are given, it sets the specified option flags, or clears them as described in the section called Argument List Processing. As a special case, if the option is -o or +o and no argument is supplied, the shell prints the settings of all its options. If the option is -o, the settings are printed in a human-readable format; if the option is +o, the settings are printed in a format suitable for reinput to the shell to affect the same option settings. The third use of the set command is to set the values of the shell's positional parameters to the specified args. To change the positional parameters without changing any options, use “--” as the first argument to set. If no args are present, the set command will clear all the positional parameters (equivalent to executing “shift $#”.) shift [n] Shift the positional parameters n times. A shift sets the value of $1 to the value of $2, the value of $2 to the value of $3, and so on, decreasing the value of $# by one. If n is greater than the number of positional parameters, shift will issue an error message, and exit with return status 2. test expression [ expression ] The test utility evaluates the expression and, if it evaluates to true, returns a zero (true) exit status; otherwise it returns 1 (false). If there is no expression, test also returns 1 (false). All operators and flags are separate arguments to the test utility. The following primaries are used to construct expression: -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 (regardless of type). -f file True if file exists and is a regular file. -g file True if file exists and its set group ID flag is set. -h file True if file exists and is a symbolic link. -k file True if file exists and its sticky bit is set. -n string True if the length of string is nonzero. -p file True if file is a named pipe (FIFO). -r file True if file exists and is readable. -s file True if file exists and has a size greater than zero. -t file_descriptor True if the file whose file descriptor number is file_descriptor is open and is associated with a terminal. -u file True if file exists and its set user ID flag is set. -w file True if file exists and is writable. True indicates only that the write flag is on. The file is not writable on a read-only file system even if this test indicates true. -x file True if file exists and is executable. True indicates only that the execute flag is on. If file is a directory, true indicates that file can be searched. -z string True if the length of string is zero. -L file True if file exists and is a symbolic link. This operator is retained for compatibility with previous versions of this program. Do not rely on its existence; use -h instead. -O file True if file exists and its owner matches the effective user id of this process. -G file True if file exists and its group matches the effective group id of this process. -S file True if file exists and is a socket. file1 -nt file2 True if file1 and file2 exist and file1 is newer than file2. file1 -ot file2 True if file1 and file2 exist and file1 is older than file2. file1 -ef file2 True if file1 and file2 exist and refer to the same file. string True if string is not the null string. s1 = s2 True if the strings s1 and s2 are identical. s1 != s2 True if the strings s1 and s2 are not identical. s1 < s2 True if string s1 comes before s2 based on the ASCII value of their characters. s1 > s2 True if string s1 comes after s2 based on the ASCII value of their characters. n1 -eq n2 True if the integers n1 and n2 are algebraically equal. n1 -ne n2 True if the integers n1 and n2 are not algebraically equal. n1 -gt n2 True if the integer n1 is algebraically greater than the integer n2. n1 -ge n2 True if the integer n1 is algebraically greater than or equal to the integer n2. n1 -lt n2 True if the integer n1 is algebraically less than the integer n2. n1 -le n2 True if the integer n1 is algebraically less than or equal to the integer n2. These primaries can be combined with the following operators: ! expression True if expression is false. expression1 -a expression2 True if both expression1 and expression2 are true. expression1 -o expression2 True if either expression1 or expression2 are true. (expression) True if expression is true. The -a operator has higher precedence than the -o operator. times Print the accumulated user and system times for the shell and for processes run from the shell. The return status is 0. trap [action signal ...] Cause the shell to parse and execute action when any of the specified signals are received. The signals are specified by signal number or as the name of the signal. If signal is 0 or EXIT, the action is executed when the shell exits. action may be empty (''), which causes the specified signals to be ignored. With action omitted or set to `-' the specified signals are set to their default action. When the shell forks off a subshell, it resets trapped (but not ignored) signals to the default action. The trap command has no effect on signals that were ignored on entry to the shell. trap without any arguments cause it to write a list of signals and their associated action to the standard output in a format that is suitable as an input to the shell that achieves the same trapping results. Examples: trap List trapped signals and their corresponding action trap '' INT QUIT tstp 30 Ignore signals INT QUIT TSTP USR1 trap date INT Print date upon receiving signal INT type [name ...] Interpret each name as a command and print the resolution of the command search. Possible resolutions are: shell keyword, alias, shell builtin, command, tracked alias and not found. For aliases the alias expansion is printed; for commands and tracked aliases the complete pathname of the command is printed. ulimit [-H | -S] [-a | -tfdscmlpnv [value]] Inquire about or set the hard or soft limits on processes or set new limits. The choice between hard limit (which no process is allowed to violate, and which may not be raised once it has been lowered) and soft limit (which causes processes to be signaled but not necessarily killed, and which may be raised) is made with these flags: -H set or inquire about hard limits -S set or inquire about soft limits. If neither -H nor -S is specified, the soft limit is displayed or both limits are set. If both are specified, the last one wins. The limit to be interrogated or set, then, is chosen by specifying any one of these flags: -a show all the current limits -t show or set the limit on CPU time (in seconds) -f show or set the limit on the largest file that can be created (in 512-byte blocks) -d show or set the limit on the data segment size of a process (in kilobytes) -s show or set the limit on the stack size of a process (in kilobytes) -c show or set the limit on the largest core dump size that can be produced (in 512-byte blocks) -m show or set the limit on the total physical memory that can be in use by a process (in kilobytes) -l show or set the limit on how much memory a process can lock with mlock(2) (in kilobytes) -p show or set the limit on the number of processes this user can have at one time -n show or set the limit on the number files a process can have open at once -v show or set the limit on the total virtual memory that can be in use by a process (in kilobytes) -r show or set the limit on the real-time scheduling priority of a process If none of these is specified, it is the limit on file size that is shown or set. If value is specified, the limit is set to that number; otherwise the current limit is displayed. Limits of an arbitrary process can be displayed or set using the sysctl(8) utility. umask [mask] Set the value of umask (see umask(2)) to the specified octal value. If the argument is omitted, the umask value is printed. unalias [-a] [name] If name is specified, the shell removes that alias. If -a is specified, all aliases are removed. unset [-fv] name ... The specified variables and functions are unset and unexported. If -f or -v is specified, the corresponding function or variable is unset, respectively. If a given name corresponds to both a variable and a function, and no options are given, only the variable is unset. wait [job] Wait for the specified job to complete and return the exit status of the last process in the job. If the argument is omitted, wait for all jobs to complete and return an exit status of zero. Command Line Editing When dash is being used interactively from a terminal, the current command and the command history (see fc in Builtins) can be edited using vi-mode command-line editing. This mode uses commands, described below, similar to a subset of those described in the vi man page. The command ‘set -o vi’ enables vi-mode editing and places sh into vi insert mode. With vi-mode enabled, sh can be switched between insert mode and command mode. It is similar to vi: typing ⟨ESC⟩ enters vi command mode. Hitting ⟨return⟩ while in command mode will pass the line to the shell. EXIT STATUS Errors that are detected by the shell, such as a syntax error, will cause the shell to exit with a non-zero exit status. If the shell is not an interactive shell, the execution of the shell file will be aborted. Otherwise the shell will return the exit status of the last command executed, or if the exit builtin is used with a numeric argument, it will return the argument. ENVIRONMENT HOME Set automatically by login(1) from the user's login directory in the password file (passwd(4)). This environment variable also functions as the default argument for the cd builtin. PATH The default search path for executables. See the above section Path Search. CDPATH The search path used with the cd builtin. MAIL The name of a mail file, that will be checked for the arrival of new mail. Overridden by MAILPATH. MAILCHECK The frequency in seconds that the shell checks for the arrival of mail in the files specified by the MAILPATH or the MAIL file. If set to 0, the check will occur at each prompt. MAILPATH A colon “:” separated list of file names, for the shell to check for incoming mail. This environment setting overrides the MAIL setting. There is a maximum of 10 mailboxes that can be monitored at once. PS1 The primary prompt string, which defaults to “$ ”, unless you are the superuser, in which case it defaults to “# ”. PS2 The secondary prompt string, which defaults to “> ”. PS4 Output before each line when execution trace (set -x) is enabled, defaults to “+ ”. IFS Input Field Separators. This is normally set to ⟨space⟩, ⟨tab⟩, and ⟨newline⟩. See the White Space Splitting section for more details. TERM The default terminal setting for the shell. This is inherited by children of the shell, and is used in the history editing modes. HISTSIZE The number of lines in the history buffer for the shell. PWD The logical value of the current working directory. This is set by the cd command. OLDPWD The previous logical value of the current working directory. This is set by the cd command. PPID The process ID of the parent process of the shell. FILES $HOME/.profile /etc/profile SEE ALSO csh(1), echo(1), getopt(1), ksh(1), login(1), printf(1), test(1), getopt(3), passwd(5), environ(7), sysctl(8) HISTORY dash is a POSIX-compliant implementation of /bin/sh that aims to be as small as possible. dash is a direct descendant of the NetBSD version of ash (the Almquist SHell), ported to Linux in early 1997. It was renamed to dash in 2002. BUGS Setuid shell scripts should be avoided at all costs, as they are a significant security risk. PS1, PS2, and PS4 should be subject to parameter expansion before being displayed. macOS 14.5 January 19, 2003 macOS 14.5
dash – command interpreter (shell)
dash [-aCefnuvxIimqVEb] [+aCefnuvxIimqVEb] [-o option_name] [+o option_name] [command_file [argument ...]] dash -c [-aCefnuvxIimqVEb] [+aCefnuvxIimqVEb] [-o option_name] [+o option_name] command_string [command_name [argument ...]] dash -s [-aCefnuvxIimqVEb] [+aCefnuvxIimqVEb] [-o option_name] [+o option_name] [argument ...]
null
null
rmdir
The rmdir utility removes the directory entry specified by each directory argument, provided it is empty. Arguments are processed in the order given. In order to remove both a parent directory and a subdirectory of that parent, the subdirectory must be specified first so the parent directory is empty when rmdir tries to remove it. The following option is available: -p Each directory argument is treated as a pathname of which all components will be removed, if they are empty, starting with the last most component. (See rm(1) for fully non-discriminant recursive removal.) -v Be verbose, listing each directory as it is removed. EXIT STATUS The rmdir utility exits with one of the following values: 0 Each directory entry specified by a directory operand referred to an empty directory and was removed successfully. >0 An error occurred.
rmdir – remove directories
rmdir [-pv] directory ...
null
Remove the directory foobar, if it is empty: $ rmdir foobar Remove all directories up to and including cow, stopping at the first non-empty directory (if any): $ rmdir -p cow/horse/monkey SEE ALSO rm(1) STANDARDS The rmdir utility is expected to be IEEE Std 1003.2 (“POSIX.2”) compatible. HISTORY A rmdir command appeared in Version 1 AT&T UNIX. macOS 14.5 March 15, 2013 macOS 14.5
mv
In its first form, the mv utility renames the file named by the source operand to the destination path named by the target operand. This form is assumed when the last operand does not name an already existing directory. In its second form, mv moves each file named by a source operand to a destination file in the existing directory named by the directory operand. The destination path for each operand is the pathname produced by the concatenation of the last operand, a slash, and the final pathname component of the named file. The following options are available: -f Do not prompt for confirmation before overwriting the destination path. (The -f option overrides any previous -i or -n options.) -h If the target operand is a symbolic link to a directory, do not follow it. This causes the mv utility to rename the file source to the destination path target rather than moving source into the directory referenced by target. -i Cause mv to write a prompt to standard error before moving a file that would overwrite an existing file. If the response from the standard input begins with the character ‘y’ or ‘Y’, the move is attempted. (The -i option overrides any previous -f or -n options.) -n Do not overwrite an existing file. (The -n option overrides any previous -f or -i options.) -v Cause mv to be verbose, showing files after they are moved. It is an error for the source operand to specify a directory if the target exists and is not a directory. If the destination path does not have a mode which permits writing, mv prompts the user for confirmation as specified for the -i option. As the rename(2) call does not work across file systems, mv uses cp(1) and rm(1) to accomplish the move. The effect is equivalent to: rm -f destination_path && \ cp -pRP source_file destination && \ rm -rf source_file EXIT STATUS The mv utility exits 0 on success, and >0 if an error occurs. The command "mv dir/afile dir" will abort with an error message. LEGACY DIAGNOSTICS In legacy mode, the command "mv dir/afile dir" will fail silently, returning an exit code of 0. For more information about legacy mode, see compat(5).
mv – move files
mv [-f | -i | -n] [-hv] source target mv [-f | -i | -n] [-v] source ... directory
null
Rename file foo to bar, overwriting bar if it already exists: $ mv -f foo bar COMPATIBILITY The -h, -n, and -v options are non-standard and their use in scripts is not recommended. The mv utility now supports HFS+ Finder and Extended Attributes and resource forks. The mv utility will no longer strip resource forks off of HFS files. For an alternative method, refer to cp(1). SEE ALSO cp(1), rm(1), symlink(7) STANDARDS The mv utility is expected to be IEEE Std 1003.2 (“POSIX.2”) compatible. HISTORY A mv command appeared in Version 1 AT&T UNIX. macOS 14.5 March 15, 2013 macOS 14.5
ln
The ln utility creates a new directory entry (linked file) for the file name specified by target_file. The target_file will be created with the same file modes as the source_file. It is useful for maintaining multiple copies of a file in many places at once without using up storage for the “copies”; instead, a link “points” to the original copy. There are two types of links; hard links and symbolic links. How a link “points” to a file is one of the differences between a hard and symbolic link. The options are as follows: -F If the target file already exists and is a directory, then remove it so that the link may occur. The -F option should be used with either -f or -i options. If neither -f nor -i is specified, -f is implied. The -F option is a no-op unless -s is specified. -L When creating a hard link to a symbolic link, create a hard link to the target of the symbolic link. This is the default. This option cancels the -P option. -P When creating a hard link to a symbolic link, create a hard link to the symbolic link itself. This option cancels the -L option. -f If the target file already exists, then unlink it so that the link may occur. (The -f option overrides any previous -i and -w options.) -h If the target_file or target_dir is a symbolic link, do not follow it. This is most useful with the -f option, to replace a symlink which may point to a directory. -i Cause ln to write a prompt to standard error if the target file exists. If the response from the standard input begins with the character ‘y’ or ‘Y’, then unlink the target file so that the link may occur. Otherwise, do not attempt the link. (The -i option overrides any previous -f options.) -n Same as -h, for compatibility with other ln implementations. -s Create a symbolic link. -v Cause ln to be verbose, showing files as they are processed. -w Warn if the source of a symbolic link does not currently exist. By default, ln makes hard links. A hard link to a file is indistinguishable from the original directory entry; any changes to a file are effectively independent of the name used to reference the file. Directories may not be hardlinked, and hard links may not span file systems. A symbolic link contains the name of the file to which it is linked. The referenced file is used when an open(2) operation is performed on the link. A stat(2) on a symbolic link will return the linked-to file; an lstat(2) must be done to obtain information about the link. The readlink(2) call may be used to read the contents of a symbolic link. Symbolic links may span file systems and may refer to directories. Given one or two arguments, ln creates a link to an existing file source_file. If target_file is given, the link has that name; target_file may also be a directory in which to place the link; otherwise it is placed in the current directory. If only the directory is specified, the link will be made to the last component of source_file. Given more than two arguments, ln makes links in target_dir to all the named source files. The links made will have the same name as the files being linked to. When the utility is called as link, exactly two arguments must be supplied, neither of which may specify a directory. No options may be supplied in this simple mode of operation, which performs a link(2) operation using the two passed arguments.
ln, link – link files
ln [-L | -P | -s [-F]] [-f | -iw] [-hnv] source_file [target_file] ln [-L | -P | -s [-F]] [-f | -iw] [-hnv] source_file ... target_dir link source_file target_file
null
Create a symbolic link named /home/src and point it to /usr/src: # ln -s /usr/src /home/src Hard link /usr/local/bin/fooprog to file /usr/local/bin/fooprog-1.0: # ln /usr/local/bin/fooprog-1.0 /usr/local/bin/fooprog As an exercise, try the following commands: # ls -i /bin/[ 11553 /bin/[ # ls -i /bin/test 11553 /bin/test Note that both files have the same inode; that is, /bin/[ is essentially an alias for the test(1) command. This hard link exists so test(1) may be invoked from shell scripts, for example, using the if [ ] construct. In the next example, the second call to ln removes the original foo and creates a replacement pointing to baz: # mkdir bar baz # ln -s bar foo # ln -shf baz foo Without the -h option, this would instead leave foo pointing to bar and inside foo create a new symlink baz pointing to itself. This results from directory-walking. An easy rule to remember is that the argument order for ln is the same as for cp(1): The first argument needs to exist, the second one is created. COMPATIBILITY The -h, -i, -n, -v and -w options are non-standard and their use in scripts is not recommended. They are provided solely for compatibility with other ln implementations. The -F option is a FreeBSD extension and should not be used in portable scripts. SEE ALSO link(2), lstat(2), readlink(2), stat(2), symlink(2), symlink(7) STANDARDS The ln utility conforms to IEEE Std 1003.2-1992 (“POSIX.2”). The simplified link command conforms to Version 2 of the Single UNIX Specification (“SUSv2”). HISTORY An ln command appeared in Version 1 AT&T UNIX. macOS 14.5 May 10, 2021 macOS 14.5
ls
For each operand that names a file of a type other than directory, ls displays its name as well as any requested, associated information. For each operand that names a file of type directory, ls displays the names of files contained within that directory, as well as any requested, associated information. If no operands are given, the contents of the current directory are displayed. If more than one operand is given, non-directory operands are displayed first; directory and non-directory operands are sorted separately and in lexicographical order. The following options are available: -@ Display extended attribute keys and sizes in long (-l) output. -A Include directory entries whose names begin with a dot (‘.’) except for . and ... Automatically set for the super-user unless -I is specified. -B Force printing of non-printable characters (as defined by ctype(3) and current locale settings) in file names as \xxx, where xxx is the numeric value of the character in octal. This option is not defined in IEEE Std 1003.1-2008 (“POSIX.1”). -C Force multi-column output; this is the default when output is to a terminal. -D format When printing in the long (-l) format, use format to format the date and time output. The argument format is a string used by strftime(3). Depending on the choice of format string, this may result in a different number of columns in the output. This option overrides the -T option. This option is not defined in IEEE Std 1003.1-2008 (“POSIX.1”). -F Display a slash (‘/’) immediately after each pathname that is a directory, an asterisk (‘*’) after each that is executable, an at sign (‘@’) after each symbolic link, an equals sign (‘=’) after each socket, a percent sign (‘%’) after each whiteout, and a vertical bar (‘|’) after each that is a FIFO. -G Enable colorized output. This option is equivalent to defining CLICOLOR or COLORTERM in the environment and setting --color=auto. (See below.) This functionality can be compiled out by removing the definition of COLORLS. This option is not defined in IEEE Std 1003.1-2008 (“POSIX.1”). -H Symbolic links on the command line are followed. This option is assumed if none of the -F, -d, or -l options are specified. -I Prevent -A from being automatically set for the super-user. This option is not defined in IEEE Std 1003.1-2008 (“POSIX.1”). -L Follow all symbolic links to final target and list the file or directory the link references rather than the link itself. This option cancels the -P option. -O Include the file flags in a long (-l) output. This option is incompatible with IEEE Std 1003.1-2008 (“POSIX.1”). See chflags(1) for a list of file flags and their meanings. -P If argument is a symbolic link, list the link itself rather than the object the link references. This option cancels the -H and -L options. -R Recursively list subdirectories encountered. -S Sort by size (largest file first) before sorting the operands in lexicographical order. -T When printing in the long (-l) format, display complete time information for the file, including month, day, hour, minute, second, and year. The -D option gives even more control over the output format. This option is not defined in IEEE Std 1003.1-2008 (“POSIX.1”). -U Use time when file was created for sorting or printing. This option is not defined in IEEE Std 1003.1-2008 (“POSIX.1”). -W Display whiteouts when scanning directories. This option is not defined in IEEE Std 1003.1-2008 (“POSIX.1”). -a Include directory entries whose names begin with a dot (‘.’). -b As -B, but use C escape codes whenever possible. This option is not defined in IEEE Std 1003.1-2008 (“POSIX.1”). -c Use time when file status was last changed for sorting or printing. --color=when Output colored escape sequences based on when, which may be set to either always, auto, or never. always will make ls always output color. If TERM is unset or set to an invalid terminal, then ls will fall back to explicit ANSI escape sequences without the help of termcap(5). always is the default if --color is specified without an argument. auto will make ls output escape sequences based on termcap(5), but only if stdout is a tty and either the -G flag is specified or the COLORTERM environment variable is set and not empty. never will disable color regardless of environment variables. never is the default when neither --color nor -G is specified. For compatibility with GNU coreutils, ls supports yes or force as equivalent to always, no or none as equivalent to never, and tty or if-tty as equivalent to auto. -d Directories are listed as plain files (not searched recursively). -e Print the Access Control List (ACL) associated with the file, if present, in long (-l) output. -f Output is not sorted. This option turns on -a. It also negates the effect of the -r, -S and -t options. As allowed by IEEE Std 1003.1-2008 (“POSIX.1”), this option has no effect on the -d, -l, -R and -s options. -g This option has no effect. It is only available for compatibility with 4.3BSD, where it was used to display the group name in the long (-l) format output. This option is incompatible with IEEE Std 1003.1-2008 (“POSIX.1”). -h When used with the -l option, use unit suffixes: Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte in order to reduce the number of digits to four or fewer using base 2 for sizes. This option is not defined in IEEE Std 1003.1-2008 (“POSIX.1”). -i For each file, print the file's file serial number (inode number). -k This has the same effect as setting environment variable BLOCKSIZE to 1024, except that it also nullifies any -h options to its left. -l (The lowercase letter “ell”.) List files in the long format, as described in the The Long Format subsection below. -m Stream output format; list files across the page, separated by commas. -n Display user and group IDs numerically rather than converting to a user or group name in a long (-l) output. This option turns on the -l option. -o List in long format, but omit the group id. -p Write a slash (‘/’) after each filename if that file is a directory. -q Force printing of non-graphic characters in file names as the character ‘?’; this is the default when output is to a terminal. -r Reverse the order of the sort. -s Display the number of blocks used in the file system by each file. Block sizes and directory totals are handled as described in The Long Format subsection below, except (if the long format is not also requested) the directory totals are not output when the output is in a single column, even if multi-column output is requested. (-l) format, display complete time information for the file, including month, day, hour, minute, second, and year. The -D option gives even more control over the output format. This option is not defined in IEEE Std 1003.1-2008 (“POSIX.1”). -t Sort by descending time modified (most recently modified first). If two files have the same modification timestamp, sort their names in ascending lexicographical order. The -r option reverses both of these sort orders. Note that these sort orders are contradictory: the time sequence is in descending order, the lexicographical sort is in ascending order. This behavior is mandated by IEEE Std 1003.2 (“POSIX.2”). This feature can cause problems listing files stored with sequential names on FAT file systems, such as from digital cameras, where it is possible to have more than one image with the same timestamp. In such a case, the photos cannot be listed in the sequence in which they were taken. To ensure the same sort order for time and for lexicographical sorting, set the environment variable LS_SAMESORT or use the -y option. This causes ls to reverse the lexicographical sort order when sorting files with the same modification timestamp. -u Use time of last access, instead of time of last modification of the file for sorting (-t) or long printing (-l). -v Force unedited printing of non-graphic characters; this is the default when output is not to a terminal. -w Force raw printing of non-printable characters. This is the default when output is not to a terminal. This option is not defined in IEEE Std 1003.1-2001 (“POSIX.1”). -x The same as -C, except that the multi-column output is produced with entries sorted across, rather than down, the columns. -y When the -t option is set, sort the alphabetical output in the same order as the time output. This has the same effect as setting LS_SAMESORT. See the description of the -t option for more details. This option is not defined in IEEE Std 1003.1-2001 (“POSIX.1”). -% Distinguish dataless files and directories with a '%' character in long (-l) output, and don't materialize dataless directories when listing them. -1 (The numeric digit “one”.) Force output to be one entry per line. This is the default when output is not to a terminal. -, (Comma) When the -l option is set, print file sizes grouped and separated by thousands using the non-monetary separator returned by localeconv(3), typically a comma or period. If no locale is set, or the locale does not have a non-monetary separator, this option has no effect. This option is not defined in IEEE Std 1003.1-2001 (“POSIX.1”). The -1, -C, -x, and -l options all override each other; the last one specified determines the format used. The -c, -u, and -U options all override each other; the last one specified determines the file time used. The -S and -t options override each other; the last one specified determines the sort order used. The -B, -b, -w, and -q options all override each other; the last one specified determines the format used for non-printable characters. The -H, -L and -P options all override each other (either partially or fully); they are applied in the order specified. By default, ls lists one entry per line to standard output; the exceptions are to terminals or when the -C or -x options are specified. File information is displayed with one or more ⟨blank⟩s separating the information associated with the -i, -s, and -l options. The Long Format If the -l option is given, the following information is displayed for each file: file mode, number of links, owner name, group name, number of bytes in the file, abbreviated month, day-of-month file was last modified, hour file last modified, minute file last modified, and the pathname. If the file or directory has extended attributes, the permissions field printed by the -l option is followed by a '@' character. Otherwise, if the file or directory has extended security information (such as an access control list), the permissions field printed by the -l option is followed by a '+' character. If the -% option is given, a '%' character follows the permissions field for dataless files and directories, possibly replacing the '@' or '+' character. If the modification time of the file is more than 6 months in the past or future, and the -D or -T are not specified, then the year of the last modification is displayed in place of the hour and minute fields. If the owner or group names are not a known user or group name, or the -n option is given, the numeric ID's are displayed. If the file is a character special or block special file, the device number for the file is displayed in the size field. If the file is a symbolic link the pathname of the linked-to file is preceded by “->”. The listing of a directory's contents is preceded by a labeled total number of blocks used in the file system by the files which are listed as the directory's contents (which may or may not include . and .. and other files which start with a dot, depending on other options). The default block size is 512 bytes. The block size may be set with option -k or environment variable BLOCKSIZE. Numbers of blocks in the output will have been rounded up so the numbers of bytes is at least as many as used by the corresponding file system blocks (which might have a different size). The file mode printed under the -l option consists of the entry type and the permissions. The entry type character describes the type of file, as follows: - Regular file. b Block special file. c Character special file. d Directory. l Symbolic link. p FIFO. s Socket. w Whiteout. The next three fields are three characters each: owner permissions, group permissions, and other permissions. Each field has three character positions: 1. If r, the file is readable; if -, it is not readable. 2. If w, the file is writable; if -, it is not writable. 3. The first of the following that applies: S If in the owner permissions, the file is not executable and set-user-ID mode is set. If in the group permissions, the file is not executable and set-group-ID mode is set. s If in the owner permissions, the file is executable and set-user-ID mode is set. If in the group permissions, the file is executable and setgroup-ID mode is set. x The file is executable or the directory is searchable. - The file is neither readable, writable, executable, nor set-user-ID nor set-group-ID mode, nor sticky. (See below.) These next two apply only to the third character in the last group (other permissions). T The sticky bit is set (mode 1000), but not execute or search permission. (See chmod(1) or sticky(7).) t The sticky bit is set (mode 1000), and is searchable or executable. (See chmod(1) or sticky(7).) The next field contains a plus (‘+’) character if the file has an ACL, or a space (‘ ’) if it does not. The ls utility does not show the actual ACL unless the -e option is used in conjunction with the -l option. ENVIRONMENT The following environment variables affect the execution of ls: BLOCKSIZE If this is set, its value, rounded up to 512 or down to a multiple of 512, will be used as the block size in bytes by the -l and -s options. See The Long Format subsection for more information. CLICOLOR Use ANSI color sequences to distinguish file types. See LSCOLORS below. In addition to the file types mentioned in the -F option some extra attributes (setuid bit set, etc.) are also displayed. The colorization is dependent on a terminal type with the proper termcap(5) capabilities. The default “cons25” console has the proper capabilities, but to display the colors in an xterm(1), for example, the TERM variable must be set to “xterm-color”. Other terminal types may require similar adjustments. Colorization is silently disabled if the output is not directed to a terminal unless the CLICOLOR_FORCE variable is defined or --color is set to “always”. CLICOLOR_FORCE Color sequences are normally disabled if the output is not directed to a terminal. This can be overridden by setting this variable. The TERM variable still needs to reference a color capable terminal however otherwise it is not possible to determine which color sequences to use. COLORTERM See description for CLICOLOR above. COLUMNS If this variable contains a string representing a decimal integer, it is used as the column position width for displaying multiple-text-column output. The ls utility calculates how many pathname text columns to display based on the width provided. (See -C and -x.) LANG The locale to use when determining the order of day and month in the long -l format output. See environ(7) for more information. LSCOLORS The value of this variable describes what color to use for which attribute when colors are enabled with CLICOLOR or COLORTERM. This string is a concatenation of pairs of the format fb, where f is the foreground color and b is the background color. The color designators are as follows: a black b red c green d brown e blue f magenta g cyan h light grey A bold black, usually shows up as dark grey B bold red C bold green D bold brown, usually shows up as yellow E bold blue F bold magenta G bold cyan H bold light grey; looks like bright white x default foreground or background Note that the above are standard ANSI colors. The actual display may differ depending on the color capabilities of the terminal in use. The order of the attributes are as follows: 1. directory 2. symbolic link 3. socket 4. pipe 5. executable 6. block special 7. character special 8. executable with setuid bit set 9. executable with setgid bit set 10. directory writable to others, with sticky bit 11. directory writable to others, without sticky bit The default is "exfxcxdxbxegedabagacad", i.e., blue foreground and default background for regular directories, black foreground and red background for setuid executables, etc. LS_COLWIDTHS If this variable is set, it is considered to be a colon-delimited list of minimum column widths. Unreasonable and insufficient widths are ignored (thus zero signifies a dynamically sized column). Not all columns have changeable widths. The fields are, in order: inode, block count, number of links, user name, group name, flags, file size, file name. LS_SAMESORT If this variable is set, the -t option sorts the names of files with the same modification timestamp in the same sense as the time sort. See the description of the -t option for more details. TERM The CLICOLOR and COLORTERM functionality depends on a terminal type with color capabilities. TZ The timezone to use when displaying dates. See environ(7) for more information. EXIT STATUS The ls utility exits 0 on success, and >0 if an error occurs.
ls – list directory contents
ls [-@ABCFGHILOPRSTUWabcdefghiklmnopqrstuvwxy1%,] [--color=when] [-D format] [file ...]
null
List the contents of the current working directory in long format: $ ls -l In addition to listing the contents of the current working directory in long format, show inode numbers, file flags (see chflags(1)), and suffix each filename with a symbol representing its file type: $ ls -lioF List the files in /var/log, sorting the output such that the most recently modified entries are printed first: $ ls -lt /var/log COMPATIBILITY The group field is now automatically included in the long listing for files in order to be compatible with the IEEE Std 1003.2 (“POSIX.2”) specification. LEGACY DESCRIPTION In legacy mode, the -f option does not turn on the -a option and the -g, -n, and -o options do not turn on the -l option. Also, the -o option causes the file flags to be included in a long (-l) output; there is no -O option. When -H is specified (and not overridden by -L or -P) and a file argument is a symlink that resolves to a non-directory file, the output will reflect the nature of the link, rather than that of the file. In legacy operation, the output will describe the file. For more information about legacy mode, see compat(5). SEE ALSO chflags(1), chmod(1), sort(1), xterm(1), localeconv(3), strftime(3), strmode(3), compat(5), termcap(5), sticky(7), symlink(7) STANDARDS With the exception of options -g, -n and -o, the ls utility conforms to IEEE Std 1003.1-2001 (“POSIX.1”) and IEEE Std 1003.1-2008 (“POSIX.1”). The options -B, -D, -G, -I, -T, -U, -W, -Z, -b, -h, -w, -y and -, are non-standard extensions. The ACL support is compatible with IEEE Std 1003.2c (“POSIX.2c”) Draft 17 (withdrawn). HISTORY An ls command appeared in Version 1 AT&T UNIX. BUGS To maintain backward compatibility, the relationships between the many options are quite complex. The exception mentioned in the -s option description might be a feature that was based on the fact that single-column output usually goes to something other than a terminal. It is debatable whether this is a design bug. IEEE Std 1003.2 (“POSIX.2”) mandates opposite sort orders for files with the same timestamp when sorting with the -t option. macOS 14.5 August 31, 2020 macOS 14.5
cp
In the first synopsis form, the cp utility copies the contents of the source_file to the target_file. In the second synopsis form, the contents of each named source_file is copied to the destination target_directory. The names of the files themselves are not changed. If cp detects an attempt to copy a file to itself, the copy will fail. The following options are available: -H If the -R option is specified, symbolic links on the command line are followed. (Symbolic links encountered in the tree traversal are not followed.) -L If the -R option is specified, all symbolic links are followed. -P No symbolic links are followed. This is the default if the -R option is specified. -R If source_file designates a directory, cp copies the directory and the entire subtree connected at that point. If the source_file ends in a /, the contents of the directory are copied rather than the directory itself. This option also causes symbolic links to be copied, rather than indirected through, and for cp to create special files rather than copying them as normal files. Created directories have the same mode as the corresponding source directory, unmodified by the process' umask. In -R mode, cp will continue copying even if errors are detected. Note that cp copies hard linked files as separate files. If you need to preserve hard links, consider using tar(1), cpio(1), or pax(1) instead. -a Archive mode. Same as -RpP options. Preserves structure and attributes of files but not directory structure. -c copy files using clonefile(2). Note that if clonefile(2) is not supported for the target filesystem, then cp will fallback to using copyfile(2) instead to ensure the copy still succeeds. -f If the destination file cannot be opened, remove it and create a new file, without prompting for confirmation regardless of its permissions. (The -f option overrides any previous -n option.) The target file is not unlinked before the copy. Thus, any existing access rights will be retained. -i Cause cp to write a prompt to the standard error output before copying a file that would overwrite an existing file. If the response from the standard input begins with the character ‘y’ or ‘Y’, the file copy is attempted. (The -i option overrides any previous -n option.) -l Create hard links to regular files in a hierarchy instead of copying. -n Do not overwrite an existing file. (The -n option overrides any previous -f or -i options.) -p Cause cp to preserve the following attributes of each source file in the copy: modification time, access time, file flags, file mode, user ID, and group ID, as allowed by permissions. Access Control Lists (ACLs) and Extended Attributes (EAs), including resource forks, will also be preserved. If the user ID and group ID cannot be preserved, no error message is displayed and the exit value is not altered. If the source file has its set-user-ID bit on and the user ID cannot be preserved, the set-user-ID bit is not preserved in the copy's permissions. If the source file has its set-group-ID bit on and the group ID cannot be preserved, the set-group-ID bit is not preserved in the copy's permissions. If the source file has both its set-user-ID and set-group-ID bits on, and either the user ID or group ID cannot be preserved, neither the set-user-ID nor set- group-ID bits are preserved in the copy's permissions. -S Do not attempt to preserve holes in sparse files. -s Create symbolic links to regular files in a hierarchy instead of copying. -v Cause cp to be verbose, showing files as they are copied. -X Do not copy Extended Attributes (EAs) or resource forks. -x File system mount points are not traversed. For each destination file that already exists, its contents are overwritten if permissions allow. Its mode, user ID, and group ID are unchanged unless the -p option was specified. In the second synopsis form, target_directory must exist unless there is only one named source_file which is a directory and the -R flag is specified. If the destination file does not exist, the mode of the source file is used as modified by the file mode creation mask (umask, see csh(1)). If the source file has its set-user-ID bit on, that bit is removed unless both the source file and the destination file are owned by the same user. If the source file has its set-group-ID bit on, that bit is removed unless both the source file and the destination file are in the same group and the user is a member of that group. If both the set-user-ID and set-group-ID bits are set, all of the above conditions must be fulfilled or both bits are removed. Appropriate permissions are required for file creation or overwriting. Symbolic links are always followed unless the -R flag is set, in which case symbolic links are not followed, by default. The -H or -L flags (in conjunction with the -R flag) cause symbolic links to be followed as described above. The -H, -L and -P options are ignored unless the -R option is specified. In addition, these options override each other and the command's actions are determined by the last one specified. If cp receives a SIGINFO (see the status argument for stty(1)) signal, the current input and output file and the percentage complete will be written to the standard output. If cp encounters an I/O error during the copy, then cp may leave a partially copied target_file in place. cp specifically avoids cleaning up the output file in error cases to avoid further data loss in cases where the source may not be recoverable. Alternatives, like install(1), may be preferred if stronger guarantees about the target_file are required. EXIT STATUS The cp utility exits 0 on success, and >0 if an error occurs.
cp – copy files
cp [-R [-H | -L | -P]] [-fi | -n] [-alpSsvXx] source_file target_file cp [-R [-H | -L | -P]] [-fi | -n] [-alpSsvXx] source_file ... target_directory cp [-f | -i | -n] [-alPpSsvx] source_file target_file cp [-f | -i | -n] [-alPpSsvx] source_file ... target_directory
null
Make a copy of file foo named bar: $ cp foo bar Copy a group of files to the /tmp directory: $ cp *.txt /tmp Copy the directory junk and all of its contents (including any subdirectories) to the /tmp directory: $ cp -R junk /tmp COMPATIBILITY Historic versions of the cp utility had a -r option. This implementation supports that option, however, its behavior is different from historical FreeBSD behavior. Use of this option is strongly discouraged as the behavior is implementation-dependent. In FreeBSD, -r is a synonym for -RL and works the same unless modified by other flags. Historical implementations of -r differ as they copy special files as normal files while recreating a hierarchy. The -l, -s, -v, -x and -n options are non-standard and their use in scripts is not recommended. LEGACY DESCRIPTION In legacy mode, -f will override -i. Also, under the -f option, the target file is always unlinked before the copy. Thus, new access rights will always be set. In -R mode, copying will terminate if an error is encountered. For more information about legacy mode, see compat(5). SEE ALSO install(1), mv(1), rcp(1), clonefile(2), copyfile(2), umask(2), fts(3), compat(5), symlink(7) STANDARDS The cp command is expected to be IEEE Std 1003.2 (“POSIX.2”) compatible. HISTORY A cp command appeared in Version 1 AT&T UNIX. macOS 14.5 April 17, 2022 macOS 14.5
sync
The sync utility can be called to ensure that all disk writes have been completed before the processor is halted in a way not suitably done by reboot(8) or halt(8). Generally, it is preferable to use reboot(8) or halt(8) to shut down the system, as they may perform additional actions such as resynchronizing the hardware clock and flushing internal caches before performing a final sync. The sync utility utilizes the sync(2) function call. SEE ALSO fsync(2), sync(2), halt(8), reboot(8) HISTORY A sync utility appeared in Version 4 AT&T UNIX. macOS 14.5 May 31, 1993 macOS 14.5
sync – force completion of pending disk writes (flush cache)
sync
null
null
zsh
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. It does not provide compatibility with POSIX or other shells in its default operating mode: see the section `Compatibility' below. 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. Zsh is now maintained by the members of the zsh-workers mailing list <zsh-workers@zsh.org>. 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 HTTP and anonymous FTP site. ftp://ftp.zsh.org/pub/ https://www.zsh.org/pub/ The up-to-date source code is available via Git from Sourceforge. See https://sourceforge.net/projects/zsh/ for details. A summary of instructions for the archive can be found at https://zsh.sourceforge.io/. MAILING LISTS Zsh has several mailing lists: <zsh-announce@zsh.org> Announcements about releases, major changes in the shell and the monthly posting of the Zsh FAQ. (moderated) <zsh-users@zsh.org> User discussions. <zsh-workers@zsh.org> Hacking, development, bug reports and patches. <zsh-security@zsh.org> Private mailing list (the general public cannot subscribe to it) for discussing bug reports with security implications, i.e., potential vulnerabilities. If you find a security problem in zsh itself, please mail this address. To subscribe or unsubscribe, send mail to the associated administrative address for the mailing list. <zsh-announce-subscribe@zsh.org> <zsh-users-subscribe@zsh.org> <zsh-workers-subscribe@zsh.org> <zsh-announce-unsubscribe@zsh.org> <zsh-users-unsubscribe@zsh.org> <zsh-workers-unsubscribe@zsh.org> YOU ONLY NEED TO JOIN ONE OF THE MAILING LISTS AS THEY ARE NESTED. All submissions to zsh-announce are automatically forwarded to zsh-users. All submissions to zsh-users are automatically forwarded to zsh-workers. If you have problems subscribing/unsubscribing to any of the mailing lists, send mail to <listmaster@zsh.org>. The mailing lists are archived; the archives can be accessed via the administrative addresses listed above. There is also a hypertext archive available at https://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 zsh-announce mailing list. The latest version can be found at any of the Zsh FTP sites, or at https://www.zsh.org/FAQ/. The contact address for FAQ-related matters is <faqmaster@zsh.org>. THE ZSH WEB PAGE Zsh has a web page which is located at https://www.zsh.org/. The contact address for web-related 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 https://zsh.sourceforge.io/Guide/. At the time of writing, chapters dealing with startup files and their contents and the new completion system were essentially complete. INVOCATION 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. -i Force shell to be interactive. It is still possible to specify a script to execute. -s 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. If there are any remaining arguments after option processing, and neither of the options -c or -s was supplied, the first argument is taken as the file name of a script containing shell commands to be executed. If the option PATH_SCRIPT is set, and the file name does not contain a directory path (i.e. there is no `/' in the name), first the current directory and then the command path given by the variable PATH are searched for the script. If the option is not set or the file name contains a `/' it is used directly. 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). The long option `--emulate' followed (in a separate word) by an emulation mode may be passed to the shell. The emulation modes are those described for the emulate builtin, see zshbuiltins(1). The `--emulate' option must precede any other options (which might otherwise be overridden), but following options are honoured, so may be used to modify the requested emulation mode. Note that certain extra steps are taken to ensure a smooth emulation when this option is used compared with the emulate command within the shell: for example, variables that conflict with POSIX usage such as path are not defined within the shell. Options may be specified by name using the -o option. -o acts like a single-letter 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 single-letter 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, `--option-name'. When this is done, `-' characters in the option name are permitted: they are translated into `_', and thus ignored. So, for example, `zsh --sh-word-split' 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 `+-sh-word-split' is equivalent to `--no-sh-word-split'. Unlike other option syntaxes, GNU-style long options cannot be stacked with any other options, so for example `-x-shwordsplit' is an error, rather than being treated like `-x --shwordsplit'. The special GNU-style option `--version' is handled; it sends to standard output the shell's 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 `-x-f' is an error), but note the GNU-style option form discussed above, where `--shwordsplit' is permitted and does not end option processing. Except when the sh/ksh emulation single-letter options are in effect, the option `-b' (or `+b') ends option processing. `-b' is like `--', except that further single-letter 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 `b', `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. 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. Please note that, whilst reasonable efforts are taken to address incompatibilities when they arise, zsh does not guarantee complete emulation of other shells, nor POSIX compliance. For more information on the differences between zsh and other shells, please refer to chapter 2 of the shell FAQ, https://www.zsh.org/FAQ/. 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: • changing directories with the cd builtin • changing or unsetting the EGID, EUID, GID, HISTFILE, HISTSIZE, IFS, LD_AOUT_LIBRARY_PATH, LD_AOUT_PRELOAD, LD_LIBRARY_PATH, LD_PRELOAD, MODULE_PATH, module_path, PATH, path, SHELL, UID and USERNAME 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 • 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. A shell Restricted Mode is an outdated way to restrict what users may do: modern systems have better, safer and more reliable ways to confine user actions, such as chroot jails, containers and zones. A restricted shell is very difficult to implement safely. The feature may be removed in a future version of zsh. It is important to realise that the restrictions only apply to the shell, not to the commands it runs (except for some shell builtins). While a restricted shell can only run the restricted list of commands accessible via the predefined `PATH' variable, it does not prevent those commands from running any other command. As an example, if `env' is among the list of allowed commands, then it allows the user to run any command as `env' is not a shell builtin command and can run arbitrary executables. So when implementing a restricted shell framework it is important to be fully aware of what actions each of the allowed commands or features (which may be regarded as modules) can perform. Many commands can have their behaviour affected by environment variables. Except for the few listed above, zsh does not restrict the setting of environment variables. If a `perl', `python', `bash', or other general purpose interpreted script it treated as a restricted command, the user can work around the restriction by setting specially crafted `PERL5LIB', `PYTHONPATH', `BASHENV' (etc.) environment variables. On GNU systems, any command can be made to run arbitrary code when performing character set conversion (including zsh itself) by setting a `GCONV_PATH' environment variable. Those are only a few examples. Bear in mind that, contrary to some other shells, `readonly' is not a security feature in zsh as it can be undone and so cannot be used to mitigate the above. A restricted shell only works if the allowed commands are few and carefully written so as not to grant more access to users than intended. It is also important to restrict what zsh module the user may load as some of them, such as `zsh/system', `zsh/mapfile' and `zsh/files', allow bypassing most of the restrictions. 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 global startup files (those shown here with an path starting with a /). 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 re-enable 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 end-of-file from the terminal. However, if the shell terminates due to exec'ing 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. 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 pre-compiled 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. 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 (installation-specific - /etc is the default) SEE ALSO sh(1), csh(1), tcsh(1), rc(1), bash(1), ksh(1), zshall(1), zshbuiltins(1), zshcompwid(1), zshcompsys(1), zshcompctl(1), zshcontrib(1), zshexpn(1), zshmisc(1), zshmodules(1), zshoptions(1), zshparam(1), zshroadmap(1), zshtcpsys(1), zshzftpsys(1), zshzle(1) IEEE Standard for information Technology - Portable Operating System Interface (POSIX) - Part 2: Shell and Utilities, IEEE Inc, 1993, ISBN 1-55937-255-9. zsh 5.9 May 14, 2022 ZSH(1)
zsh - the Z shell OVERVIEW Because zsh contains many features, the zsh manual has been split into a number of sections: zsh Zsh overview (this section) 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 built-in functions zshzle Zsh command line editing zshcompwid Zsh completion widgets zshcompsys Zsh completion system zshcompctl Zsh completion control zshmodules Zsh loadable modules zshtcpsys Zsh built-in TCP functions zshzftpsys Zsh built-in FTP client zshcontrib Additional zsh functions and utilities zshall Meta-man page containing all of the above
null
null
null
chmod
The chmod utility modifies the file mode bits of the listed files as specified by the mode operand. It may also be used to modify the Access Control Lists (ACLs) associated with the listed files. The generic options are as follows: -f Do not display a diagnostic message if chmod could not modify the mode for file, nor modify the exit status to reflect such failures. -H If the -R option is specified, symbolic links on the command line are followed and hence unaffected by the command. (Symbolic links encountered during tree traversal are not followed.) -h If the file is a symbolic link, change the mode of the link itself rather than the file that the link points to. -L If the -R option is specified, all symbolic links are followed. -P If the -R option is specified, no symbolic links are followed. This is the default. -R Change the modes of the file hierarchies rooted in the files, instead of just the files themselves. Beware of unintentionally matching the “..” hard link to the parent directory when using wildcards like “.*”. -v Cause chmod to be verbose, showing filenames as the mode is modified. If the -v flag is specified more than once, the old and new modes of the file will also be printed, in both octal and symbolic notation. The -H, -L and -P options are ignored unless the -R option is specified. In addition, these options override each other and the command's actions are determined by the last one specified. If chmod receives a SIGINFO signal (see the status argument for stty(1)), then the current filename as well as the old and new modes are displayed. Only the owner of a file or the super-user is permitted to change the mode of a file. EXIT STATUS The chmod utility exits 0 on success, and >0 if an error occurs. MODES Modes may be absolute or symbolic. An absolute mode is an octal number constructed from the sum of one or more of the following values: 4000 (the setuid bit). Executable files with this bit set will run with effective uid set to the uid of the file owner. Directories with this bit set will force all files and sub- directories created in them to be owned by the directory owner and not by the uid of the creating process, if the underlying file system supports this feature: see chmod(2) and the suiddir option to mount(8). 2000 (the setgid bit). Executable files with this bit set will run with effective gid set to the gid of the file owner. 1000 (the sticky bit). See chmod(2) and sticky(7). 0400 Allow read by owner. 0200 Allow write by owner. 0100 For files, allow execution by owner. For directories, allow the owner to search in the directory. 0040 Allow read by group members. 0020 Allow write by group members. 0010 For files, allow execution by group members. For directories, allow group members to search in the directory. 0004 Allow read by others. 0002 Allow write by others. 0001 For files, allow execution by others. For directories allow others to search in the directory. For example, the absolute mode that permits read, write and execute by the owner, read and execute by group members, read and execute by others, and no set-uid or set-gid behaviour is 755 (400+200+100+040+010+004+001). The symbolic mode is described by the following grammar: mode ::= clause [, clause ...] clause ::= [who ...] [action ...] action action ::= op [perm ...] who ::= a | u | g | o op ::= + | - | = perm ::= r | s | t | w | x | X | u | g | o The who symbols ``u'', ``g'', and ``o'' specify the user, group, and other parts of the mode bits, respectively. The who symbol ``a'' is equivalent to ``ugo''. The perm symbols represent the portions of the mode bits as follows: r The read bits. s The set-user-ID-on-execution and set-group-ID-on-execution bits. t The sticky bit. w The write bits. x The execute/search bits. X The execute/search bits if the file is a directory or any of the execute/search bits are set in the original (unmodified) mode. Operations with the perm symbol ``X'' are only meaningful in conjunction with the op symbol ``+'', and are ignored in all other cases. u The user permission bits in the original mode of the file. g The group permission bits in the original mode of the file. o The other permission bits in the original mode of the file. The op symbols represent the operation performed, as follows: + If no value is supplied for perm, the ``+'' operation has no effect. If no value is supplied for who, each permission bit specified in perm, for which the corresponding bit in the file mode creation mask (see umask(2)) is clear, is set. Otherwise, the mode bits represented by the specified who and perm values are set. - If no value is supplied for perm, the ``-'' operation has no effect. If no value is supplied for who, each permission bit specified in perm, for which the corresponding bit in the file mode creation mask is set, is cleared. Otherwise, the mode bits represented by the specified who and perm values are cleared. = The mode bits specified by the who value are cleared, or, if no who value is specified, the owner, group and other mode bits are cleared. Then, if no value is supplied for who, each permission bit specified in perm, for which the corresponding bit in the file mode creation mask (see umask(2)) is clear, is set. Otherwise, the mode bits represented by the specified who and perm values are set. Each clause specifies one or more operations to be performed on the mode bits, and each operation is applied to the mode bits in the order specified. Operations upon the other permissions only (specified by the symbol ``o'' by itself), in combination with the perm symbols ``s'' or ``t'', are ignored. The ``w'' permission on directories will permit file creation, relocation, and copy into that directory. Files created within the directory itself will inherit its group ID. EXAMPLES OF VALID MODES 644 make a file readable by anyone and writable by the owner only. go-w deny write permission to group and others. =rw,+X set the read and write permissions to the usual defaults, but retain any execute permissions that are currently set. +X make a directory or file searchable/executable by everyone if it is already searchable/executable by anyone. 755 u=rwx,go=rx u=rwx,go=u-w make a file readable/executable by everyone and writable by the owner only. go= clear all mode bits for group and others. g=u-w set the group bits equal to the user bits, but clear the group write bit. ACL MANIPULATION OPTIONS ACLs are manipulated using extensions to the symbolic mode grammar. Each file has one ACL, containing an ordered list of entries. Each entry refers to a user or group, and grants or denies a set of permissions. In cases where a user and a group exist with the same name, the user/group name can be prefixed with "user:" or "group:" in order to specify the type of name. If the user or group name contains spaces you can use ':' as the delimiter between name and permission. The following permissions are applicable to all filesystem objects: delete Delete the item. Deletion may be granted by either this permission on an object or the delete_child right on the containing directory. readattr Read an object's basic attributes. This is implicitly granted if the object can be looked up and not explicitly denied. writeattr Write an object's basic attributes. readextattr Read extended attributes. writeextattr Write extended attributes. readsecurity Read an object's extended security information (ACL). writesecurity Write an object's security information (ownership, mode, ACL). chown Change an object's ownership. The following permissions are applicable to directories: list List entries. search Look up files by name. add_file Add a file. add_subdirectory Add a subdirectory. delete_child Delete a contained object. See the file delete permission above. The following permissions are applicable to non-directory filesystem objects: read Open for reading. write Open for writing. append Open for writing, but in a fashion that only allows writes into areas of the file not previously written. execute Execute the file as a script or program. ACL inheritance is controlled with the following permissions words, which may only be applied to directories: file_inherit Inherit to files. directory_inherit Inherit to directories. limit_inherit This flag is only relevant to entries inherited by subdirectories; it causes the directory_inherit flag to be cleared in the entry that is inherited, preventing further nested subdirectories from also inheriting the entry. only_inherit The entry is inherited by created items but not considered when processing the ACL. The ACL manipulation options are as follows: +a The +a mode parses a new ACL entry from the next argument on the commandline and inserts it into the canonical location in the ACL. If the supplied entry refers to an identity already listed, the two entries are combined.
chmod – change file modes or Access Control Lists
chmod [-fhv] [-R [-H | -L | -P]] mode file ... chmod [-fhv] [-R [-H | -L | -P]] [-a | +a | =a] ACE file ... chmod [-fhv] [-R [-H | -L | -P]] [-E] file ... chmod [-fhv] [-R [-H | -L | -P]] [-C] file ... chmod [-fhv] [-R [-H | -L | -P]] [-N] file ...
null
# ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 # chmod +a "admin allow write" file1 # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: admin allow write # chmod +a "guest deny read" file1 # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: guest deny read 2: admin allow write # chmod +a "admin allow delete" file1 # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: guest deny read 2: admin allow write,delete . # chmod +a "User 1:allow:read" file1 # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: guest deny read 2: User 1 allow read 3: admin allow write,delete The +a mode strives to maintain correct canonical form for the ACL. local deny local allow inherited deny inherited allow By default, chmod adds entries to the top of the local deny and local allow lists. Inherited entries are added by using the +ai mode. # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: guest deny read 2: admin allow write,delete 3: juser inherited deny delete 4: admin inherited allow delete 5: backup inherited deny read 6: admin inherited allow write-security # chmod +ai "others allow read" file1 # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: guest deny read 2: admin allow write,delete 3: juser inherited deny delete 4: others inherited allow read 5: admin inherited allow delete 6: backup inherited deny read 7: admin inherited allow write-security +a# When a specific ordering is required, the exact location at which an entry will be inserted is specified with the +a# mode. # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: guest deny read 2: admin allow write # chmod +a# 2 "others deny read" file1 # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: guest deny read 2: others deny read 3: admin allow write The +ai# mode may be used to insert inherited entries at a specific location. Note that these modes allow non-canonical ACL ordering to be constructed. -a The -a mode is used to delete ACL entries. All entries exactly matching the supplied entry will be deleted. If the entry lists a subset of rights granted by an entry, only the rights listed are removed. Entries may also be deleted by index using the -a# mode. # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: guest deny read 2: admin allow write,delete # chmod -a# 1 file1 # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: admin allow write,delete # chmod -a "admin allow write" file1 # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: admin allow delete Inheritance is not considered when processing the -a mode; rights and entries will be removed regardless of their inherited state. If the user or group name contains spaces you can use ':' as the delimiter Example # chmod +a "User 1:allow:read" file1 =a# Individual entries are rewritten using the =a# mode. # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: admin allow delete # chmod =a# 1 "admin allow write,chown" file1 # ls -le -rw-r--r--+ 1 juser wheel 0 Apr 28 14:06 file1 owner: juser 1: admin allow write,chown This mode may not be used to add new entries. -E Reads the ACL information from stdin, as a sequential list of ACEs, separated by newlines. If the information parses correctly, the existing information is replaced. -C Returns false if any of the named files have ACLs in non- canonical order. -i Removes the 'inherited' bit from all entries in the named file(s) ACLs. -I Removes all inherited entries from the named file(s) ACL(s). -N Removes the ACL from the named file(s). COMPATIBILITY The -v option is non-standard and its use in scripts is not recommended. SEE ALSO chflags(1), install(1), chmod(2), stat(2), umask(2), fts(3), setmode(3), sticky(7), symlink(7), chown(8), mount(8) STANDARDS The chmod utility is expected to be IEEE Std 1003.2 (“POSIX.2”) compatible with the exception of the perm symbol “t” which is not included in that standard. HISTORY A chmod command appeared in Version 1 AT&T UNIX. macOS 14.5 January 7, 2017 macOS 14.5
rm
The rm utility attempts to remove the non-directory type files specified on the command line. If the permissions of the file do not permit writing, and the standard input device is a terminal, the user is prompted (on the standard error output) for confirmation. The options are as follows: -d Attempt to remove directories as well as other types of files. -f Attempt to remove the files without prompting for confirmation, regardless of the file's permissions. If the file does not exist, do not display a diagnostic message or modify the exit status to reflect an error. The -f option overrides any previous -i options. -i Request confirmation before attempting to remove each file, regardless of the file's permissions, or whether or not the standard input device is a terminal. The -i option overrides any previous -f options. -I Request confirmation once if more than three files are being removed or if a directory is being recursively removed. This is a far less intrusive option than -i yet provides almost the same level of protection against mistakes. -P This flag has no effect. It is kept only for backwards compatibility with 4.4BSD-Lite2. -R Attempt to remove the file hierarchy rooted in each file argument. The -R option implies the -d option. If the -i option is specified, the user is prompted for confirmation before each directory's contents are processed (as well as before the attempt is made to remove the directory). If the user does not respond affirmatively, the file hierarchy rooted in that directory is skipped. -r Equivalent to -R. -v Be verbose when deleting files, showing them as they are removed. -W Attempt to undelete the named files. Currently, this option can only be used to recover files covered by whiteouts in a union file system (see undelete(2)). -x When removing a hierarchy, do not cross mount points. The rm utility removes symbolic links, not the files referenced by the links. It is an error to attempt to remove the files /, . or ... When the utility is called as unlink, only one argument, which must not be a directory, may be supplied. No options may be supplied in this simple mode of operation, which performs an unlink(2) operation on the passed argument. However, the usual option-end delimiter, --, may optionally precede the argument. EXIT STATUS The rm utility exits 0 if all of the named files or file hierarchies were removed, or if the -f option was specified and all of the existing files or file hierarchies were removed. If an error occurs, rm exits with a value >0. NOTES The rm command uses getopt(3) to parse its arguments, which allows it to accept the ‘--’ option which will cause it to stop processing flag options at that point. This will allow the removal of file names that begin with a dash (‘-’). For example: rm -- -filename The same behavior can be obtained by using an absolute or relative path reference. For example: rm /home/user/-filename rm ./-filename
rm, unlink – remove directory entries
rm [-f | -i] [-dIRrvWx] file ... unlink [--] file
null
Recursively remove all files contained within the foobar directory hierarchy: $ rm -rf foobar Any of these commands will remove the file -f: $ rm -- -f $ rm ./-f $ unlink -f COMPATIBILITY The rm utility differs from historical implementations in that the -f option only masks attempts to remove non-existent files instead of masking a large variety of errors. The -v option is non-standard and its use in scripts is not recommended. Also, historical BSD implementations prompted on the standard output, not the standard error output. The -P option does not have any effect as of FreeBSD 13 and may be removed in the future. SEE ALSO chflags(1), rmdir(1), undelete(2), unlink(2), fts(3), getopt(3), symlink(7) STANDARDS The rm command conforms to. The simplified unlink command conforms to Version 2 of the Single UNIX Specification (“SUSv2”). HISTORY A rm command appeared in Version 1 AT&T UNIX. BUGS The -P option assumes that the underlying file system is a fixed-block file system. In addition, only regular files are overwritten, other types of files are not. macOS 14.5 November 10, 2018 macOS 14.5
[
The test utility evaluates the expression and, if it evaluates to true, returns a zero (true) exit status; otherwise it returns 1 (false). If there is no expression, test also returns 1 (false). All operators and flags are separate arguments to the test utility. The following primaries are used to construct expression: -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 (regardless of type). -f file True if file exists and is a regular file. -g file True if file exists and its set group ID flag is set. -h file True if file exists and is a symbolic link. This operator is retained for compatibility with previous versions of this program. Do not rely on its existence; use -L instead. -k file True if file exists and its sticky bit is set. -n string True if the length of string is nonzero. -p file True if file is a named pipe (FIFO). -r file True if file exists and is readable. -s file True if file exists and has a size greater than zero. -t file_descriptor True if the file whose file descriptor number is file_descriptor is open and is associated with a terminal. -u file True if file exists and its set user ID flag is set. -w file True if file exists and is writable. True indicates only that the write flag is on. The file is not writable on a read-only file system even if this test indicates true. -x file True if file exists and is executable. True indicates only that the execute flag is on. If file is a directory, true indicates that file can be searched. -z string True if the length of string is zero. -L file True if file exists and is a symbolic link. -O file True if file exists and its owner matches the effective user id of this process. -G file True if file exists and its group matches the effective group id of this process. -S file True if file exists and is a socket. 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 True if string is not the null string. s1 = s2 True if the strings s1 and s2 are identical. s1 != s2 True if the strings s1 and s2 are not identical. s1 < s2 True if string s1 comes before s2 based on the binary value of their characters. s1 > s2 True if string s1 comes after s2 based on the binary value of their characters. n1 -eq n2 True if the integers n1 and n2 are algebraically equal. n1 -ne n2 True if the integers n1 and n2 are not algebraically equal. n1 -gt n2 True if the integer n1 is algebraically greater than the integer n2. n1 -ge n2 True if the integer n1 is algebraically greater than or equal to the integer n2. n1 -lt n2 True if the integer n1 is algebraically less than the integer n2. n1 -le n2 True if the integer n1 is algebraically less than or equal to the integer n2. If file is a symbolic link, test will fully dereference it and then evaluate the expression against the file referenced, except for the -h and -L primaries. These primaries can be combined with the following operators: ! expression True if expression is false. expression1 -a expression2 True if both expression1 and expression2 are true. expression1 -o expression2 True if either expression1 or expression2 are true. ( expression ) True if expression is true. The -a operator has higher precedence than the -o operator. Some shells may provide a builtin test command which is similar or identical to this utility. Consult the builtin(1) manual page. GRAMMAR AMBIGUITY The test grammar is inherently ambiguous. In order to assure a degree of consistency, the cases described in the IEEE Std 1003.2 (“POSIX.2”), section D11.2/4.62.4, standard are evaluated consistently according to the rules specified in the standards document. All other cases are subject to the ambiguity in the command semantics. In particular, only expressions containing -a, -o, ( or ) can be ambiguous. EXIT STATUS The test utility exits with one of the following values: 0 expression evaluated to true. 1 expression evaluated to false or expression was missing. >1 An error occurred.
test, [ – condition evaluation utility
test expression [ expression ]
null
Implement test FILE1 -nt FILE2 using only POSIX functionality: test -n "$(find -L -- FILE1 -prune -newer FILE2 2>/dev/null)" This can be modified using non-standard find(1) primaries like -newerca to compare other timestamps. COMPATIBILITY For compatibility with some other implementations, the = primary can be substituted with == with the same meaning. SEE ALSO builtin(1), expr(1), find(1), sh(1), stat(1), symlink(7) STANDARDS The test utility implements a superset of the IEEE Std 1003.2 (“POSIX.2”) specification. The primaries <, ==, >, -ef, -nt, -ot, -G, and -O are extensions. HISTORY A test utility appeared in Version 7 AT&T UNIX. BUGS Both sides are always evaluated in -a and -o. For instance, the writable status of file will be tested by the following command even though the former expression indicated false, which results in a gratuitous access to the file system: [ -z abc -a -w file ] To avoid this, write [ -z abc ] && [ -w file ] macOS 14.5 October 5, 2016 macOS 14.5
dsconfigad
This tool allows command-line configuration of the Active Directory. dsconfigad has the same functionality for configuring the Active Directory as the Directory Utility application. It requires "admin" privileges to the local workstation and to the Directory to make changes. A list of flags and their descriptions: -add fqdn The fully-qualified DNS name of the Domain to be used when adding the computer to the Directory (e.g., domain.ads.example.com). -alldomains enable | disable This flag determines whether the plugin allows authentication from any domain in the forest. When this is enabled, individual domains will not be visible, only "All Domains". If it is disabled, you will have the ability to select the specific domains that can authenticate to this computer. Enabled by default. -computer computerid The "computerid" to add the specified Domain -force Force the process (i.e., join the existing account or remove the binding) -ggid attribute This specifies the attribute to be used for the GID of the group. By default, a group GID is generated from the Active Directory GUID of the group. -gid attribute This specifies the attribute to be used for the GID of the user. By default, a GID is derived from the primaryGroupID of the user (typically Domain Users). -groups group1,group2,... Use the listed groups to determine who has local administrative privileges on this computer. Groups can be specified by domain to ensure security is not compromised, e.g., "domain admins@domain.ads.demo.com" -help Lists the options for calling dsconfigad -leave Leaves the current domain (preserving the computer record in the directory). -localhome enable | disable This flag determines whether the plugin forces all home directories to be local to the computer (i.e., /Users/username) (enabled by default). -localpassword password Password to use in conjunction with the specified local username. If this is not specified, you will be prompted for entry. Note that using this option has a security risk due to a small window where the password could be captured from running process list. Consider using the prompting mechanism to ensure passwords are not exposed unexpectedly. -localuser username Username of a local account that has administrative privileges to this computer -mobile enable | disable This flag determines whether the plugin will enable mobile account support for offline logon (disabled by default). This flag is a hint. If the appopriate Workgroup Management settings exist for a user, this will not override, as directory settings for the user take precendence. -mobileconfirm enable | disable This flag determines whether the plugin will warn the user when a mobile account is going to be created. This flag is a hint as discussed in -mobile -namespace forest | domain Sets the primary account username naming convention. By default it is set to "domain" naming which assumes no conflicting user accounts across all domains. If your Active Directory forest has conflicts setting this to "forest" will prefix all usernames with "DOMAIN\" to ensure unique naming between domains (e.g., "ADDOMAIN\user1"). Warning: this will change the primary name of the user for all logins. Changing this setting on an existing system will cause any existing homes to be unused on the local machine. -noggid Turn off any previously mapped attribute and generate the group GID from the Active Directory GUID. -nogid Turn off any previously mapped attribute and use the GID from the directory. -nogroups Disable use of the current groups for determining administrative privileges on this computer. -nopreferred Turn off any previously specified server and default to dynamic server discovery. -nouid Turn off any previously mapped attribute and generate the UID from the Active Directory GUID. -ou dn The LDAP DN of the container to use for adding the computer. If this is not specified, it will default to the container "CN=Computers" within the domain that was specified (e.g., "CN=Computers,DC=domain,DC=ads,DC=demo,DC=com" -packetencrypt allow | disable | require | ssl By default packet encryption is allowed but not required, but can be required or disabled (for example if debugging a problem). This ensures that the data to/from the server is encrypted and signed guaranteeing the content was not tampered with and cannot be seen by other computers on the network. -packetsign allow | disable | require By default packet signing is allowed but not required, but can be required or disabled (for example if debugging a problem). This ensures that the data to/from the server is not tampered with by another computer before received it is received. -passinterval value Set how often the computer trust account password should be changed (default 14). -password password Password to use in conjunction with the specified username. If this is not specified, you will be prompted for entry. Note that using this option has a security risk due to a small window where the password could be captured from running process list. Consider using the prompting mechanism to ensure passwords are not exposed unexpectedly. -preferred server Use the specified server for all Directory lookups and authentications. If the server is no longer available, it will fail-over to other servers. -protocol afp | smb | nfs This flag determines how a home directory is mounted on the desktop. By default SMB is used, but AFP can be used for use with Mac OS X Server or 3rd Party AFP solutions on Windows Servers (previously known as mountstyle) -restrictDDNS Restricts Dynamic DNS updates to specific interfaces (e.g., en0, en1, en2, etc.). To disable restrictions pass "" as the list. -remove Remove this computer from the current Domain -sharepoint enable | disable Enable or disable mounting of the network home as a sharepoint. -shell value Use the specified shell (e.g., "/bin/bash") if a shell attribute does not exist in the directory for the user logging into this computer. Use a shell value of "none" to disable use of a default shell, preserving values that are only specified in the directory. -show Shows the current configuration of the Active Directory -uid attribute This specifies the attribute to be used for the UID of the user. By default, a UID is generated from the Active Directory GUID. -username username Username of a Network account that has administrative privileges to add/remove this computer to/from the specified Domain -useuncpath enable | disable This flag determines whether the plugin uses the UNC specified in the Active Directory when mounting the network home. If this is disabled, the plugin will look for Apple schema extensions to mount the home directory. -xml Output in XML rather than plain text. Valid only with -show.
dsconfigad – retrieves/changes configuration for Active Directory.
dsconfigad -help dsconfigad -show [-xml] dsconfigad -add fqdn -username username [-password password] [-computer computerid] [-ou dn] [-preferred server] [-force] [-localuser username] [-localpassword password] [-packetencrypt allow | disable | require | ssl] dsconfigad -leave [-localuser username] [-localpassword password] dsconfigad -remove -username username [-password password] [-localuser username] [-localpassword password] dsconfigad [-localuser username] [-localpassword password] [-alldomains enable | disable] [-localhome enable | disable] [-gid attribute | -nogid] [-ggid attribute | -noggid] [-groups "group1,group2,..." | -nogroups] [-mobile enable | disable] [-mobileconfirm enable | disable] [-namespace forest | domain] [-packetencrypt allow | disable | require | ssl] [-packetsign allow | disable | require] [-passinterval value] [-preferred server | -nopreferred] [-protocol afp | smb | nfs] [-restrictDDNS interface,interface,...] [-sharepoint enable | disable] [-shell value] [-uid attribute | -nouid] [-useuncpath enable | disable]
null
Adding a computer to a Directory: dsconfigad -add domain.ads.example.com -computer ThisComputer -username "administrator" -ou "CN=Computers,OU=Engineering,DC=ads,DC=example,DC=com" Giving a set of groups administrative access to the local computer: dsconfigad -groups "DOMAIN\domain admins,FOREST\enterprise admins,DOMAIN\desktop techs" SEE ALSO opendirectoryd(8), odutil(1) Darwin August 28 2010 Darwin
htdbm
null
htdbm - Manipulate DBM password databases
htdbm [ -TDBTYPE ] [ -i ] [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -t ] [ -v ] filename username htdbm -b [ -TDBTYPE ] [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -t ] [ -v ] filename username password htdbm -n [ -i ] [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -t ] [ -v ] username htdbm -nb [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -t ] [ -v ] username password htdbm -v [ -TDBTYPE ] [ -i ] [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -t ] [ -v ] filename username htdbm -vb [ -TDBTYPE ] [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -t ] [ -v ] filename username password htdbm -x [ -TDBTYPE ] filename username htdbm -l [ -TDBTYPE ] SUMMARY htdbm is used to manipulate the DBM format files used to store usernames and password for basic authentication of HTTP users via mod_authn_dbm. See the dbmmanage documentation for more information about these DBM files.
-b Use batch mode; i.e., get the password from the command line rather than prompting for it. This option should be used with extreme care, since the password is clearly visible on the command line. For script use see the -i option. -i Read the password from stdin without verification (for script usage). -c Create the passwdfile. If passwdfile already exists, it is rewritten and truncated. This option cannot be combined with the -n option. -n Display the results on standard output rather than updating a database. This option changes the syntax of the command line, since the passwdfile argument (usually the first one) is omitted. It cannot be combined with the -c option. -m Use MD5 encryption for passwords. On Windows and Netware, this is the default. -B Use bcrypt encryption for passwords. This is currently considered to be very secure. -C This flag is only allowed in combination with -B (bcrypt encryption). It sets the computing time used for the bcrypt algorithm (higher is more secure but slower, default: 5, valid: 4 to 31). -d Use crypt() encryption for passwords. The default on all platforms but Windows and Netware. Though possibly supported by htdbm on all platforms, it is not supported by the httpd server on Windows and Netware. This algorithm is insecure by today's standards. -s Use SHA encryption for passwords. Facilitates migration from/to Netscape servers using the LDAP Directory Interchange Format (ldif). This algorithm is insecure by today's standards. -p Use plaintext passwords. Though htdbm will support creation on all platforms, the httpd daemon will only accept plain text passwords on Windows and Netware. -l Print each of the usernames and comments from the database on stdout. -v Verify the username and password. The program will print a message indicating whether the supplied password is valid. If the password is invalid, the program exits with error code 3. -x Delete user. If the username exists in the specified DBM file, it will be deleted. -t Interpret the final parameter as a comment. When this option is specified, an additional string can be appended to the command line; this string will be stored in the "Comment" field of the database, associated with the specified username. filename The filename of the DBM format file. Usually without the extension .db, .pag, or .dir. If -c is given, the DBM file is created if it does not already exist, or updated if it does exist. username The username to create or update in passwdfile. If username does not exist in this file, an entry is added. If it does exist, the password is changed. password The plaintext password to be encrypted and stored in the DBM file. Used only with the -b flag. -TDBTYPE Type of DBM file (SDBM, GDBM, DB, or "default"). BUGS One should be aware that there are a number of different DBM file formats in existence, and with all likelihood, libraries for more than one format may exist on your system. The three primary examples are SDBM, NDBM, GNU GDBM, and Berkeley/Sleepycat DB 2/3/4. Unfortunately, all these libraries use different file formats, and you must make sure that the file format used by filename is the same format that htdbm expects to see. htdbm currently has no way of determining what type of DBM file it is looking at. If used against the wrong format, will simply return nothing, or may create a different DBM file with a different name, or at worst, it may corrupt the DBM file if you were attempting to write to it. One can usually use the file program supplied with most Unix systems to see what format a DBM file is in. EXIT STATUS htdbm returns a zero status ("true") if the username and password have been successfully added or updated in the DBM File. htdbm returns 1 if it encounters some problem accessing files, 2 if there was a syntax problem with the command line, 3 if the password was entered interactively and the verification entry didn't match, 4 if its operation was interrupted, 5 if a value is too long (username, filename, password, or final computed record), 6 if the username contains illegal characters (see the Restrictions section), and 7 if the file is not a valid DBM password file.
htdbm /usr/local/etc/apache/.htdbm-users jsmith Adds or modifies the password for user jsmith. The user is prompted for the password. If executed on a Windows system, the password will be encrypted using the modified Apache MD5 algorithm; otherwise, the system's crypt() routine will be used. If the file does not exist, htdbm will do nothing except return an error. htdbm -c /home/doe/public_html/.htdbm jane Creates a new file and stores a record in it for user jane. The user is prompted for the password. If the file exists and cannot be read, or cannot be written, it is not altered and htdbm will display a message and return an error status. htdbm -mb /usr/web/.htdbm-all jones Pwd4Steve Encrypts the password from the command line (Pwd4Steve) using the MD5 algorithm, and stores it in the specified file. SECURITY CONSIDERATIONS Web password files such as those managed by htdbm should not be within the Web server's URI space -- that is, they should not be fetchable with a browser. The use of the -b option is discouraged, since when it is used the unencrypted password appears on the command line. When using the crypt() algorithm, note that only the first 8 characters of the password are used to form the password. If the supplied password is longer, the extra characters will be silently discarded. The SHA encryption format does not use salting: for a given password, there is only one encrypted representation. The crypt() and MD5 formats permute the representation by prepending a random salt string, to make dictionary attacks against the passwords more difficult. The SHA and crypt() formats are insecure by today's standards. RESTRICTIONS On the Windows platform, passwords encrypted with htdbm are limited to no more than 255 characters in length. Longer passwords will be truncated to 255 characters. The MD5 algorithm used by htdbm is specific to the Apache software; passwords encrypted using it will not be usable with other Web servers. Usernames are limited to 255 bytes and may not include the character :. Apache HTTP Server 2018-07-06 HTDBM(1)
netbiosd
netbiosd is responsible for interacting with NetBIOS networks. netbiosd registers and defends one or more NetBIOS name, depending on the set of configured services. It also browses and scavenges names from the NetBIOS network, making them available to the system through mDNSResponder.
netbiosd – NetBIOS protocol daemon
netbiosd [options]
-debug The service will log extensive debug information and may perform extra diagnostic checks. This option is typically only useful for debugging. -dump-packets Pretty-print all sent and received NetBIOS packets to the output log. This option is typically only useful for debugging. -help Prints a usage message and exits. -max-refresh Maximum time (in seconds) between searches to refresh the workgroup list. -min-refresh Minimum time (in seconds) between searches to refresh the workgroup list. -stdout Causes netbiosd to print log messages to standard output instead of the system log. FILES /Library/Preferences/SystemConfiguration/com.apple.smb.server.plist The primary configuration for the SMB stack. This file is updated by various system services and should not be edited by hand. /System/Library/LaunchDaemons/com.apple.netbiosd.plist The netbiosd service's property list file for launchd(8). SIGNALS SIGHUP This signal causes netbiosd to reconfigure. It will first unregister any NetBIOS names it has registered. Then it will determine its new set of NetBIOS names and register those. SIGUSR1 This signal causes netbiosd to toggle debug logging. SEE ALSO launchd(8), mDNSResponder(8) STANDARDS The TCP/UDP embodiment of the NetBIOS protocol is documented in RFC 1002 Protocol standard for a NetBIOS service on a TCP/UDP: Detailed Specifications, 1987 RFC 1001 Protocol standard for a NetBIOS service on a TCP/UDP: Concepts and Methods, 1987 The NetBIOS browsing protocol is documented as part of the Microsoft Work Group Server Protocol Program (WSPP) technical documentation set, specifically MS-BRWS Common Internet File System (CIFS) Browser Protocol Specification HISTORY The netbiosd utility first appeared in Mac OS 10.7. Darwin Wed Nov 4 20:34:39 PST 2009 Darwin
null
postlock
The postlock(1) command locks file for exclusive access, and executes command. The locking method is compatible with the Postfix UNIX-style local delivery agent. Options: -c config_dir Read the main.cf configuration file in the named directory instead of the default configuration directory. -l lock_style Override the locking method specified via the mailbox_delivery_lock configuration parameter (see below). -v Enable verbose logging for debugging purposes. Multiple -v options make the software increasingly verbose. Arguments: file A mailbox file. The user should have read/write permission. command... The command to execute while file is locked for exclusive access. The command is executed directly, i.e. without interpretation by a shell command interpreter. DIAGNOSTICS The result status is 75 (EX_TEMPFAIL) when postlock(1) could not perform the requested operation. Otherwise, the exit status is the exit status from the command. BUGS With remote file systems, the ability to acquire a lock does not necessarily eliminate access conflicts. Avoid file access by processes running on different machines. ENVIRONMENT MAIL_CONFIG Directory with Postfix configuration files. MAIL_VERBOSE Enable verbose logging for debugging purposes. CONFIGURATION PARAMETERS The following main.cf parameters are especially relevant to this program. The text below provides only a parameter summary. See postconf(5) for more details including examples. LOCKING CONTROLS deliver_lock_attempts (20) The maximal number of attempts to acquire an exclusive lock on a mailbox file or bounce(8) logfile. deliver_lock_delay (1s) The time between attempts to acquire an exclusive lock on a mailbox file or bounce(8) logfile. stale_lock_time (500s) The time after which a stale exclusive mailbox lockfile is removed. mailbox_delivery_lock (see 'postconf -d' output) How to lock a UNIX-style local(8) mailbox before attempting delivery. RESOURCE AND RATE CONTROLS fork_attempts (5) The maximal number of attempts to fork() a child process. fork_delay (1s) The delay between attempts to fork() a child process. MISCELLANEOUS CONTROLS config_directory (see 'postconf -d' output) The default location of the Postfix main.cf and master.cf configuration files. import_environment (see 'postconf -d' output) The list of environment parameters that a privileged Postfix process will import from a non-Postfix parent process, or name=value environment overrides. SEE ALSO postconf(5), configuration parameters LICENSE The Secure Mailer license must be distributed with this software. AUTHOR(S) Wietse Venema IBM T.J. Watson Research P.O. Box 704 Yorktown Heights, NY 10598, USA Wietse Venema Google, Inc. 111 8th Avenue New York, NY 10011, USA POSTLOCK(1)
postlock - lock mail folder and execute command
postlock [-c config_dir] [-l lock_style] [-v] file command...
null
null
systemsoundserverd
systemsoundserverd is a daemon used for Core Audio related purposes. systemsoundserverd was introduced with OSX version 10.11. Darwin Mon June 8 2015 Darwin
systemsoundserverd
systemsoundserverd
null
null
dseditgroup
dseditgroup allows manipulation of a single named group record on either the default local node or the specified DirectoryService node. For the "read" operation the authentication search policy (/Search node) is consulted. Default behaviour is presented below after a discussion of each operation and the possible parameters. Options and their descriptions: -o operation If "read" then the parameters of the specified groupname will be displayed. This is the default option. The authentication search policy (/Search node) will be used. If "create" then create a group with the specified groupname on either the default local node or the specified DirectoryService node. If "delete" then delete a group with the specified groupname on either the default local node or the specified DirectoryService node. If "edit" then edit a group with the specified groupname on either the default local node or the specified DirectoryService node. If "checkmember" then check if the user specified with -m or current logged in user is a member of the specified groupname. The authentication search policy (/Search node) is used to find the member. The specified node (defaults to the authentication search policy) is used to find the group. If the specified node is not on the authentication search policy the behaviour is undefined. -p You will be prompted for a password to use in conjunction with the specified username. -q This disables interactive verification of replace or delete operations. -v This enables the logging of the DirectoryService API calls and their return codes. Parameters and their descriptions: -m member The username of the account to verify group membership when using -o checkmember -n nodename Directory Service node name such as /LDAPv3/ldap.company.com and whose default value is the local node. "." can also be used to specify the local node. -u username Username of a user that has administrative privileges on this computer. -P password Password to use in conjunction with the specified username. If this is not specified, you will be prompted for a password. -a recordname The name of the record to be added to the group specified by groupname. This name is related to the first record found on the authentication search policy when a search is made with this recordname and the given recordtype. -d recordname The name of the record to be deleted from the group specified by groupname. This name is related to the first record found on the authentication search policy when a search is made with this recordname and the given recordtype. -t recordtype The type of the record to be added to or deleted from the group specified by groupname. Valid values are user, computer, group, or computergroup. -T grouptype The type of the group record to be created or modified as specified by groupname. Valid values are group or computergroup. -L If used with computergroup will also maintain the computerlist if it exists or create it if a computergroup is created. -i gid This is a group id. This will be automatically created if not specified for a create. -g guid This is a text representation of an 128 bit id. This will be automatically created if not specified for a create. -r realname This is a simple text string. -k keyword This is a simple text string. -c comment This is a simple text string. -s timetolive The number of seconds that this record is deemed valid as a cached value. There will be no automatically created default value if not specified for a create. DEFAULT BEHAVIOUR dseditgroup mygroup This simple version of the command will default to: dseditgroup -o read -n . -u $USER mygroup The output will be the parameters of the "mygroup" group record if the shell user has read access to the local node's group record of name "mygroup".
dseditgroup – group record manipulation tool.
dseditgroup [options] [parameters] groupname options: -o operation perform (read, create, delete, edit, checkmember) operation with given groupname -p prompt for authentication password -q disables interactive verification -v verbose logging to stdout parameters: -m member username to use for checkmember option -n nodename directory node location of group record -u username authenticate with admin username -P password authentication password -a recordname name of the record to add -d recordname name of the record to delete -t recordtype type of the record to add or delete -T grouptype type of group to create or modify -L maintain ComputerLists in parallel with ComputerGroups -i gid gid to add/replace -g guid GUID to add/replace -S sid SID to add/replace -r realname realname to add/replace -k keyword keyword to add -c comment comment to add/replace -s timetolive seconds to live to add/replace -f n | l change the group's format - 'n' for the new group format and 'l' for the legacy group format
null
dseditgroup extragroup dseditgroup -o read extragroup The attributes of the group extragroup from the local node are displayed. dseditgroup -o create -n /LDAPv3/ldap.company.com -u myusername -P mypassword -r "Extra Group" -c "a nice comment" -s 3600 -k "some keyword" extragroup The group extragroup is created from the node /LDAPv3/ldap.company.com with the realname, comment, timetolive (instead of default of 14400 = 4 hours), and keyword atttribute values given above if the user myusername has supplied a correct password and has write access. dseditgroup -o delete -n /LDAPv3/ldap.company.com -u myusername -P mypassword extragroup The group extragroup is deleted from the node /LDAPv3/ldap.company.com if the user myusername has supplied a correct password and has write access. dseditgroup -o edit -n /LDAPv3/ldap.company.com -u myusername -p -a username -t user extragroup The group extragroup from the node /LDAPv3/ldap.company.com will have the username added if the username is in a user record on the search policy and if the correct password is presented interactively for the user myusername which also need to have write access. dseditgroup -o edit -n /LDAPv3/ldap.company.com -u myusername -P -a mysubgroup -t group extragroup The group extragroup from the node /LDAPv3/ldap.company.com will have the mysubgroup added if the mysubgroup is in a group record on the search policy and if the user myusername has supplied a correct password and has write access. dseditgroup -o edit -n /LDAPv3/ldap.company.com -u myusername -p -d username -t user extragroup The group extragroup from the node /LDAPv3/ldap.company.com will have the username deleted if the correct password is presented interactively for the user myusername which also need to have write access. dseditgroup -o checkmember extragroup Will write out a message specifying if the current user is a member of extragroup on the authentication search policy. dseditgroup -o checkmember -n _. extragroup Will write out a message specifying if the current user is a member of extragroup on the local node. dseditgroup -n /LDAPv3/ldap.company.com -o checkmember -m user extragroup Will write out a message specifying if user (found in /Search) is a member of extragroup on the specified node /LDAPv3/ldap.company.com. The specified node /LDAPv3/ldap.company.com needs to be on the authentication search policy for a valid answer. Mac OS X March 01 2004 Mac OS X