This appendix collects many tables of values, settings, operators, commands, variables, and more in one place for easy reference.
Here are the options you can use when invoking current versions of bash. The multi-character options must appear on the command line before the single-character options. Login shells usually have the options -i (interactive), -s (read from standard input), and -m (enable job control) set internally.
In addition to those listed in Table A-1, any set option can be used on the command line; see “set Options”. In particular, the -n option is invaluable for syntax checking (see Recipe 19.12), and -x is used for debugging (Recipe 19.13).
For further reference, see http://bit.ly/2wtEjA8.
| Option | Meaning |
|---|---|
|
Commands are read from |
|
A list of all double-quoted strings preceded by |
|
Makes the shell an interactive shell. Ignores signals |
|
Makes bash act as if it were invoked as a login shell. |
|
Takes the same arguments as |
|
|
|
Reads commands from standard input. If an argument is given to bash, this flag takes precedence (i.e., the argument won’t be treated as a script name and standard input will be read). |
|
Makes the shell a restricted shell. |
|
Prints shell input lines as they’re read. |
|
Signals the end of options and disables further option processing. Any options after this are treated as filenames and arguments. |
|
Arranges for the debugger profile to be executed before the shell starts. Turns on extended debugging mode and shell function tracing in bash 3.0 or later. |
|
Does the same as |
|
Does the same as |
|
Displays a usage message and exits. |
|
Makes bash act as if it were invoked as a login shell. Same as |
|
Does not use the GNU readline library to read command lines if the shell is interactive. |
|
Does not read the startup file /etc/profile or any of the personal initialization files. |
|
Does not read the initialization file ~/.bashrc if the shell is interactive. This is on by default if the shell is invoked as sh. |
|
Changes the behavior of bash to follow the POSIX standard more closely where the default operation of bash is different. |
|
Executes commands read from |
|
Equivalent to |
|
Equivalent to |
|
Shows the version number of this instance of bash and then exits. |
Table A-2 shows a summary of the prompt customizations that are available. The customizations \[ and \] are not available in bash versions prior to 1.14. \a, \e, \H, \T, \@, \v, and \V are not available in versions prior to 2.0. \A, \D, \j, \l, and \r are only available in later versions of bash 2.0 and in bash 3.0+.
| Command | Meaning |
|---|---|
|
The ASCII bell character ( |
|
The current time in 24-hour HH:MM format. |
|
The date in “Weekday Month Day” format. |
|
The |
|
The ASCII escape character ( |
|
The hostname. |
|
The hostname up to the first |
|
The number of jobs currently managed by the shell. |
|
The basename of the shell’s terminal device name. |
|
A carriage return and line feed. |
|
A carriage return. |
|
The name of the shell. |
|
The current time in 12-hour HH:MM:SS format. |
|
The current time in 24-hour HH:MM:SS format. |
|
The current time in 12-hour a.m./p.m. format. |
|
The username of the current user. |
|
The version of bash (e.g., 2.00). |
|
The release of bash (the version and patch level; e.g., 3.00.0). |
|
The current working directory, with |
|
The basename of |
|
The command number of the current command. |
|
The history number of the current command. |
|
If the effective UID is 0, a |
|
The character code in octal. |
|
A backslash. |
|
Begin a sequence of nonprinting characters, such as a terminal control sequence. |
|
End a sequence of nonprinting characters. |
Table A-3 shows the ANSI color escape sequences.
| Code | Character attribute | FG code | Foreground color | BG code | Background color |
|---|---|---|---|---|---|
0 |
Reset all attributes |
30 |
Black |
40 |
Black |
1 |
Bright |
31 |
Red |
41 |
Red |
2 |
Dim |
32 |
Green |
42 |
Green |
4 |
Underscore |
33 |
Yellow |
43 |
Yellow |
5 |
Blink |
34 |
Blue |
44 |
Blue |
7 |
Reverse |
35 |
Magenta |
45 |
Magenta |
8 |
Hidden |
36 |
Cyan |
46 |
Cyan |
37 |
White |
47 |
White |
Table A-4 lists the builtin commands in current versions of bash (see http://bit.ly/2wlut4o).
| Command | Summary |
|---|---|
. |
Read a file and execute its contents in the current shell. See source. |
: |
Do nothing (just do expansions of any arguments). |
[ |
Evaluate a conditional expression. See test. |
alias |
Set up shorthand for a command or command line. |
bg |
Put a job in the background. |
bind |
Bind a key sequence to a readline function or macro. |
break |
Exit from the surrounding |
builtin |
Execute the specified shell builtin. |
caller |
Return the context of any active subroutine call (a shell function or a script executed with the . or source builtins). |
cd |
Change the working directory. |
command |
Run a command, bypassing shell function lookup. |
compgen |
Generate possible completion matches. |
complete |
Specify how completion should be performed. |
compopt |
Modify completion options for each |
continue |
Skip to the next iteration of the surrounding |
declare |
Declare variables and give them attributes. Same as typeset. |
dirs |
Display the list of currently remembered directories. |
disown |
Remove a job from the job table. |
echo |
Output arguments. |
enable |
Enable and disable (with |
eval |
Run the given arguments through command-line processing. |
exec |
Replace the shell with the given program. |
exit |
Exit from the shell. |
export |
Create environment variables. |
fc |
Fix command (edit the history file). |
fg |
End a background job in the foreground. |
getopts |
Process command-line options. |
hash |
Remember full pathnames of the specified commands. |
help |
Display helpful information on builtin commands. |
history |
Display the command history. |
jobs |
List any background jobs. |
kill |
Send a signal to a process. |
let |
Arithmetic variable assignment. |
local |
Create a local variable. |
logout |
Exit a login shell. |
mapfile |
Read lines from standard input or a file descriptor into the indexed array variable array. See readarray. |
popd |
Remove a directory from the directory stack. |
printf |
Write the formatted |
pushd |
Add a directory to the directory stack. |
pwd |
Print the working directory. |
read |
Read a line from standard input. |
readarray |
Read lines from standard input or a file descriptor into the indexed array variable array. See mapfile. |
readonly |
Make variables read-only (unassignable). |
return |
Return from the surrounding function or script. |
set |
Set options. |
shift |
Shift command-line arguments. |
shopt |
Toggle the values of settings controlling optional shell behavior. |
source |
Read a file and execute its contents in the current shell. See . (dot). |
suspend |
Suspend execution of a shell. |
test |
Evaluate a conditional expression. See [. |
times |
Print the accumulated user and system times for processes run from the shell. |
trap |
Set up a signal-catching routine. |
type |
Identify the source of a command. |
typeset |
Declare variables and give them attributes. Same as declare. |
ulimit |
Set/show process resource limits. |
umask |
Set/show thefile permission mask. |
unalias |
Remove alias definitions. |
unset |
Remove definitions of variables or functions. |
wait |
Wait for background job(s) to finish. |
Table A-5 lists the reserved words in current versions of bash (see http://bit.ly/2wlxEZO).
| Command | Summary |
|---|---|
|
Logical NOT of a command’s exit status. |
|
Return a status of |
|
Evaluate the arithmetic expression according to the bash shell arithmetic rules. |
|
Execute the list in a subshell. |
|
Execute the list in the current shell context. |
|
Multiway conditional construct. |
|
Part of a |
|
Part of a |
|
Part of an |
|
Part of an |
|
End of a |
|
End of an |
|
Looping construct. |
|
Define a function. |
|
Conditional construct. |
|
Part of a |
|
Menu-generation construct. |
|
Part of an |
|
Run the command pipeline and print execution times. The format of the output can be controlled with |
|
Looping construct. |
|
Looping construct. |
Table A-6 shows a complete list of environment variables available in bash 4.4. The letters in the Type column of the table have the following meanings: A = array, L = colon-separated list, R = read-only, U = unsetting it causes it to lose its special meaning.
Note that the variables beginning BASH_ or COMP as well as the variables DIRSTACK, FUNCNAME, GLOBIGNORE, GROUPS, HISTIGNORE, HOSTNAME, HISTTIMEFORMAT, LANG, LC_ALL, LC_COLLATE, LC_MESSAGE, MACHTYPE, PIPESTATUS, SHELLOPTS, and TIMEFORMAT are not available in versions prior to 2.0. BASH_ENV replaces ENV, found in earlier versions.
| Variable | Type | Description |
|---|---|---|
|
R |
The positional parameters given to the current script or function. If not double-quoted, each word is further split and expanded. If double-quoted, this returns a single string containing each argument separated by the first character of |
|
R |
Each of the positional parameters given to the current script or function, given as a list of double-quoted strings (e.g., |
|
R |
The number of arguments given to the current script or function. |
|
R |
The exit status of the previous command. |
|
R |
The options given to the shell on invocation. |
|
R |
The process ID of the shell process. |
|
R |
The process ID of the last background command. |
|
R |
The name of the shell or shell script. |
|
R |
The last argument to the previous command. |
|
Controls how job control works (values are |
|
|
The full pathname used to invoke this instance of bash. |
|
|
L |
A colon-separated list of enabled shell options. |
|
Expands to the process ID of the current bash process. |
|
|
A |
An associative array variable whose members correspond to the internal list of aliases as maintained by the alias builtin. |
|
A |
An array of values, which 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. |
|
A |
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. |
|
An associative array variable whose members correspond to the internal hash table of commands as maintained by the hash builtin. |
|
|
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. |
|
|
The name of a file to run as the environment file when the shell is invoked. |
|
|
The command argument to the |
|
|
A |
An array whose members are the line numbers in source files corresponding to each member of |
|
L |
A colon-separated list of directories in which the shell looks for dynamically loadable builtins specified by the enable command. |
|
AR |
An array whose members are assigned by the |
|
A |
An array containing the source filenames corresponding to the elements in the |
|
Incremented by 1 each time a subshell or subshell environment is spawned. The initial value is 0. A subshell is a forked copy of the parent shell and shares its environment. |
|
|
AR |
Version information for this instance of bash. Each element of the array holds parts of the version number. |
|
The version number of this instance of bash. |
|
|
If set to an integer corresponding to a valid file descriptor, bash will write the trace output generated when |
|
|
L |
A list of directories for the cd command to search. |
|
The number of exited child status values for the shell to remember. |
|
|
Used by the select command to determine the terminal width when printing selection lists. |
|
|
An index into |
|
|
The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion facilities. |
|
|
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 |
|
|
A |
An array of the individual words in the current command line. This variable is available only in shell functions invoked by the programmable completion facilities. |
|
A |
The possible completions generated by a shell function invoked by the programmable completion facilities. |
|
A |
An array variable from which bash reads the possible completions generated by a shell function invoked by the programmable completion facilities. |
|
The key (or final key of a key sequence) used to invoke the current completion function. |
|
|
An integer value corresponding to the type of completion attempted that caused a completion function to be called. |
|
|
An array variable created to hold the file descriptors for output from and input to an unnamed coprocess. |
|
|
ARU |
The current contents of the directory stack. |
|
When set to |
|
|
Controls which default set of key bindings is used. |
|
|
If bash finds this variable in the environment when the shell starts with the value |
|
|
Similar to |
|
|
R |
The effective user ID of the current user. |
|
L |
A colon-separated list of shell patterns defining the list of filenames to be ignored by command search using |
|
The default editor for the fc command. |
|
|
L |
A list of names to ignore when doing filename completion. |
|
ARU |
An array 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. |
|
If set to a numeric value greater than 0, defines a maximum function nesting level. |
|
|
L |
A list of patterns defining filenames to ignore during pathname expansion. |
|
AR |
An array containing a list of groups of which the current user is a member. |
|
Specifies what to use as the history control characters. Normally set to the string |
|
|
U |
The history number of the current command. |
|
L |
A list of patterns, separated by colons ( |
|
The name of the command history file. |
|
|
The maximum number of lines to keep in the history file. |
|
|
A list of patterns used to determine what should be retained in the history list. |
|
|
The maximum number of commands to keep in the command history. |
|
|
If set, timestamps are written to the history file so they may be preserved across shell sessions. If not null, this variable’s value is used as a format string for strftime(3) to print the timestamp associated with each history entry displayed by the history builtin. |
|
|
The home (login) directory. |
|
|
The file to be used for hostname completion. |
|
|
The name of the current host. |
|
|
The type of machine bash is running on. |
|
|
The internal field separator: a list of characters that act as word separators. Normally set to space, tab, and newline. |
|
|
The number of |
|
|
The readline startup file. |
|
|
Used to determine the locale category for any category where one is not specifically set with a variable starting with |
|
|
Overrides the value of |
|
|
Determines the collation order used when sorting the results of pathname expansion. |
|
|
Determines the interpretation of characters and the behavior of character classes within pathname expansion and pattern matching. |
|
|
Determines the locale used to translate double-quoted strings preceded by a |
|
|
Determines the locale category used for number formatting. |
|
|
Determines the locale category used for date and time formatting. |
|
|
U |
The number of the line that just ran in a script or function. |
|
Used by the select command to determine the column length for printing selection lists. |
|
|
A string describing the system on which bash is executing. |
|
|
The name of the file to check for new mail. |
|
|
How often (in seconds) to check for new mail. |
|
|
L |
A list of filenames to check for new mail, if |
|
A |
An array variable created to hold the text read by the mapfile builtin when no variable name is supplied. |
|
If set to |
|
|
The previous working directory. |
|
|
The value of the last option argument processed by getopts. |
|
|
If set to |
|
|
The index of the last option argument processed by getopts. |
|
|
The operating system on which bash is executing. |
|
|
L |
The search path for commands. |
|
A |
An array variable containing a list of exit status values from the processes in the most recently executed foreground pipeline. |
|
If this is set in the environment when bash starts, the shell enters POSIX mode before reading the startup files, as if the |
|
|
R |
The process ID of the shell’s parent process. |
|
The value is executed as a command before the primary prompt is issued. |
|
|
If set to a number greater than 0, the value is used as the number of trailing directory components to retain when expanding the |
|
|
If set, the prompt string is displayed in an interactive shell after reading a command and before the command is executed. Only available in bash 4.4 and newer. |
|
|
The primary command prompt string. |
|
|
The prompt string for line continuations. |
|
|
The prompt string for the select command. |
|
|
The prompt string for the xtrace option. |
|
|
R |
The process ID of the parent process. |
|
The current working directory as set by the cd builtin. |
|
|
U |
When referenced, generates a pseudorandom integer between 0 and 32,767. |
|
The contents of the readline line buffer, for use with |
|
|
The position of the insertion point in the readline line buffer, for use with |
|
|
The user’s response to the select command; also, the result of the read command if no variable names are given. |
|
|
U |
The number of seconds since the shell was started. |
|
The full pathname of the shell. |
|
|
LR |
A colon-separated list of enabled shell options. |
|
Incremented by 1 each time a new instance (not a subshell) of bash is invoked. This is intended to be a count of how deeply your bash shells are nested. |
|
|
Indicates the location of the message catalog files if not using |
|
|
Indicates the location of the message catalog files if using |
|
|
Specifies the format for the output from using the |
|
|
If set to a positive integer, the number of seconds after which the shell automatically terminates if no input is received. |
|
|
If set, the name of the directory in which bash creates temporary files for the shell’s use. |
|
|
R |
The numeric real user ID of the current user. |
The options in Table A-7 can be turned on with the set -arg command. They are all initially off except where noted. Full names, where listed, are arguments to set that can be used with set -o. The full names braceexpand, histexpand, history, keyword, and onecmd are not available in versions of bash prior to 2.0. Also, in those versions, hashing is switched with -d.
The mode string variables are only displayed when the show-mode-in-prompt readline variable is enabled (see Table A-22).
For further reference, see http://bit.ly/2uUXPpQ.
| Option | Full name (-o) | Meaning |
|---|---|---|
|
|
Export all subsequently defined or modified variables. |
|
|
Perform brace expansion. This is on by default. |
|
|
Report the status of terminating background jobs immediately. |
|
|
Prevent output redirection using |
|
|
If set, any trap on |
|
|
Exit the shell when a simple command exits with nonzero status. A simple command is a command not part of a |
|
Use an Emacs-style line editing interface. This also affects the editing interface used for |
|
|
|
Disable filename expansion (globbing). |
|
|
Enable |
|
Enable command history. On by default in interactive shells. |
|
|
|
Locate and remember (hash) commands as they are looked up for execution. This option is enabled by default. |
|
Prevent an interactive shell from exiting upon reading |
|
|
|
All arguments in the form of assignment statements are placed in the environment for a command, not just those that precede the command name. |
|
|
Enable job control. On by default in interactive shells. |
|
|
Read commands but do not execute them. This may be used to check a script for syntax errors. This option is ignored by interactive shells. |
|
|
If set, do not resolve symbolic links when performing commands such as cd that change the current directory. |
|
|
Turn on privileged mode. |
|
The return value of a pipeline is the value of the last (rightmost) command to exit with a nonzero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default. |
|
|
Change the behavior of bash where the default operation differs from the POSIX standard to match the standard. |
|
|
|
If set, any traps on |
|
|
Exit after reading and executing one command. |
|
|
Treat unset variables and parameters other than the special parameters |
|
|
Print shell input lines before running them. |
|
Use vi-style command-line editing. |
|
|
|
Print commands (after expansions) before running them. |
|
If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters are set to the arguments, even if some of them begin with a |
|
|
Signals the end of options. All remaining arguments are assigned to the positional parameters. |
The shopt options are set with shopt -s arg and unset with shopt -u arg (see Table A-8). Versions of bash prior to 2.0 had environment variables to perform some of these settings. Setting them equated to shopt -s. The variables (and corresponding shopt options) were allow_null_glob_expansion (nullglob), cdable_vars (cdable_vars), command_oriented_history (cmdhist), glob_dot_filenames (dotglob), and no_exit_ on_failed_exec (execfail). These variables no longer exist.
The options extdebug, failglob, force_fignore, and gnu_errfmt are not available in versions of bash prior to 3.0.
For further reference, see http://bit.ly/2vPjVsC.
| Option | Meaning if set |
|---|---|
|
A command name that is the name of a directory is executed as if it were the argument to the cd command. |
|
An argument to cd that is not a directory is assumed to be the name of a variable whose value is the directory to change to. |
|
Minor errors in the spelling of a directory name supplied to the cd command will be corrected if there is a suitable match. This correction includes missing letters, incorrect letters, and letter transposition. This option works for interactive shells only. |
|
Commands found in the hash table are checked for existence before being executed, and nonexistence forces a |
|
bash lists the status of any stopped and running jobs before exiting an interactive shell. |
|
bash checks the window size after each command and, if necessary, updates the values of |
|
bash attempts to save all lines of a multiline command in a single history entry. |
|
bash changes its behavior to that of version 3.2 with respect to locale-specific string comparison when using certain commands and operators. |
|
bash changes its behavior to that of version 4.0 with respect to locale-specific string comparison when using certain commands and operators. |
|
bash, when in POSIX mode, treats a single quote in a double-quoted parameter expansion as a special character. |
|
bash does not process the replacement string in the pattern substitution word expansion using quote removal. |
|
bash changes its behavior to that of version 4.3 with respect to certain operations. |
|
bash quotes all shell metacharacters in filenames and directory names when performing completion. |
|
bash replaces directory names with the results of word expansion when performing filename completion. |
|
bash attempts spelling correction on directory names during word completion if the directory name initially supplied does not exist. |
|
bash includes filenames beginning with a dot in the results of filename expansion. |
|
A noninteractive shell will not exit if it cannot execute the argument to an exec command. Interactive shells do not exit if an exec fails. |
|
Aliases are expanded. |
|
Behavior intended for use by debuggers is enabled. For example, the |
|
Extended pattern-matching features are enabled. |
|
If set, |
|
Patterns that fail to match filenames during pathname expansion result in an expansion error. |
|
The suffixes specified by the |
|
Range expressions used in pattern-matching bracket expressions behave as if in the traditional C locale when performing comparisons. |
|
The pattern |
|
Shell error messages are written in the standard GNU error message format. |
|
The history list is appended to the file named by the value of the variable |
|
If readline is being used, the opportunity is given for reediting a failed history substitution. |
|
If 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. |
|
If readline is being used, an attempt will be made to perform hostname completion when a word beginning with |
|
bash will send a |
|
Command substitution inherits the value of the |
|
Allows a word beginning with |
|
If job control is not active, the shell runs the last command of a pipeline not executed in the background in the current shell environment. |
|
If the |
|
bash was started as a login shell. This is a read-only value. |
|
If the file being checked for mail has been accessed since the last time it was checked, the message “The mail in mailfile has been read” is displayed. |
|
If readline is being used, no attempt will be made to search the |
|
bash matches filenames in a case-insensitive fashion when performing pathname expansion. |
|
bash matches patterns in a case-insensitive fashion when performing certain operations. |
|
Causes patterns that match no files to expand to null strings rather than to themselves. |
|
Programmable completion facilities are enabled. Default is on. |
|
Prompt strings undergo variable and parameter expansion after being expanded. |
|
The shell was started in restricted mode. This value cannot be changed. |
|
The shift builtin will print an error if it has shifted past the last positional parameter. |
|
The source builtin will use the value of |
|
echo expands backslash escape sequences by default. |
The operators in Table A-9 are used with test and the [ ] and [[ ]] constructs. They can be logically combined with -a (“and”) and -o (“or”) and grouped with escaped parentheses (\( \)). The string comparisons < and > and the [[ ]] construct are not available in versions of bash prior to 2.0, and =~ is only available in bash version 3.0 and later, as noted.
| Operator | True if |
|---|---|
|
True if |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if the length of |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if file descriptor |
|
True if |
|
True if |
|
True if |
|
True if the length of |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if the strings are not equal |
|
True if |
|
True if |
|
True if |
|
True if arithmetic expressions |
|
True if arithmetic expressions |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if |
|
True if |
a Only available in bash version 3.0 and later. May only be used inside | |
Table A-10 is a complete list of I/O redirectors. Note that there are two formats for specifying STDOUT and STDERR redirection: &>file and >&file. The second of these (which is the one used throughout this book) is the preferred way.
| Redirector | Function |
|---|---|
|
Pipe; send standard output of |
|
Pipe; send standard output and standard error of |
|
Direct standard output to |
|
Take standard input from |
|
Direct standard output to |
|
Force standard output to |
|
Force output to |
|
Use |
|
Direct standard output and standard error to |
|
Direct standard output and standard error to |
|
Use |
|
Here-document. |
|
Here-string. |
|
Direct file descriptor |
|
Take file descriptor |
|
Direct file descriptor |
|
Duplicate standard output to file descriptor |
|
Duplicate standard input from file descriptor |
|
File descriptor |
|
File descriptor |
|
Direct standard output and standard error to |
|
Close the standard input. |
|
Close the standard output. |
|
Close the output from file descriptor |
|
Close the input from file descriptor |
|
If |
|
If |
|
Moves the file descriptor |
|
Moves the file descriptor |
echo accepts three arguments (see Table A-11).
| Option | Function |
|---|---|
|
Turns on the interpretation of backslash-escaped characters |
|
Turns off the interpretation of backslash-escaped characters on systems where this mode is the default |
|
Omits the final newline (same as the |
echo also accepts a number of escape sequences that start with a backslash (Table A-12). These sequences exhibit fairly predictable behavior, except for \f, which on some displays causes a screen clear while on others it causes a line feed, and it ejects the page on most printers. \v is somewhat obsolete; it usually causes a line feed.
| Sequence | Character printed |
|---|---|
|
Alert or Ctrl-G (bell) |
|
Backspace or Ctrl-H |
|
Suppress further output |
|
Escape character (same as |
|
Escape character |
|
Form feed or Ctrl-L |
|
Newline (not at end of command) or Ctrl-J |
|
Return (Enter) or Ctrl-M |
|
Tab or Ctrl-I |
|
Vertical tab or Ctrl-K |
\\ |
Single backslash |
|
The eight-bit character whose value is the octal (base-8) value |
|
Same as |
|
The eight-bit character whose value is the hexadecimal (base-16) value |
|
The Unicode (ISO/IEC 10646) character whose value is the hexadecimal value |
|
The Unicode (ISO/IEC 10646) character whose value is the hexadecimal value |
The \n, \0, and \x sequences are even more device-dependent and can be used for complex I/O, such as cursor control and special graphics characters.
The printf command, available in bash since version 2.02, has three parts (beyond the command name):
printf [-v var] format-string [arguments]
-v var is optional and causes the output to be assigned to the variable var rather than being printed to standard output.
format-string describes the format specifications; this is best supplied as a string constant in quotes. arguments is a list, such as a list of strings or variable values that correspond to the format specifications.
The format is reused as necessary to use up 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.
A format specification is preceded by a percent sign (%), and the specifier is one of the characters described in Table A-13. Two of the main format specifiers are %s for strings and %d for decimal integers.
| Format character | Meaning |
|---|---|
|
Causes printf to expand backslash escape sequences in the corresponding argument in the same way as |
|
ASCII character (prints first character of corresponding argument) |
|
Decimal (base 10) integer |
|
Floating-point format |
|
Floating-point format ( |
|
Floating-point format ( |
|
|
|
|
|
Unsigned octal value |
|
Causes printf to output the corresponding argument in a format that can be reused as shell input |
|
String |
|
Unsigned decimal value |
|
Unsigned hexadecimal number; uses |
|
Unsigned hexadecimal number; uses |
%% |
Literal |
|
Causes printf to output the date-time string resulting from using datefmt as a format string for strftime (bash 4.2 or newer) |
The printf command can be used to specify the width and alignment of output fields. A format expression can take three optional modifiers following the % and preceding the format specifier:
%<flags<>width.precision<> format-specifier>
The width of the output field is a numeric value. When you specify a field width, the contents of the field are right-justified by default. You must specify a flag of - to get left-justification (the rest of the flags are shown in the table). Thus, %-20s outputs a left-justified string in a field 20 characters wide. If the string is less than 20 characters, the field is padded with whitespace to fill it. In the following examples, we put our format specifier between a pair of | in our format string so you can see the width of the field in the output. The first example right-justifies the text:
printf "|%10s|\n" hello@
It produces:
| hello|
The next example left-justifies the text:
printf "|%-10s|\n" hello
It produces:
|hello |
The precision modifier, used for decimal or floating-point values, controls the number of digits that appear in the result. For string values, it controls the maximum number of characters from the string that will be printed.
You can even specify both the width and precision dynamically, via values in the printf argument list. You do this by specifying asterisks in the format expression, instead of literal values:
$ myvar=42.123456 $ mysig=6 $ printf "|%*.*G|\n" 5 $mysig $myvar |42.1235| $
In this example, the width is 5, the precision is 6, and the value to print comes from the value of $myvar. The precision is optional and its exact meaning varies by control letter, as shown in Table A-14.
| Format | What “precision” means |
|---|---|
|
The minimum number of digits to print. When the value has fewer digits, it is padded with leading zeros. The default precision is 1. |
|
The minimum number of digits to print. When the value has fewer digits, it is padded with zeros after the decimal point. The default precision is 10. A precision of 0 inhibits printing of the decimal point. |
|
The number of digits to the right of the decimal point. |
|
The maximum number of significant digits. |
|
The maximum number of characters to print. |
|
[POSIX shell—may be nonportable to other versions of printf.] When used instead of |
|
[POSIX shell—may be nonportable to other versions of printf.] When used instead of |
%b and %q are additions to bash (and other POSIX-compliant shells) that provide useful features at the expense of nonportability to versions of the printf command found in some other shells and in other places in Unix. Here are two examples to make their functions a little clearer.
%q shell quotes:
$ printf "%q\n" "greetings to the world" greetings\ to\ the\ world $
%b echo-style escapes:
$ printf "%s\n" 'hello\nworld' hello\nworld $ printf "%b\n" 'hello\nworld' hello world $
Table A-15 shows the escape sequences that will be translated in a string printed with the %b format.
| Escape sequence | Meaning |
|---|---|
|
Escape character |
|
Bell character |
|
Backspace character |
|
Form feed character |
|
Newline character |
|
Carriage return character |
|
Tab character |
|
Vertical tab character |
|
Single-quote character |
|
Double-quote character |
|
Backslash character |
|
8-bit character whose ASCII value is the 1-, 2-, or 3-digit octal number |
|
8-bit character whose ASCII value is the 1- or 2-digit hexadecimal number |
Finally, one or more flags may precede the field width and the precision in a printf format specifier. We’ve already seen the - flag for left-justification. The rest of the flags are shown in Table A-16.
| Character | Description |
|---|---|
|
Left-justify the formatted value within the field. |
Space |
Prefix positive values with a space and negative values with a minus. |
|
Always prefix numeric values with a sign, even if the value is positive. |
|
Use an alternate form: |
|
Pad output with zeros, not spaces. This only happens when the field width is wider than the converted result. In the C language, this flag applies to all output formats, even nonnumeric ones. For bash, it only applies to the numeric formats. |
|
Format with thousands grouping characters if the format specification includes |
These examples for printf use some shell variables, assigned as follows in Table A-17:
PI=3.141592653589
| printf statement | Result | Comment |
|---|---|---|
|
|
Note the default rounding. |
|
|
A common mistake—the format specifier should be on the other side of the |
|
|
Gives five places to the right of the decimal point. |
|
|
Leading |
|
|
Truncates to four characters; with only one character, we get only one-character-wide output. Note reuse of format string. |
|
|
Assures us of a minimum four-character field width, right-justified; doesn’t truncate, though. |
|
|
Does it all—minimum width of four, maximum width of four, truncating if necessary, and left justifies (due to the minus sign) shorter than four. |
Here is one more example that will not display well in the table. The traditional way to write printf statements is to embed all formatting, including things like newlines, in the format string. This is shown in the table. That is encouraged, but you don’t have to do it that way, and sometimes it’s easier if you don’t. Note the → denotes a tab character in the output of this example:
$ printf "%b" "\aRing terminal bell, then tab\t then newline\nThen line 2.\n" Ring terminal bell, then tab → then newline Then line 2.
Finally, we really like the %(datefmt)T introduced in bash 4.2 because you can now often eliminate a subshell call to date, like so:
$ printf "%(%F)T\n" '-1' 2017-02-06 $ printf "%(%F_%T)T\n" 2017-02-06_20:31:25 $ printf "%(%F_%T%z)T: %s\n" '-1' 'Your log line here...' 2017-02-06_20:32:24-0500: Your log line here...
Table A-18 shows common date and time string formatting options. Consult your system’s manpages for date and strftime(3), as both the options and what they mean vary from system to system.
| Format | Description |
|---|---|
|
A literal |
|
The locale’s abbreviated weekday name (Sun..Sat). |
|
The locale’s full weekday name (Sunday..Saturday). |
|
The locale’s full month name (January..December). |
|
The locale’s abbreviated month name (Jan..Dec). See also |
|
The locale’s default/preferred date and time representation. |
|
The century (a year divided by 100 and truncated to an integer) as a decimal number (00..99). |
|
The day of the month as a decimal number (01..31). |
|
The date in the format |
|
The day of the month as a blank-padded decimal number ( 1..31). |
|
The date in the format |
|
The two-digit year corresponding to the |
|
The four-digit year corresponding to the |
|
The hour (24-hour clock) as a decimal number (00..23). |
|
The locale’s abbreviated month name (Jan..Dec). See also |
|
The hour (12-hour clock) as a decimal number (01..12). |
|
The day of the year as a decimal number (001..366). |
|
The hour (24-hour clock) as a blank-padded decimal number ( 0..23). |
|
The hour (12-hour clock) as a blank-padded decimal number ( 1..12). |
|
The month as a decimal number (01..12). |
|
The minute as a decimal number (00..59). |
|
A literal newline. |
|
Nanoseconds (000000000..999999999). [GNU] |
|
The locale’s equivalent of either “AM” or “PM”. |
|
The locale’s equivalent of either “am” or “pm”. [GNU] |
|
The locale’s representation of 12-hour clock time using AM/PM notation (HH:MM:SS AM/PM). |
|
The time in the format |
|
The number of seconds since the epoch, UTC (January 1, 1970 at 00:00:00). |
|
The second as a decimal number (00..61). The range of seconds is (00..61) instead of (00..59) to allow for the periodic occurrence of leap seconds and double leap seconds. |
|
A literal tab. |
|
The time in the format |
|
The weekday (Monday as the first day of the week) as a decimal number (1..7). |
|
The week number of the year (Sunday as the first day of the week) as a decimal number (00..53). |
|
The date in the format |
|
The week number of the year (Monday as the first day of the week) as a decimal number (01..53). According to ISO 8601 the week containing January 1 is week 1 if it has four or more days in the new year; otherwise it is week 53 of the previous year, and the next week is week 1. The year is given by the |
|
The weekday (Sunday as the first day of the week) as a decimal number (0..6). |
|
The week number of the year (Monday as the first day of the week) as a decimal number (00..53). |
|
The locale’s appropriate date representation. |
|
The locale’s appropriate time representation. |
|
The year without the century as a decimal number (00..99). |
|
The year with the century as a decimal number. |
|
The offset from UTC in the ISO 8601 format |
|
The time zone name. |
Table A-19 lists the pattern-matching characters in bash. The material in this section is adapted from the Bash Reference Manual.
| Character | Meaning |
|---|---|
|
Matches any string, including the null string |
|
Matches any single character |
|
Matches any one of the enclosed characters |
|
Matches any character not enclosed |
The following POSIX character classes may be used within brackets, as shown here (consult the grep or egrep manpage on your system for more details):
[[:alnum:]] [[:alpha:]] [[:ascii:]] [[:blank:]] [[:cntrl:]] [[:digit:]] [[:graph:]] [[:lower:]] [[:print:]] [[:punct:]] [[:space:]] [[:upper:]] [[:word:]] [[:xdigit:]]
The word character class matches letters, digits, and the character _.
[=c=] matches all characters with the same collation weight (as defined by the current locale) as the character c, while [.symbol.] matches the collating symbol symbol.
These character classes are affected by the locale setting. To get the traditional Unix values, use LC_COLLATE=C or LC_ALL=C.
The operators in Table A-20 apply when using shopt -s extglob. Matches are case-sensitive, but you may use shopt -s nocasematch (bash 3.1+) to change that. This option affects case and [[ commands.
| Grouping | Meaning |
|---|---|
|
Only one occurrence |
|
Zero or more occurrences |
|
One or more occurrences |
|
Zero or one occurrence |
|
No occurrences of this, but anything else |
Table A-21 lists the tr escape sequences.
| Sequence | Meaning |
|---|---|
|
Character with octal value |
|
A backslash character (i.e., escapes the backslash itself) |
|
“Audible” bell, the ASCII BEL character (since |
|
Backspace |
|
Form feed |
|
Newline |
|
Return |
|
Tab (sometimes called a horizontal tab) |
|
Vertical tab |
The GNU readline library provides the command line on which you type to communicate with bash and some other GNU utilities. It is amazingly configurable, but most people are not aware of this.
Tables A-22, A-23, and A-24 are a subset of what is available to work with. See the readline documentation for the full details.
The following is adapted directly from Chet Ramey’s documentation.
You can modify the runtime behavior of readline by altering the values of variables in readline using the set command within the init file. The syntax is simple:
set variable value
Here, for example, is how to change from the default Emacs-like key binding to use vi line-editing commands:
set editing-mode vi
Variable names and values, where appropriate, are recognized without regard to case. Unrecognized variable names are ignored.
Boolean variables (those that can be set to on or off) are set to on if the value is null or empty, on (case-insensitive), or 1. Any other value results in the variable being set to off.
Also, the mode string variables are only displayed when the show-mode-in-prompt readline variable is enabled (see also Table A-7).
| Variable | Description |
|---|---|
|
Controls what happens when readline wants to ring the terminal bell. If set to |
|
If set to |
|
If set to |
|
If set to |
|
If set to |
|
The string to insert at the beginning of the line when the insert-comment command is executed. The default value is |
|
The number of screen columns used to display possible matches when performing completion. The value is ignored if it is less than zero or greater than the terminal screen width. A value of |
|
If set to |
|
If set to |
|
The length in characters of the common prefix of a list of possible completions that is displayed without modification. When set to a value greater than zero, common prefixes longer than this value are replaced with an ellipsis when displaying possible completions. |
|
The number of possible completions that determines when the user is asked whether the list of possibilities should be displayed. If the number of possible completions is greater than this value, readline will ask the user whether to display them; otherwise, they are simply listed. This variable must be set to an integer value greater than or equal to zero. A negative value means readline should never ask. The default limit is |
|
If set to |
|
If set to |
|
When set to |
|
Controls which default set of key bindings is used. By default, readline starts up in Emacs editing mode, where the keystrokes are most similar to Emacs. This variable can be set to either |
|
The string to display immediately before the last line of the primary prompt when Emacs editing mode is active. The value is expanded like a key binding, so the standard set of meta- and control prefixes and backslash escape sequences is available. Use the |
|
When set to |
|
When set to |
|
When set to |
|
If set to |
|
If set to |
|
The maximum number of history entries to save in the history list. If set to |
|
If set to |
|
If set to |
|
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. |
|
Sets readline’s idea of the current keymap for key binding commands. Acceptable keymap names are |
|
Specifies the duration readline will wait for a character when reading an ambiguous key sequence (one that can form a complete key sequence using the input read so far, or can take additional input to complete a longer key sequence). If no input is received within the timeout, readline will use the shorter but complete key sequence. readline uses this value to determine whether or not input is available on the current input source ( |
|
If set to |
|
If set to |
|
If set to |
|
If set to |
|
If set to |
|
If set to |
|
If set to |
|
If set to |
|
If set to |
|
Alters the default behavior of the completion functions. If set to |
|
Alters the default behavior of the completion functions in a fashion similar to |
|
If set to |
|
If set to |
|
The string to display immediately before the last line of the primary prompt when vi editing mode is active and in command mode. The value is expanded like a key binding, so the standard set of meta and control prefixes and backslash escape sequences is available. Use the |
|
The string to display immediately before the last line of the primary prompt when vi editing mode is active and in insertion mode. The value is expanded like a key binding, so the standard set of meta and control prefixes and backslash escape sequences is available. Use the |
|
If set to |
The material in this section also appears in Learning the bash Shell, 3rd Edition, by Cameron Newham (O’Reilly).
Table A-23 is a complete list of readline Emacs editing mode commands.
| Command | Meaning |
|---|---|
Ctrl-A |
Move to beginning of line. |
Ctrl-B |
Move backward one character. |
Ctrl-D |
Delete one character forward. |
Ctrl-E |
Move to end of line. |
Ctrl-F |
Move forward one character. |
Ctrl-G |
Abort the current editing command and ring the terminal bell. |
Ctrl-J |
Same as Return. |
Ctrl-K |
Delete (kill) forward to end of line. |
Ctrl-L |
Clear screen and redisplay the line. |
Ctrl-M |
Same as Return. |
Ctrl-N |
Next line in command history. |
Ctrl-O |
Same as Return, then display next line in history file. |
Ctrl-P |
Previous line in command history. |
Ctrl-R |
Search backward. |
Ctrl-S |
Search forward. |
Ctrl-T |
Transpose two characters. |
Ctrl-U |
Kill backward from point to the beginning of line. |
Ctrl-V |
Make the next character typed verbatim. |
Ctrl-V Tab |
Insert a tab. |
Ctrl-W |
Kill the word behind the cursor, using whitespace as the boundary. |
Ctrl-X/ |
List the possible filename completions of the current word. |
Ctrl-X~ |
List the possible username completions of the current word. |
Ctrl-X $ |
List the possible shell variable completions of the current word. |
Ctrl-X@ |
List the possible hostname completions of the current word. |
Ctrl-X! |
List the possible command name completions of the current word. |
Ctrl-X( |
Begin saving characters into the current keyboard macro. |
Ctrl-X) |
Stop saving characters into the current keyboard macro. |
Ctrl-Xe |
Reexecute the last keyboard macro defined. |
Ctrl-X Ctrl-R |
Read in the contents of the readline initialization file. |
Ctrl-X Ctrl-V |
Display version information on this instance of bash. |
Ctrl-Y |
Retrieve (yank) last item killed. |
Delete |
Delete one character backward. |
Ctrl-[ |
Same as Esc (most keyboards). |
Esc-B |
Move one word backward. |
Esc-C |
Change word after point to all capital letters. |
Esc-D |
Delete one word forward. |
Esc-F |
Move one word forward. |
Esc-L |
Change word after point to all lowercase letters. |
Esc-N |
Nonincremental forward search. |
Esc-P |
Nonincremental reverse search. |
Esc-R |
Undo all the changes made to this line. |
Esc-T |
Transpose two words. |
Esc-U |
Change word after point to all uppercase letters. |
Esc-Ctrl-E |
Perform shell alias, history, and word expansion on the line. |
Esc-Ctrl-H |
Delete one word backward. |
Esc-Ctrl-Y |
Insert the first argument to the previous command (usually the second word) at point. |
Esc-Delete |
Delete one word backward. |
Esc-^ |
Perform history expansion on the line. |
Esc-< |
Move to first line of history file. |
Esc-> |
Move to last line of history file. |
Esc-. |
Insert last word in previous command line after point. |
Esc-_ |
Same as above. |
Tab |
Attempt filename completion on current word. |
Esc-? |
List the possible completions of the text before point. |
Esc-/ |
Attempt filename completion on current word. |
Esc-~ |
Attempt username completion on current word. |
Esc-$ |
Attempt variable completion on current word. |
Esc-@ |
Attempt hostname completion on current word. |
Esc-! |
Attempt command name completion on current word. |
Esc-Tab |
Attempt completion from text in the command history. |
Esc-~ |
Attempt tilde expansion on the current word. |
Esc-\ |
Delete all the spaces and tabs around point. |
Esc-* |
Insert all of the completions that would be generated by Esc-= before point. |
Esc-= |
List the possible completions before point. |
Esc-{ |
Attempt filename completion and return the list to the shell enclosed within braces. |
The material in this section also appears in Learning the bash Shell, 3rd Edition, by Cameron Newham (O’Reilly).
Table A-24 shows a complete list of readline vi control mode commands.
| Command | Meaning |
|---|---|
|
Move left one character. |
|
Move right one character. |
|
Move right one word. |
|
Move left one word. |
|
Move to beginning of next nonblank word. |
|
Move to beginning of preceding nonblank word. |
|
Move to end of current word. |
|
Move to end of current nonblank word. |
|
Move to beginning of line. |
|
Repeat the last |
|
Move to first nonblank character in line. |
|
Move to end of line. |
|
Insert text before current character. |
|
Insert text after current character. |
|
Insert text at beginning of line. |
|
Insert text at end of line. |
|
Overwrite existing text. |
|
Delete one character backward. |
|
Delete one character forward. |
|
Delete one word backward. |
|
Delete one word forward. |
|
Delete one nonblank word backward. |
|
Delete one nonblank word forward. |
|
Delete to end of line. |
|
Delete to beginning of line. |
|
Equivalent to |
|
Equivalent to |
|
Equivalent to |
|
Equivalent to |
|
Equivalent to |
|
Equivalent to |
|
Move backward one line. |
|
Move forward one line. |
|
Move to line given by repeat count. |
/ |
Search forward for |
|
Search backward for |
|
Repeat search forward. |
|
Repeat search backward. |
|
Move right to next occurrence of |
|
Move left to previous occurrence of |
|
Move right to next occurrence of |
|
Move left to previous occurrence of |
|
Redo last character finding command. |
|
Redo last character finding command in opposite direction. |
|
Do filename completion. |
|
Do wildcard expansion (onto command line). |
|
Do wildcard expansion (as printed list). |
|
Invert (twiddle) case of current character(s). |
|
Append last word of previous command, enter input mode. |
Ctrl-L |
Start a new line and redraw the current line on it. |
|
Prepend |
Many of our favorite computer books have an ASCII chart (Table A-25). Even in the era of GUIs and web servers, you may be surprised to find that you still need to look up a character every now and then. It’s certainly useful when working with tr or finding some special sequence of escape characters.
| Int | Octal | Hex | ASCII |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|