7.7. Built-in Commands
Examples to be entered as a command
line are shown with the $ prompt.
Otherwise, examples should be treated as code fragments that might be
included in a shell script. For convenience, some of the reserved
words used by multiline commands also are included.
# Ignore all text that follows on the same line. # is used in shell
scripts as the comment character and is not really a command.
#!shell Used as the first line of a script to invoke the named
shell (with optional arguments) or other
program. For example: #!/bin/bash
: Null command. Returns an exit status of 0. Sometimes used as the
first character in a file to denote a bash script. Shell variables can be placed
after the : to expand them to their
values.
Example
To check whether someone is logged in:
if who | grep -w $1 > /dev/null
then : # do nothing
# if pattern is found
else echo "User $1 is not logged in"
fi
. file [arguments] Same as source.
alias [-p] [name[=cmd]] Assign a shorthand name as a synonym for
cmd. If =cmd is omitted, print
the alias for name; if name
is also omitted or if -p is
specified, print all aliases. See also unalias.
bg [jobIDs] Put current job or jobIDs in the background. See
Section 7.7.
bind [options]
bind [options] key:function Print or set the bindings that allow keys to invoke functions such as
cursor movement and line editing. Typical syntax choices for
keys are "\C-t" for Ctrl-T and
"\M-t" or
"\et" for Esc-T (quoting is
needed to escape the sequences from the shell). Function names can be
seen though the -l option.
Options
- -f filename
-
Consult filename for bindings, which should be
in the same format as on the bind
command line.
- -l
-
Print all Readline functions, which are functions that can be bound
to keys.
- -m keymap
-
Specify a keymap for this and further bindings. Possible keymaps are
emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move,
vi-command, and vi-insert.
- -p
-
Display all functions and the keys that invoke them, in the format by
which keys can be set.
- -q function
-
Display the key bindings that invoke function.
- -r key
-
Remove the binding attached to key so that it no
longer works.
- -s
-
Display all macros and the keys that invoke them, in the format by
which keys can be set.
- -u function
-
Remove all the bindings attached to function so
that no keys will invoke it.
- -v
-
Display all Readline variables (settings that affect history and line
editing) and their current settings, in the format by which variables
can be set.
- -x key:command
-
Bind key to a shell command.
- -P
-
Display all bound keys and the functions they invoke.
- -S
-
Display all macros and the keys that invoke them.
- -V
-
Display all Readline variables (settings that affect history and line
editing) and their current settings.
Example
Bind Ctrl-T to copy-forward-word,
the function that copies the part of the word following the cursor so
it can be repasted:
$ bind "\C-t":copy-forward-word
break [n] Exit from the innermost (most deeply nested) for, while,
or until loop, or from the
nth innermost level of the loop. Also exits from
a select list.
builtin command [arguments] Execute command, which must be a shell built-in.
Useful for invoking built-ins within scripts of the same name.
case string
in
regex)
commands
;;
...
esac If string matches regular expression
regex, perform the following
commands. Proceed down the list of regular
expressions until one is found. (To catch all remaining strings, use
* as regex at the end.)
cd [options] [dir] With no arguments, change to user's home directory.
Otherwise, change working directory to dir. If
dir is a relative pathname but is not in the
current directory, search the CDPATH
variable.
Options
- -L
-
Force symbolic links to be followed.
- -P
-
Don't follow symbolic links, but use the physical
directory structure.
command [options] command [arguments] Execute command, but do not perform function
lookup (i.e., refuse to run any command that is neither in PATH nor a built-in). Set exit status to that
returned by command unless
command cannot be found, in which case exit with
a status of 127.
Options
- -p
-
Search default path, ignoring the PATH variable's value.
- -v
-
Print the command or filename that invokes the command.
- -V
-
Like -v, but also print a
description of the command.
- --
-
Treat everything that follows as an argument, not an option.
compgen [options] [word] Generate possible completion matches for word
for use with bash's
programmable completion feature, and write the matches to standard
output. If word is not specified, display all
completions. See complete for the
options; any except -p and -r can be used with compgen.
complete [options] names Specify completions for arguments to each name,
for use with bash's
programmable completion feature. With no options or with -p, print all completion specifications such
that they can be reused as input.
Options
- -o comp-option
-
Specify other aspects of the completion
specification's behavior besides generating a
completion. Possible values of comp-option are:
- default
-
Use readline's
default filename completion if the completion specification generates
no matches.
- dirnames
-
Use directory name completion if the completion specification
generates no matches.
- filenames
-
Tell readline that the completion
specification generates filenames so that it can process them
accordingly. For use with shell functions.
- nospace
-
Tell readline not to append a space
to completions at the end of the line. This is the default.
- -p
-
Print all completion specifications.
- -r
-
Remove completion specification for each name,
or all specifications if no names are given.
- -A action
-
Specify an action to generate a list of completions. Possible actions
are:
- alias
-
Alias names. May be specified as -a.
- arrayvar
-
Array variable names.
- binding
-
readline key binding names.
- builtin
-
Shell built-in command names. May be specified as -b.
- command
-
Command names. May be specified as -c.
- directory
-
Directory names. May be specified as -d.
- disabled
-
Disabled shell built-in command names.
- enabled
-
Enabled shell built-in command names.
- export
-
Exported shell variable names. May be specified as -e.
- file
-
Filenames. May be specified as -f.
- function
-
Shell function names.
- group
-
Group names. May be specified as -g.
- helptopic
-
Help topic names accepted by the help built-in command.
- hostname
-
Hostnames, from the file specified by HOSTFILE.
- job
-
Job names, if job control is active. May be specified as -j.
- keyword
-
Shell reserved words. May be specified as -k.
- running
-
Names of running jobs, if job control is active.
- service
-
Service names. May be specified as -s.
- setopt
-
Valid arguments for the -o option to
the set built-in command.
- shopt
-
Valid shell option names for the shopt built-in command.
- signal
-
Signal names.
- stopped
-
Names of stopped jobs, if job control is active.
- user
-
Usernames. May be specified as -u.
- variable
-
Shell variable names. May be specified as -v.
- -C command
-
Execute the specified command in a subshell and use the output as
possible completions.
- -F function
-
Execute the specified function in the current shell and take the
possible completions from the COMPREPLY array variable.
- -G globpat
-
Expand the specified filename expansion pattern to generate the
possible completions.
- -P prefix
-
Prepend the specified prefix to each possible completion after all
other options have been applied.
- -S suffix
-
Append the specified suffix to each possible completion after all
other options have been applied.
- -W list
-
Split the specified word list and expand each resulting word. The
possible completions are the members of the resulting list that match
the word being completed.
- -X pattern
-
Use the specified pattern as a filter and apply it to the list of
possible completions generated by all the other options except
-P and -S, removing all matches from the list. A
leading ! in the pattern negates it so that any
completion that does not match the pattern is
removed.
continue [n] Skip remaining commands in a for,
while, or until loop, resuming with the next iteration
of the loop (or skipping n loops).
declare [options] [name[=value]]
typeset [options] [name[=value]] Print or set variables. Options prefaced by + instead of - are
inverted in meaning.
Options
- -a
-
Treat the following names as array variables.
- -f
-
Treat the following names as functions.
- -i
-
Expect variable to be an integer, and evaluate its assigned value.
- -p
-
Print names and settings of all shell variables and functions; take
no other action.
- -r
-
Do not allow variables to be reset later.
- -x
-
Mark variables for subsequent export.
- -F
-
Print names of all shell functions; take no other action.
dirs [options] Print directories currently remembered for pushd/popd
operations.
Options
- +entry
-
Print entryth entry from start of list (list
starts at 0).
- -entry
-
Print entryth entry from end of list.
- -c
-
Clear the directory stack.
- -l
-
Long listing.
- -p
-
Print the directory stack, one entry per line.
- -v
-
Like -p, but prefix each entry with
its position in the stack.
disown [options] [jobIDs] Let job run, but disassociate it from the shell. By default, does not
even list the job as an active job; commands like jobs and fg
will no longer recognize it. When -h
is specified, the job is recognized but is kept from being killed
when the shell dies.
Options
- -a
-
Act on all jobs.
- -h
-
Do not pass a SIGHUP signal received by the shell on to the job.
echo [options] [strings] Write each string to standard output, separated
by spaces and terminated by a newline. If no strings are supplied,
echo a newline. (See also echo in
Chapter 3.)
Options
- -e
-
Enable interpretation of escape characters:
- \a
-
Audible alert
- \b
-
Backspace
- \c
-
Suppress the terminating newline (same as -n)
- \e
-
Escape character
- \f
-
Form feed
- \n
-
Newline
- \r
-
Carriage return
- \t
-
Horizontal tab
- \v
-
Vertical tab
- \\
-
Backslash
- \nnn
-
The character in the ASCII set corresponding to the octal number
nnn.
- \xnn
-
The character in the ASCII set corresponding to the hexadecimal
number nn (1 or 2 hex digits).
- -n
-
Do not append a newline to the output.
- -E
-
Disable interpretation of escape characters.
enable [options] [built-in ...] Enable (or when -n is specified,
disable) built-in shell commands. Without
built-in argument or with -p option, print enabled built-ins. With
-a, print the status of all
built-ins. You can disable shell commands in order to define your own
functions with the same names.
Options
- -a
-
Display all built-ins, both enabled and disabled.
- -d
-
Delete a built-in command that was previously loaded with -f.
- -f filename
-
On systems that support dynamic loading, load the new built-in
command built-in from the shared object
filename.
- -n
-
Disable each specified built-in.
- -p
-
Display enabled built-ins.
- -s
-
Restrict display to special built-ins defined by the POSIX standard.
eval [command args...] Perform command, passing
args.
exec [options] [command] Execute command in place of the current shell
(instead of creating a new process). exec is also useful for opening, closing, or
copying file descriptors.
Options
- -a name
-
Tell command that it was invoked as
name.
- -c
-
Remove all environment variables from the process when the new
command runs.
- -l
-
Treat the new process as if the user were logging in.
Examples
trap 'exec 2>&-' 0 Close standard error when shell script
exits (signal 0)
$ exec /bin/tcsh Replace current shell with extended C shell
$ exec < infile Reassign standard input to infile
exit [n] Exit a shell script with status n (e.g.,
exit 1). n can
be zero (success) or nonzero (failure). If n is
not given, exit status will be that of the most recent command.
exit can be issued at the command
line to close a window (log out).
Example
if [ $# -eq 0 ]; then
echo "Usage: $0 [-c] [-d] file(s)"
exit 1 # Error status
fi
export [options] [variables]
export [options] [name=[value]]... Pass (export) the value of one or more shell
variables, giving global meaning to the
variables (which are local by default). For example, a variable
defined in one shell script must be exported if its value will be
used in other programs called by the script. When a shell variable
has been exported, you can access its value by referencing the
equivalent environment variable. If no variables
are given, export lists the
variables exported by the current shell. If name
and value are specified, export assigns value to a
variable name and exports it.
Options
- --
-
Treat all subsequent strings as arguments, not options.
- -f
-
Expect variables to be functions.
- -n
-
Unexport variable.
- -p
-
List variables exported by current shell.
fc [options] [first] [last]
fc -s [oldpattern=newpattern] [command] Display or edit commands in the history list. (Use only one of
-l or -e.) fc
provides capabilities similar to the C shell's
history and ! syntax. first and
last are numbers or strings specifying the range
of commands to display or edit. If last is
omitted, fc applies to a single
command (specified by first). If both
first and last are omitted,
fc edits the previous command or
lists the last 16. A negative number is treated as an offset from the
current command. The second form of fc takes a history
command, replaces old
string with new string, and executes the
modified command. If no strings are specified,
command is reexecuted. If no
command is given either, the previous command is
reexecuted. command is a number or string like
first. See earlier examples under Section 7.5.
Options
- -e [editor]
-
Invoke editor to edit the specified history
commands. The default editor is set by the shell
variable FCEDIT. If FCEDIT is not set, the value of EDITOR is used, or vi if neither is set.
- -l [first last]
-
List the specified command or range of commands, or list the last 16.
- -n
-
Suppress command numbering from the -l listing.
- -r
-
Reverse the order of the -l listing.
- -s oldpattern=newpattern
-
Edit command(s), replacing all occurrences of the specified old
pattern with the new pattern. Then reexecute.
fg [jobIDs] Bring current job or jobIDs to the foreground.
See Section 7.6.
for x [in list]
do
commands
done Assign each word in list to
x in turn and execute commands. If
list is omitted, $@ (positional parameters) is assumed.
Examples
Paginate all files in the current directory and save each result:
for file in *
do
pr $file > $file.tmp
done
Search chapters for a list of words (like fgrep
-f):
for item in `cat program_list`
do
echo "Checking chapters for"
echo "references to program $item..."
grep -c "$item.[co]" chap*
done
function command{ ...} Define a function. Refer to arguments the same way as positional
parameters in a shell script ($1,
etc.) and terminate with }.
getopts string name [args] Process command-line arguments (or args, if
specified) and check for legal options. getopts is used in shell script loops and is
intended to ensure standard syntax for command-line options.
string contains the option letters to be
recognized by getopts when running
the shell script. Valid options are processed in turn and stored in
the shell variable name. If an option letter is
followed by a colon, the option must be followed by one or more
arguments.
hash [options] [commands] Search for commands and remember the directory
in which each command resides. Hashing causes the shell to remember
the association between a name and the absolute pathname of an
executable, so that future executions don't require
a search of PATH. With no arguments
or only -l, hash lists the current hashed commands. The
display shows hits (the number of times the
command is called by the shell) and command (the
full pathname).
Options
- -d
-
Forget the remembered location of each specified command.
- -l
-
Display the output in a format that can be reused as input.
- -p filename
-
Assume filename is the full path to the command
and don't do a path search.
- -r
-
Forget the locations of all remembered commands.
- -t
-
Print the full pathname for each command. With more than one command,
print the command before each full path.
help [-s] [string] Print help text on all built-in commands or those matching
string. With -s, display only brief syntax; otherwise
display summary paragraph also.
history [options]
history [lines] Print a numbered command history, denoting modified commands with *.
Include commands from previous sessions. You may specify how many
lines of history to print.
Options
- -a [file]
-
bash maintains a file called
.bash_history in the user's
home directory, a record of previous sessions'
commands. Ask bash to append the
current session's commands to
.bash_history or to file.
- -c
-
Clear history list: remove all previously entered commands from the
list remembered by the shell.
- -d offset
-
Delete the history entry at the specified offset from the beginning
of the history list.
- -n [file]
-
Append to the history list those lines in
.bash_history or in file
that have not yet been included.
- -p args
-
Perform history substitution on the specified arguments and display
the result on standard output. The results are not stored in the
history list. Each argument must be quoted to disable normal history
expansion.
- -r [file]
-
Use .bash_history or file
as the history list, instead of using the working history list.
- -s args
-
Remove the last command in the history list and then add the
specified arguments to the list as a single entry (but
don't execute the entry).
- -w [file]
-
Overwrite .bash_history or
file with the working history list.
if test-cmds Begin a conditional statement. The possible formats, shown here side
by side, are: if test-cmds if test-cmds if test-cmds
then then then
cmds1 cmds1 cmds1
fi else elif test-cmds
cmds2 then
fi cmds2
...
else
cmdsn
fi
Usually, the initial if and any
elif lines execute one test or [ ]
command (although any series of commands is permitted). When
if succeeds (that is, the last of
its test-cmds returns 0),
cmds1 are performed; otherwise, each succeeding
elif or else line is tried.
jobs [options] [jobIDs] List all running or stopped jobs, or those specified by
jobIDs. For example, you can check whether a
long compilation or text format is still running. Also useful before
logging out. See also Section 7.6 earlier in this chapter.
Options
- -l
-
List job IDs and process group IDs.
- -n
-
List only jobs whose status has changed since last notification.
- -p
-
List process group IDs only.
- -r
-
List active, running jobs only.
- -s
-
List stopped jobs only.
- -x command [arguments]
-
Execute command. If jobIDs
are specified, replace them with command.
kill [options] IDs Terminate each specified process ID or job ID. You must own the
process or be a privileged user. See also Section 7.6 and the killall command in Chapter 3.
Options
- -signal
-
The signal number (from ps -f) or
name (from kill -l). The default is
TERM (signal number 15). With a signal number of 9, the kill is
unconditional. If nothing else works to kill a process, kill -9 almost always kills it, but does not
allow the process any time to clean up.
- --
-
Consider all subsequent strings to be arguments, not options.
- -l [arg]
-
With no argument, list the signal names. (Used by itself.) The
argument can be a signal name or a number representing either the
signal number or the exit status of a process terminated by a signal.
If it is a name, the correspoding number is returned; otherwise, the
corresponding name is returned.
- -n signum
-
Specify the signal number to send.
- -s signal
-
Specify signal. May be a signal name or number.
let expressions Perform arithmetic as specified by one or more integer
expressions. expressions
consist of numbers, operators, and shell variables (which
don't need a preceding $), and must be quoted if they contain spaces
or other special characters. For more information and examples, see
Section 7.4 earlier in this chapter.
See also expr in Chapter 3.
Examples
Both of the following examples add 1 to variable i:
let i=i+1
let "i = i + 1"
local [options] [variable[=value]] [variable2[=value]] ... Without arguments, print all local variables. Otherwise, create (and
set, if specified) one or more local variables. See the declare built-in command for options. Must be
used within a function.
logout [status] Exit the shell, returning status as exit status
to invoking program if specified. Can be used only in a login shell.
Otherwise, use exit.
popd [options] Manipulate the directory stack. By default, remove the top directory
and cd to it. If successful, run
dirs to show the new directory
stack.
Options
- +n
-
Remove the nth directory in the stack, counting
from 0.
- -n
-
Remove the nth entry from the bottom of the
stack, counting from 0.
- -n
-
Don't do a cd when
removing directories from the stack.
printf string [arguments] Format the arguments according to
string. Works like the C library printf function. Standard printf percent-sign formats are recognized in
string, such as %i for integer. Escape sequences such as
\n can be included in
string and are automatically recognized; if you
want to include them in arguments, specify a
string of %b.
You can escape characters in arguments to output
a string suitable for input to other commands by specifying a
string of %q.
Examples
printf "Previous command: %i\n" "$(($HISTCMD-1))"
Previous command: 534
$ echo $PAGER
less -E
$ printf "%q\n" "\t$PAGER"
\\tless\ -E
The last command would probably be used to record a setting in a file
where it could be read and assigned by another shell script.
pushd [directory]
pushd [options] By default, switch top two directories on stack. If specified, add a
new directory to the top of the stack instead, and cd to it.
Options
- +n
-
Rotate the stack to place the nth (counting from
0) directory at the top.
- -n
-
Rotate the stack to place the nth directory from
the bottom of the stack at the top.
- -n
-
Don't do a cd when
adding directories to the stack.
pwd [option] Display the current working directory's absolute
pathname. By default, any symbolic directories used when reaching the
current directory are displayed, but with -P, or if the -o option to the set built-in is set, the real names are
displayed instead.
Options
- -L
-
Include any symbolic links in the pathname.
- -P
-
Do not include symbolic links in the pathname.
read [options] [variable1 variable2 ...] Read one line of standard input and assign each word (as defined by
IFS) to the corresponding variable, with all
leftover words assigned to the last variable. If only one variable is
specified, the entire line will be assigned to that variable. The
return status is 0 unless EOF is reached, a distinction that is
useful for running loops over input files. If no variable names are
provided, read the entire string into the environment variable
REPLY.
Options
- -a var
-
Read each word into an element of var, which is
treated as an array variable.
- -d char
-
Stop reading the line at char instead of at the
newline.
- -e
-
Line editing and command history are enabled during input.
- -n num
-
Read only num characters from the line.
- -p string
-
Display the prompt string to the user before
reading each line, if input is interactive.
- -r
-
Raw mode; ignore \ as a line continuation character.
- -s
-
Do not echo the characters entered by the user (useful for reading a
password).
- -t seconds
-
Time out and return without setting any variables if input is
interactive and no input has been entered for
seconds seconds.
- -u fd
-
Read input from specified file descriptor fd
instead of standard input.
Examples
read first last address
Sarah Caldwell 123 Main Street
$ echo "$last, $first\n$address"
Caldwell, Sarah
123 Main Street
The following commands, which read a password into the variable
$user_pw and then display its value,
use recently added options that are not in all versions of bash in current use.
$ read -sp "Enter password (will not appear on screen)" user_pw
Enter password (will not appear on screen)
$ echo $user_pw
You weren't supposed to know!
The following script reads input from the system's
password file, which uses colons to delimit fields (making it a
popular subject for examples of input parsing).
IFS=:
cat /etc/passwd |
while
read account pw user group gecos home shell
do
echo "Account name $account has user info: $gecos"
done
readonly [options] [variable1 variable2...] Prevent the specified shell variables from being assigned new values.
Variables can be accessed (read) but not overwritten.
Options
- -a
-
Treat the following names as array variables.
- -f
-
Treat the following names as functions and set them read-only so that
they cannot be changed.
- -p
-
Display all read-only variables (default).
return [n] Normally used inside a function to exit the function with status
n or with the exit status of the previously
executed command. Can be used outside a function during execution of
a script by the . command to cause the shell to stop execution of the
script. The return status is n or the
script's exit status.
select name [ in wordlist ; ]
do
commands
done Choose a value for name by displaying the words
in wordlist to the user and prompting for a
choice. Store user input in the variable REPLY and the chosen word in
name. Then execute commands
repeatedly until they execute a break or return. The default prompt can be changed by
setting the PS3 shell variable.
set [options] [arg1 arg2 ...] With no arguments, set prints the
values of all variables known to the current shell. Options can be
enabled (-option) or disabled
(+option). Options can also be set when the
shell is invoked, via bash.
Arguments are assigned in order to $1, $2, and
so on.
Options
- -
-
Turn off -v and -x, and turn off option processing.
- --
-
Used as the last option; turn off option processing so that arguments
beginning with - are not misinterpreted as options. (For example, you
can set $1 to -1.) If no arguments
are given after --, unset the
positional parameters.
- -a
-
From now on, automatically mark variables for export after defining
or changing them.
- -b
-
Report background job status at termination instead of waiting for
next shell prompt.
- -e
-
Exit if a command yields a nonzero exit status.
- -f
-
Do not expand filename metacharacters (e.g., *
? [ ]). Wildcard expansion is sometimes called
globbing.
- -h
-
Locate and remember commands as they are defined.
- -k
-
Assignment of environment variables
(var=value) will take effect
regardless of where they appear on the command line. Normally,
assignments must precede the command name.
- -m
-
Monitor mode. Enable job control; background jobs execute in a
separate process group. -m usually
is set automatically.
- -n
-
Read commands, but don't execute. Useful for
checking errors, particularly for shell scripts.
- -o [m]
-
List shell modes, or turn on mode m. Many modes
can be set by other options. The modes can be turned off through the
+o option. Modes are:
- allexport
-
Same as -a.
- braceexpand
-
Same as -B.
- emacs
-
Enter Emacs editing mode (on by default).
- errexit
-
Same as -e.
- hashall
-
Same as -h.
- histexpand
-
Same as -H.
- history
-
Default. Preserve command history.
- ignoreeof
-
Don't allow use of a single Ctrl-D (the end-of-file or EOF character) to
log off; use the exit command to log
off. This has the same effect as setting the shell variable IGNOREEOF=1.
- interactive-comments
-
Allow comments to appear in interactive commands.
- keyword
-
Same as -k.
- monitor
-
Same as -m.
- noclobber
-
Same as -C.
- noexec
-
Same as -n.
- noglob
-
Same as -f.
- notify
-
Same as -b.
- nounset
-
Same as -u.
- onecmd
-
Same as -t.
- physical
-
Same as -P.
- posix
-
Match POSIX standard.
- privileged
-
Same as -p.
- verbose
-
Same as -v.
- vi
-
Enable vi-style command-line editing.
- xtrace
-
Same as -x.
- +o [m]
-
Display the set commands that would
recreate the current mode settings or turn off mode
m. See the -o
option for a list of modes.
- -p
-
Start up as a privileged user; don't process
$HOME/.profile.
- -t
-
Exit after one command is executed.
- -u
-
Indicate an error when user tries to use a variable that is undefined.
- -v
-
Show each shell command line when read.
- -x
-
Show commands and arguments when executed, preceded by a + or the prompt defined by the PS4 shell variable. This provides step-by-step
debugging of shell scripts. (Same as -o
xtrace.)
- -B
-
Default. Enable brace expansion.
- -C
-
Don't allow output redirection (>) to overwrite an existing file.
- -H
-
Default. Enable ! and !! commands.
- -P
-
Print absolute pathnames in response to pwd. By default, bash includes symbolic links in its response
to pwd.
Examples
set -- "$num" -20 -30 Set $1 to $num, $2 to -20, $3 to -30
set -vx Read each command line; show it; execute it;
show it again (with arguments)
set +x Stop command tracing
set -o noclobber Prevent file overwriting
set +o noclobber Allow file overwriting again
shift [n] Shift positional arguments (e.g., $2
becomes $1). If
n is given, shift to the left
n places.
shopt [options] [optnames] Set or unset variables that control optional shell behavior. With no
options or with -p, display the
settable optnames.
Options
- -o
-
Allow only options defined for the set
-o built-in to be set or unset.
- -p
-
Display output in a form that can be reused as input.
- -q
-
Quiet mode. Suppress normal output.
- -s
-
Set (enable) each specified option. With no
optname, list all set options.
- -u
-
Unset (disable) each specified option. With no
optname, list all unset options.
Settable shell options
Unless otherwise noted, options are disabled by default.
- cdable_vars
-
If an argument to the cd built-in is
not a directory, assume that it's a variable
containing the name of the directory to change to.
- cdspell
-
For interactive shells, check for minor errors in the name of a
directory component (transposed characters, a missing character, or
an extra character). Print the corrected name and proceed.
- checkhash
-
Check that a command found in the hash table actually exists before
trying to execute it; if it is not found, do a path search.
- checkwinsize
-
Check the window size after each command and update LINES and COLUMNS as necessary.
- cmdhist
-
Attempt to save all lines of a multiline command in one history entry
to facilitate re-editing.
- dotglob
-
Include filenames beginning with . in the results of pathname
expansion.
- execfail
-
For a noninteractive shell, do not exit if the file specified as an
argument to exec cannot be executed.
For an interactive shell, do not exit from the shell if exec fails.
- expand_aliases
-
Expand aliases. Enabled by default for interactive shells.
- extglob
-
Enable the shell's extended pattern matching
features for pathname expansion.
- histappend
-
Append the history list to the file specified by HISTFILE when the
shell exits, instead of overwriting the file.
- histreedit
-
Give the user a chance to re-edit a failed history substitution.
- histverify
-
Load a history substitution into the readline editing buffer so it can be further
edited, instead of immediately passing it to the shell parser.
- hostcomplete
-
Try to provide hostname completion when a word containing @ is being
completed. Set by default.
- huponexit
-
Send SIGHUP to all jobs when an interactive login shell exits.
- interactive_comments
-
In an interactive shell, treat any word beginning with a #, and any
subsequent characters, as a comment. Set by default.
- lithist
-
If cmdhist is also enabled, save
multiline commands to the history file separated by embedded newlines
rather than semicolons (;) when possible.
- login_shell
-
Set by the shell if it is started as a login shell. Cannot be changed
by the user.
- mailwarn
-
Warn if a mail file has been accessed since the last time bash checked it.
- no_empty_cmd_completion
-
Don't attempt to search the PATH for possible
completions when completion is attempted on an empty line.
- nocaseglob
-
Use case-insensitive filename matching during pathname expansion.
- nullglob
-
Allow patterns that do not match any files to expand to a null string.
- progcomp
-
Enable the programmable completion facilities. Set by default.
- promptvars
-
Perform variable and parameter expansion on prompt strings after
performing normal expansion. Set by default.
- restricted_shell
-
Set by the shell if started in restricted mode. This option cannot be
changed by the user and is not reset when the startup files are
executed.
- shift_verbose
-
Cause the shift built-in to print an
error message when the shift count is greater than the number of
positional parameters.
- sourcepath
-
Cause the source built-in (.) to
search the PATH to find the directory containing a file supplied as
an argument. Set by default.
- xpg_echo
-
Cause the echo built-in to expand
backslash-escape sequences by default.
source file [arguments] Read and execute lines in file.
file does not have to be executable but must
reside in a directory searched by PATH. Any
arguments are passed as positional parameters to
the file when it is executed.
suspend [-f] Same as Ctrl-Z.
Option
- -f
-
Force suspend, even if shell is a login shell.
test condition
[ condition ] Evaluate a condition and, if its value is true,
return a zero exit status; otherwise, return a nonzero exit status.
An alternate form of the command uses [
] rather than the word test. condition is
constructed using the following expressions. Conditions are true if
the description holds true.
File conditions
- -a file
-
file exists.
- -b file
-
file is a block special file.
- -c file
-
file is a character special file.
- -d file
-
file is a directory.
- -e file
-
file exists.
- -f file
-
file is a regular file.
- -g file
-
file has the set-group-ID bit set.
- -h file
-
file is a symbolic link.
- -k file
-
file has its sticky bit (no longer used) set.
- -p file
-
file is a named pipe (FIFO).
- -r file
-
file is readable.
- -s file
-
file has a size greater than 0.
- -t [n]
-
The open file descriptor n is associated with a
terminal device (default n is 1).
- -u file
-
file has its set-user-ID bit set.
- -w file
-
file is writable.
- -x file
-
file is executable.
- -G file
-
file's group is the
process's effective group ID.
- -L file
-
file is a symbolic link.
- -N file
-
file has been modified since its last time of
access.
- -O file
-
file's owner is the
process's effective user ID.
- -S file
-
file is a socket.
- f1 -ef f2
-
Files f1 and f2 are linked
(refer to the same file through a hard link).
- f1 -nt f2
-
File f1 is newer than f2.
- f1 -ot f2
-
File f1 is older than f2.
String conditions
- -n s1
-
String s1 has nonzero length.
- -o s1
-
Shell option s1 is set. Shell options are
described under the set built-in
command.
- -z s1
-
String s1 has 0 length.
- s1 = s2
-
Strings s1 and s2 are
identical.
- s1 = = s2
-
Strings s1 and s2 are
identical.
- s1 != s2
-
Strings s1 and s2 are not
identical.
- s1 < s2
-
String s1 is lower in the alphabet (or other
sort in use) than s2. By default, the check is
performed character-by-character against the ASCII character set.
- s1 > s2
-
String s1 is higher in the alphabet (or other
sort in use) than s2.
- string
-
string is not null.
Integer comparisons
- n1 -eq n2
-
n1 equals n2.
- n1 -ge n2
-
n1 is greater than or equal to
n2.
- n1 -gt n2
-
n1 is greater than n2.
- n1 -le n2
-
n1 is less than or equal to
n2.
- n1 -lt n2
-
n1 is less than n2.
- n1 -ne n2
-
n1 does not equal n2.
Combined forms
- ! condition
-
True if condition is false.
- condition1 -a condition2
-
True if both conditions are true.
- condition1 -o condition2
-
True if either condition is true.
Examples
Each of the following examples shows the first line of various
statements that might use a test condition:
while test $# -gt 0 While there are arguments . . .
while [ -n "$1" ] While the first argument is nonempty . . .
if [ $count -lt 10 ] If $count is less than 10 . . .
if [ -d RCS ] If the RCS directory exists . . .
if [ "$answer" != "y" ] If the answer is not y . . .
if [ ! -r "$1" -o ! -f "$1" ] If the first argument is not a
readable file or a regular file . . .
times Print accumulated process times for user and system.
trap [option] [commands] [signals] Execute commands if any of
signals is received. Each
signal can be a signal name or number. Common
signals include 0, 1, 2, and 15. Multiple commands should be quoted
as a group and separated by semicolons internally. If
commands is the null string (e.g., trap "" signals), then
signals is ignored by the shell. If
commands is omitted entirely, reset processing
of specified signals to the default action. If both
commands and signals are
omitted, list current trap assignments. See examples at the end of
this entry and under exec.
Options
- -l
-
List signal names and numbers.
- -p
-
Used with no commands to print the trap commands
associated with each signal, or all signals if
none is specified.
Signals
Signals are listed along with what triggers them.
- 0
-
Exit from shell (usually when shell script finishes).
- 1
-
Hang up (usually logout).
- 2
-
Interrupt (usually through Ctrl-C).
- 3
-
Quit.
- 4
-
Illegal instruction.
- 5
-
Trace trap.
- 6
-
Abort.
- 7
-
Unused.
- 8
-
Floating-point exception.
- 9
-
Termination.
- 10
-
User-defined.
- 11
-
Reference to invalid memory.
- 12
-
User-defined.
- 13
-
Write to a pipe without a process to read it.
- 14
-
Alarm timeout.
- 15
-
Software termination (usually via kill).
- 16
-
Unused.
- 17
-
Termination of child process.
- 18
-
Continue (if stopped).
- 19
-
Stop process.
- 20
-
Process suspended (usually through Ctrl-Z).
- 21
-
Background process has tty input.
- 22
-
Background process has tty output.
- 23-28
-
Unused.
- 29
-
I/O possible on a channel.
Examples
trap "" 2 Ignore signal 2 (interrupts)
trap 2 Obey interrupts again
Remove a $tmp file when the shell
program exits or if the user logs out, presses Ctrl-C, or does a kill:
trap "rm -f $tmp; exit" 0 1 2 15
type [options] commands Report absolute pathname of programs invoked for
commands and whether or not they are hashed.
Options
- --
-
Consider all subsequent strings to be arguments, not options.
- -a, -all
-
Print all occurrences of command, not just that
which would be invoked.
- -f
-
Suppress shell function lookup.
- -p, -path
-
Print the hashed value of command, which may
differ from the first appearance of command in
the PATH.
- -t, -type
-
Determine and state if command is an alias,
keyword, function, built-in, or file.
- -P
-
Force a PATH search for each name, even if -t would not return a value of
"file" for the name.
Example
type mv read
mv is /bin/mv
read is a shell built-in
typeset Obsolete. See declare.
ulimit [options] [n] Print the value of one or more resource limits or, if
n is specified, set a resource limit to
n. Resource limits can be either hard (-H) or soft (-S). By default, ulimit sets both limits or prints the soft
limit. The options determine which resource is acted on. Values are
in 1024-byte increments unless otherwise indicated.
Options
- --
-
Consider all subsequent strings to be arguments, not options.
- -a
-
Print all current limits.
- -H
-
Hard resource limit.
- -S
-
Soft resource limit.
Specific limits
These options limit specific resource sizes.
- -c
-
Core files.
- -d
-
Size of processes' data segments.
- -f
-
Size of shell-created files.
- -l
-
Size of memory that the process can lock.
- -m
-
Resident set size.
- -n
-
Number of file descriptors. On many systems, this cannot be set.
- -p
-
Pipe size, measured in blocks of 512 bytes.
- -s
-
Stack size.
- -t
-
Amount of CPU time, counted in seconds.
- -u
-
Number of processes per user.
- -v
-
Virtual memory used by shell.
umask [options] [nnn] Display file creation mask or set file creation mask to octal value
nnn. The file creation mask determines which
permission bits are turned off (e.g., umask
002 produces rw-rw-r--).
Options
- -p
-
Display mask within a umask command
so that a caller can read and execute it.
- -S
-
Display umask symbolically rather
than in octal.
unalias [-a] names Remove names from the alias list. See also
alias.
Option
- -a
-
Remove all aliases.
unset [options] names Erase definitions of functions or variables listed in
names.
Options
- -f
-
Expect name to refer to a function.
- -v
-
Expect name to refer to a variable (default).
until
test-commands
do
commands
done Execute test-commands (usually a test or [ ]
command); if the exit status is nonzero (that is, the test fails),
perform commands. Repeat.
wait [ID] Pause in execution until all background jobs complete (exit status 0
will be returned), or until the specified background process ID or
job ID completes (exit status of ID is
returned). Note that the shell variable $! contains the process ID of the most recent
background process. If job control is not in effect,
ID can only be a process ID number. See Section 7.6.
Example
ait $! Wait for last background process to finish
while
test-commands
do
commands
done Execute test-commands (usually a test or [ ]
command); if the exit status is 0, perform
commands. Repeat.
| | | 7.6. Job Control | | 8. tcsh: An Extended C Shell |
Copyright © 2003 O'Reilly & Associates. All rights reserved.
|