# |
#
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.
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
alias |
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.
bind |
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.
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 |
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 |
builtin command [arguments]
Execute command, which must be a shell built-in. Useful for invoking built-ins within scripts of the same name.
case |
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 |
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.
command |
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.
compgen |
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 |
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.
continue |
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 |
declare [options] [name[=value]] typeset [options] [name[=value]]
Print or set variables. Options prefaced by + instead of - are inverted in meaning.
dirs |
dirs [options]
Print directories currently remembered for pushd/popd operations.
disown |
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.
echo |
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.)
enable |
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.
exec |
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.
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 |
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).
if [ $# -eq 0 ]; then echo "Usage: $0 [-c] [-d] file(s)" exit 1 # Error status fi
export |
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.
fc |
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.
for |
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.
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 |
function command{ ...}
Define a function. Refer to arguments the same way as positional parameters in a shell script ($1, etc.) and terminate with }.
getopts |
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 |
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).
help |
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 |
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.
if |
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 |
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.
kill |
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.
let |
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.
Both of the following examples add 1 to variable i:
let i=i+1 let "i = i + 1"
local |
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 |
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 |
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.
printf |
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.
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 |
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.
pwd |
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.
read |
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.
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 |
readonly [options] [variable1 variable2...]
Prevent the specified shell variables from being assigned new values. Variables can be accessed (read) but not overwritten.
return |
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 |
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 |
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.
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 |
shift [n]
Shift positional arguments (e.g., $2 becomes $1). If n is given, shift to the left n places.
shopt |
shopt [options] [optnames]
Set or unset variables that control optional shell behavior. With no options or with -p, display the settable optnames.
Unless otherwise noted, options are disabled by default.
source |
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.
test |
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.
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 . . .
trap |
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.
Signals are listed along with what triggers them.
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 |
type [options] commands
Report absolute pathname of programs invoked for commands and whether or not they are hashed.
type mv read mv is /bin/mv read is a shell built-in
typeset |
typeset
Obsolete. See declare.
ulimit |
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.
These options limit specific resource sizes.
umask |
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--).
unalias |
unalias [-a] names
Remove names from the alias list. See also alias.
unset |
unset [options] names
Erase definitions of functions or variables listed in names.
until |
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 |
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.
ait $! Wait for last background process to finish
while |
while test-commands do commands done
Execute test-commands (usually a test or [ ] command); if the exit status is 0, perform commands. Repeat.
Copyright © 2003 O'Reilly & Associates. All rights reserved.