Appendix A. Reference Lists

This appendix collects many tables of values, settings, operators, commands, variables, and more in one place for easy reference.

bash Invocation

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.

Table A-1. Command-line options to bash
Option Meaning

-c string

Commands are read from string, if present. Any arguments after string are interpreted as positional parameters, starting with $0.

-D

A list of all double-quoted strings preceded by $ is written to standard output. These are the strings that are subject to language translation when the current locale is not C or POSIX. This also turns on the -n option.

-i

Makes the shell an interactive shell. Ignores signals TERM, INT, and QUIT. With job control in effect, TTIN, TTOU, and TSTP are also ignored.

-l

Makes bash act as if it were invoked as a login shell.

-o option

Takes the same arguments as set -o (see “set Options”).

-O,
+O shopt-option

shopt-option is one of the shell options accepted by the shopt builtin. If shopt-option is present, -O sets the value of that option; +O unsets it. If shopt-option is not supplied, the names and values of the shell options accepted by shopt are written to standard output. If the invocation option is +O, the output is displayed in a format that may be reused as input.

-s

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).

-r

Makes the shell a restricted shell.

-v

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. -- is synonymous with -.

--debugger

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.

--dump-strings

Does the same as -D.

--dump-po-strings

Does the same as -D, but the output is in the GNU gettext portable object (.po) file format.

--help

Displays a usage message and exits.

--login

Makes bash act as if it were invoked as a login shell. Same as -l.

--noediting

Does not use the GNU readline library to read command lines if the shell is interactive.

--noprofile

Does not read the startup file /etc/profile or any of the personal initialization files.

--norc

Does not read the initialization file ~/.bashrc if the shell is interactive. This is on by default if the shell is invoked as sh.

--posix

Changes the behavior of bash to follow the POSIX standard more closely where the default operation of bash is different.

--rcfile file, --init-file file

Executes commands read from file instead of the initialization file ~/.bashrc, if the shell is interactive.

--restricted

Equivalent to -r.

--verbose

Equivalent to -v.

--version

Shows the version number of this instance of bash and then exits.

Prompt String Customizations

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+.

See http://bit.ly/2wlpQHf.

Table A-2. Prompt string format codes
Command Meaning

\a

The ASCII bell character (007).

\A

The current time in 24-hour HH:MM format.

\d

The date in “Weekday Month Day” format.

\D {format}

The format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation. The braces are required.

\e

The ASCII escape character (033).

\H

The hostname.

\h

The hostname up to the first ..

\j

The number of jobs currently managed by the shell.

\l

The basename of the shell’s terminal device name.

\n

A carriage return and line feed.

\r

A carriage return.

\s

The name of the shell.

\T

The current time in 12-hour HH:MM:SS format.

\t

The current time in 24-hour HH:MM:SS format.

\@

The current time in 12-hour a.m./p.m. format.

\u

The username of the current user.

\v

The version of bash (e.g., 2.00).

\V

The release of bash (the version and patch level; e.g., 3.00.0).

\w

The current working directory, with $HOME abbreviated with a tilde (uses the $PROMPT_DIRTRIM variable).

\W

The basename of $PWD, with $HOME abbreviated with a tilde.

\#

The command number of the current command.

\!

The history number of the current command.

\$

If the effective UID is 0, a #; otherwise, a $.

\nnn

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.

ANSI Color Escape Sequences

Table A-3 shows the ANSI color escape sequences.

Table A-3. 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

Builtin Commands

Table A-4 lists the builtin commands in current versions of bash (see http://bit.ly/2wlut4o).

Table A-4. Builtin commands
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 for, select, while, or until loop.

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 name according to the options, or for the currently executing completion if no names are supplied.

continue

Skip to the next iteration of the surrounding for, select, while, or until loop.

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 -n) builtin shell commands.

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 arguments to standard output under the control of the format.

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.

bash Reserved Words

Table A-5 lists the reserved words in current versions of bash (see http://bit.ly/2wlxEZO).

Table A-5. bash reserved words
Command Summary

!

Logical NOT of a command’s exit status.

[[ ]]

Return a status of 0 or 1 depending on the evaluation of the conditional expression.

(( ))

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.

case

Multiway conditional construct.

do

Part of a for, select, while, or until looping construct.

done

Part of a for, select, while, or until looping construct.

elif

Part of an if construct.

else

Part of an if construct.

esac

End of a case construct.

fi

End of an if construct.

for

Looping construct.

function

Define a function.

if

Conditional construct.

in

Part of a case construct.

select

Menu-generation construct.

then

Part of an if construct.

time

Run the command pipeline and print execution times. The format of the output can be controlled with TIMEFORMAT.

until

Looping construct.

while

Looping construct.

Builtin Shell Variables

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.

See http://bit.ly/2v2Xxcr.

Table A-6. Builtin shell environment variables
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 $IFS (e.g., "arg1 arg2 arg3") or with no separator if $IFS is null.

@

R

Each of the positional parameters given to the current script or function, given as a list of double-quoted strings (e.g., "arg1" "arg2" "arg3").

#

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.

0

R

The name of the shell or shell script.

_

R

The last argument to the previous command.

auto_resume

Controls how job control works (values are exact, substring, or something other than those keywords).

BASH

The full pathname used to invoke this instance of bash.

BASHOPTS

L

A colon-separated list of enabled shell options.

BASHPID

Expands to the process ID of the current bash process.

BASH_ALIASES

A

An associative array variable whose members correspond to the internal list of aliases as maintained by the alias builtin.

BASH_ARGC

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.

BASH_ARGV

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.

BASH_CMDS

An associative array variable whose members correspond to the internal hash table of commands as maintained by the hash builtin.

BASH_COMMAND

The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap.

BASH_ENV

The name of a file to run as the environment file when the shell is invoked.

BASH_EXECUTION_STRING

The command argument to the -c invocation option.

BASH_LINENO

A

An array whose members are the line numbers in source files corresponding to each member of @var{FUNCNAME}. ${BASHLINENO[$i]} is the line number in the source file where ${FUNCNAME[$i + 1]} was called. The corresponding source filename is ${BASHSOURCE[$i + 1]}.

BASH_LOADABLES_PATH

L

A colon-separated list of directories in which the shell looks for dynamically loadable builtins specified by the enable command.

BASH_REMATCH

AR

An array whose members are assigned by the =~ binary operator to the [[ conditional command. The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the nth parenthesized subexpression.

BASH_SOURCE

A

An array containing the source filenames corresponding to the elements in the $FUNCNAME array variable.

BASH_SUBSHELL

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.

BASH_VERSINFO

AR

Version information for this instance of bash. Each element of the array holds parts of the version number.

BASH_VERSION

The version number of this instance of bash.

BASH_XTRACEFD

If set to an integer corresponding to a valid file descriptor, bash will write the trace output generated when set -x is enabled to that file descriptor.

CDPATH

L

A list of directories for the cd command to search.

CHILD_MAX

The number of exited child status values for the shell to remember.

COLUMNS

Used by the select command to determine the terminal width when printing selection lists.

COMP_CWORD

An index into ${COMPWORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities.

COMP_LINE

The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion facilities.

COMP_POINT

The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the current command, the value of this variable is equal to ${#COMPLINE}. This variable is available only in shell functions and external commands invoked by the programmable completion facilities.

COMP_WORDS

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.

COMPREPLY

A

The possible completions generated by a shell function invoked by the programmable completion facilities.

COMPREPLY

A

An array variable from which bash reads the possible completions generated by a shell function invoked by the programmable completion facilities.

COMP_KEY

The key (or final key of a key sequence) used to invoke the current completion function.

COMP_TYPE

An integer value corresponding to the type of completion attempted that caused a completion function to be called.

COPROC

An array variable created to hold the file descriptors for output from and input to an unnamed coprocess.

DIRSTACK

ARU

The current contents of the directory stack.

echo-control-characters

When set to on, on operating systems that indicate they support it, readline echoes a character corresponding to a signal generated from the keyboard.

editing-mode

Controls which default set of key bindings is used.

EMACS

If bash finds this variable in the environment when the shell starts with the value t, it assumes that the shell is running in an Emacs shell buffer and disables line editing.

ENV

Similar to BASH_ENV; used when the shell is invoked in POSIX mode.

EUID

R

The effective user ID of the current user.

EXECIGNORE

L

A colon-separated list of shell patterns defining the list of filenames to be ignored by command search using PATH.

FCEDIT

The default editor for the fc command.

FIGNORE

L

A list of names to ignore when doing filename completion.

FUNCNAME

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.

FUNCNEST

If set to a numeric value greater than 0, defines a maximum function nesting level.

GLOBIGNORE

L

A list of patterns defining filenames to ignore during pathname expansion.

GROUPS

AR

An array containing a list of groups of which the current user is a member.

histchars

Specifies what to use as the history control characters. Normally set to the string !^#.

HISTCMD

U

The history number of the current command.

HISTCONTROL

L

A list of patterns, separated by colons (:), which can have the following values: ignorespace: (lines beginning with a space are not entered into the history list), ignoredups: (lines matching the last history line are not saved in the history list),), erasedups: (all previous lines matching the current line are removed from the history list before the line is saved), or ignoreboth: (enables both ignorespace and ignoredups).

HISTFILE

The name of the command history file.

HISTFILESIZE

The maximum number of lines to keep in the history file.

HISTIGNORE

A list of patterns used to determine what should be retained in the history list.

HISTSIZE

The maximum number of commands to keep in the command history.

HISTTIMEFORMAT

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.

HOME

The home (login) directory.

HOSTFILE

The file to be used for hostname completion.

HOSTNAME

The name of the current host.

HOSTTYPE

The type of machine bash is running on.

IFS

The internal field separator: a list of characters that act as word separators. Normally set to space, tab, and newline.

IGNOREEOF

The number of EOF characters that can be received before exiting an interactive shell.

INPUTRC

The readline startup file.

LANG

Used to determine the locale category for any category where one is not specifically set with a variable starting with LC_.

LC_ALL

Overrides the value of LANG and any other LC_ variable specifying a locale category.

LC_COLLATE

Determines the collation order used when sorting the results of pathname expansion.

LC_CTYPE

Determines the interpretation of characters and the behavior of character classes within pathname expansion and pattern matching.

LC_MESSAGES

Determines the locale used to translate double-quoted strings preceded by a $.

LC_NUMERIC

Determines the locale category used for number formatting.

LC_TIME

Determines the locale category used for date and time formatting.

LINENO

U

The number of the line that just ran in a script or function.

LINES

Used by the select command to determine the column length for printing selection lists.

MACHTYPE

A string describing the system on which bash is executing.

MAIL

The name of the file to check for new mail.

MAILCHECK

How often (in seconds) to check for new mail.

MAILPATH

L

A list of filenames to check for new mail, if MAIL is not set.

MAPFILE

A

An array variable created to hold the text read by the mapfile builtin when no variable name is supplied.

mark-directories

If set to on, completed directory names have a slash appended.

OLDPWD

The previous working directory.

OPTARG

The value of the last option argument processed by getopts.

OPTERR

If set to 1, display error messages from getopts.

OPTIND

The index of the last option argument processed by getopts.

OSTYPE

The operating system on which bash is executing.

PATH

L

The search path for commands.

PIPESTATUS

A

An array variable containing a list of exit status values from the processes in the most recently executed foreground pipeline.

POSIXLY_CORRECT

If this is set in the environment when bash starts, the shell enters POSIX mode before reading the startup files, as if the --posix invocation option had been supplied. If it is set while the shell is running, bash enables POSIX mode, as if the command set -o posix had been executed.

PPID

R

The process ID of the shell’s parent process.

PROMPT_COMMAND

The value is executed as a command before the primary prompt is issued.

PROMPT_DIRTRIM

If set to a number greater than 0, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes.

PS0

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.

PS1

The primary command prompt string.

PS2

The prompt string for line continuations.

PS3

The prompt string for the select command.

PS4

The prompt string for the xtrace option.

PPID

R

The process ID of the parent process.

PWD

The current working directory as set by the cd builtin.

RANDOM

U

When referenced, generates a pseudorandom integer between 0 and 32,767.

READLINE_LINE

The contents of the readline line buffer, for use with bind -x.

READLINE_POINT

The position of the insertion point in the readline line buffer, for use with bind -x.

REPLY

The user’s response to the select command; also, the result of the read command if no variable names are given.

SECONDS

U

The number of seconds since the shell was started.

SHELL

The full pathname of the shell.

SHELLOPTS

LR

A colon-separated list of enabled shell options.

SHLVL

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.

TEXTDOMAIN

Indicates the location of the message catalog files if not using LC_MESSAGES.

TEXTDOMAINDIR

Indicates the location of the message catalog files if using TEXTDOMAIN.

TIMEFORMAT

Specifies the format for the output from using the time reserved word on a command pipeline.

TMOUT

If set to a positive integer, the number of seconds after which the shell automatically terminates if no input is received.

TMPDIR

If set, the name of the directory in which bash creates temporary files for the shell’s use.

UID

R

The numeric real user ID of the current user.

set Options

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.

Table A-7. set options
Option Full name (-o) Meaning

-a

allexport

Export all subsequently defined or modified variables.

-B

braceexpand

Perform brace expansion. This is on by default.

-b

notify

Report the status of terminating background jobs immediately.

-C

noclobber

Prevent output redirection using >, >&, and <> from overwriting existing files.

-E

errtrace

If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment.

-e

errexit

Exit the shell when a simple command exits with nonzero status. A simple command is a command not part of a while, until, or if; nor part of a && or || list; nor a command whose return value is inverted by !.

emacs

Use an Emacs-style line editing interface. This also affects the editing interface used for read -e.

-f

noglob

Disable filename expansion (globbing).

-H

histexpand

Enable !-style history substitution. This option is on by default for interactive shells.

history

Enable command history. On by default in interactive shells.

-h

hashall

Locate and remember (hash) commands as they are looked up for execution. This option is enabled by default.

ignoreeof

Prevent an interactive shell from exiting upon reading EOF (Ctrl-D).

-k

keyword

All arguments in the form of assignment statements are placed in the environment for a command, not just those that precede the command name.

-m

monitor

Enable job control. On by default in interactive shells.

-n

noexec

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.

-P

physical

If set, do not resolve symbolic links when performing commands such as cd that change the current directory.

-p

privileged

Turn on privileged mode.

pipefail

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.

posix

Change the behavior of bash where the default operation differs from the POSIX standard to match the standard.

-T

functrace

If set, any traps on DEBUG and RETURN are inherited by shell functions, command substitutions, and commands executed in a subshell environment.

-t

onecmd

Exit after reading and executing one command.

-u

nounset

Treat unset variables and parameters other than the special parameters @ or * as an error (not null) when performing parameter expansion.

-v

verbose

Print shell input lines before running them.

vi

Use vi-style command-line editing.

-x

xtrace

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. -x and -v are turned off. If there are no remaining arguments to set, the positional arguments remain unchanged.

shopt Options

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.

Table A-8. shopt options
Option Meaning if set

autocd

A command name that is the name of a directory is executed as if it were the argument to the cd command.

cdable_vars

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.

cdspell

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.

checkhash

Commands found in the hash table are checked for existence before being executed, and nonexistence forces a $PATH search.

checkjobs

bash lists the status of any stopped and running jobs before exiting an interactive shell.

checkwinsize

bash checks the window size after each command and, if necessary, updates the values of LINES and COLUMNS.

cmdhist

bash attempts to save all lines of a multiline command in a single history entry.

compat32

bash changes its behavior to that of version 3.2 with respect to locale-specific string comparison when using certain commands and operators.

compat40

bash changes its behavior to that of version 4.0 with respect to locale-specific string comparison when using certain commands and operators.

compat41

bash, when in POSIX mode, treats a single quote in a double-quoted parameter expansion as a special character.

compat42

bash does not process the replacement string in the pattern substitution word expansion using quote removal.

compat43

bash changes its behavior to that of version 4.3 with respect to certain operations.

complete_fullquote

bash quotes all shell metacharacters in filenames and directory names when performing completion.

direxpand

bash replaces directory names with the results of word expansion when performing filename completion.

dirspell

bash attempts spelling correction on directory names during word completion if the directory name initially supplied does not exist.

dotglob

bash includes filenames beginning with a dot in the results of filename expansion.

execfail

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.

expand_aliases

Aliases are expanded.

extdebug

Behavior intended for use by debuggers is enabled. For example, the -F option of declare displays the source filename and line number corresponding to each function name supplied as an argument; if the command run by the DEBUG trap returns a nonzero value, the next command is skipped and not executed; and if the command run by the DEBUG trap returns a value of 2, and the shell is executing in a subroutine, a call to return is simulated.

extglob

Extended pattern-matching features are enabled.

extquote

If set, $string and $"string" quoting is performed within ${parameter} expansions enclosed in double quotes.

failglob

Patterns that fail to match filenames during pathname expansion result in an expansion error.

force_fignore

The suffixes specified by the $FIGNORE shell variable cause words to be ignored when performing word completion even if the ignored words are the only possible completions.

globasciiranges

Range expressions used in pattern-matching bracket expressions behave as if in the traditional C locale when performing comparisons.

globstar

The pattern ** used in a filename expansion context will match all files and zero or more directories and subdirectories.

gnu_errfmt

Shell error messages are written in the standard GNU error message format.

histappend

The history list is appended to the file named by the value of the variable $HISTFILE when the shell exits, rather than overwriting the file.

histreedit

If readline is being used, the opportunity is given for reediting a failed history substitution.

histverify

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.

hostcomplete

If readline is being used, an attempt will be made to perform hostname completion when a word beginning with @ is being completed.

huponexit

bash will send a SIGHUP signal to all jobs when an interactive login shell exits.

inherit_errexit

Command substitution inherits the value of the errexit option, instead of unsetting it in the subshell environment.

interactive_comments

Allows a word beginning with # and all subsequent characters on the line to be ignored in an interactive shell.

lastpipe

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.

lithist

If the cmdhist option is enabled, multiline commands are saved to the history with embedded newlines rather than using semicolon separators where possible.

login_shell

bash was started as a login shell. This is a read-only value.

mailwarn

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.

no_empty_cmd_completion

If readline is being used, no attempt will be made to search the $PATH for possible completions when completion is attempted on an empty line.

nocaseglob

bash matches filenames in a case-insensitive fashion when performing pathname expansion.

nocasematch

bash matches patterns in a case-insensitive fashion when performing certain operations.

nullglob

Causes patterns that match no files to expand to null strings rather than to themselves.

progcomp

Programmable completion facilities are enabled. Default is on.

promptvars

Prompt strings undergo variable and parameter expansion after being expanded.

restricted_shell

The shell was started in restricted mode. This value cannot be changed.

shift_verbose

The shift builtin will print an error if it has shifted past the last positional parameter.

sourcepath

The source builtin will use the value of $PATH to find the directory containing the file supplied as an argument.

xpg_echo

echo expands backslash escape sequences by default.

Test Operators

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.

See http://bit.ly/2wloyMK.

Table A-9. Test operators
Operator True if

-a file

True if file exists; same as -e

-b file

True if file exists and is a block device file

-c file

True if file exists and is a character device file

-d file

True if file exists and is a directory

-e file

True if file exists; same as -a

-f file

True if file exists and is a regular file

-g file

True if file exists and has its setgid bit set

-G file

True if file exists and is owned by the effective group ID

-h file

True if file exists and is a symbolic link; same as -L

-k file

True if file exists and has its sticky bit set

-L file

True if file exists and is a symbolic link; same as -h

-n string

True if the length of string is nonzero

-N file

True if file was modified since it was last read

-O file

True if file exists and is owned by the effective user ID

-p file

True if file exists and is a pipe or named pipe (FIFO file)

-r file

True if file exists and is readable

-s file

True if file exists and is not empty

-S file

True if file exists and is a socket

-t fd

True if file descriptor fd is open and refers to a terminal.

-u file

True if file exists and has its setuid bit set

-w file

True if file exists and is writable

-x file

True if file exists and is executable, or file is a directory that can be searched

-z string

True if the length of string is zero

file1 -ef file2

True if file1 and file2 refer to the same device and inode numbers

file1 -nt file2

True if file1’s modification date is newer than file2’s, or if file1 exists and file2 does not

file1 -ot file2

True if file1’s modification date is older than file2’s, or if file2 exists and file1 does not

string1 = string2

True if string1 equals string2 (POSIX version)

string1 == string2

True if string1 equals string2

string1 != string2

True if the strings are not equal

string1 < string2

True if string1 sorts before string2 lexicographically

string1 > string2

True if string1 sorts after string2 lexicographically

string1 =~ regexp

True if string1 matches the extended regular expression regexpa

exprA -eq exprB

True if arithmetic expressions exprA and exprB are equal

exprA -ne exprB

True if arithmetic expressions exprA and exprB are not equal

exprA -lt exprB

True if exprA is less than exprB

exprA -le exprB

True if exprA is less than or equal to exprB

exprA -gt exprB

True if exprA is greater than exprB

exprA -ge exprB

True if exprA is greater than or equal to exprB

exprA -a exprB

True if exprA is true and exprB is true

exprA -o exprB

True if exprA is true or exprB is true

a Only available in bash version 3.0 and later. May only be used inside [[ ]].

I/O Redirection

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.

See http://bit.ly/2xfqrqA.

Table A-10. Input/output redirection
Redirector Function

cmd1 | cmd2

Pipe; send standard output of cmd1 as standard input to cmd2.

cmd1 |& cmd2

Pipe; send standard output and standard error of cmd1 as standard input to cmd2 (bash 4.0 or newer).

> file

Direct standard output to file.

< file

Take standard input from file.

>> file

Direct standard output to file; append to file if it already exists.

>| file

Force standard output to file even if noclobber is set.

n>| file

Force output to file from file descriptor n even if noclobber is set.

<> file

Use file as both standard input and standard output.

&> file

Direct standard output and standard error to file.

&>> file

Direct standard output and standard error to file; append to file if it already exists (bash 4.0 or newer).

n<> file

Use file as both input and output for file descriptor n.

<< label

Here-document.

<<< word

Here-string.

n> file

Direct file descriptor n to file.

n< file

Take file descriptor n from file.

n>> file

Direct file descriptor n to file; append to file if it already exists.

n>&

Duplicate standard output to file descriptor n.

n<&

Duplicate standard input from file descriptor n.

n>&m

File descriptor n is made to be a copy of the output file descriptor m.

n<&m

File descriptor n is made to be a copy of the input file descriptor m.

&>file

Direct standard output and standard error to file.

<&-

Close the standard input.

>&-

Close the standard output.

n>&-

Close the output from file descriptor n.

n<&-

Close the input from file descriptor n.

n>&word

If n is not specified, the standard output (file descriptor 1) is used; if the digits in word do not specify a file descriptor open for output, a redirection error occurs. As a special case, if n is omitted, and word does not expand to one or more digits, the standard output and standard error are redirected as described previously.

n<&word

If word expands to one or more digits, the file descriptor denoted by n is made to be a copy of that file descriptor; if the digits in word do not specify a file descriptor open for input, a redirection error occurs. If word evaluates to -, file descriptor n is closed; if n is not specified, the standard input (file descriptor 0) is used.

n>&digit-

Moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1) if n is not specified.

n<&digit-

Moves the file descriptor digit to file descriptor n, or the standard input (file descriptor 0) if n is not specified; digit is closed after being duplicated to n.

echo Options and Escape Sequences

echo accepts three arguments (see Table A-11).

Table A-11. echo options
Option Function

-e

Turns on the interpretation of backslash-escaped characters

-E

Turns off the interpretation of backslash-escaped characters on systems where this mode is the default

-n

Omits the final newline (same as the \c escape sequence; see Table A-12)

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.

See http://bit.ly/2ii87KI.

Table A-12. echo escape sequences
Sequence Character printed

\a

Alert or Ctrl-G (bell)

\b

Backspace or Ctrl-H

\c

Suppress further output

\e

Escape character (same as \E)

\E

Escape character

\f

Form feed or Ctrl-L

\n

Newline (not at end of command) or Ctrl-J

\r

Return (Enter) or Ctrl-M

\t

Tab or Ctrl-I

\v

Vertical tab or Ctrl-K

\\

Single backslash

\0nnn

The eight-bit character whose value is the octal (base-8) value nnn (zero to three octal digits)

\nnn

Same as \0nnn

\xHH

The eight-bit character whose value is the hexadecimal (base-16) value HH (one or two hex digits)

\uHHHH

The Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits)

\UHHHHHHHH

The Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits)

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.

printf

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.

See http://bit.ly/2uUYkjy.

Table A-13. printf format specifiers
Format character Meaning

%b

Causes printf to expand backslash escape sequences in the corresponding argument in the same way as echo -e

%c

ASCII character (prints first character of corresponding argument)

%d, %i

Decimal (base 10) integer

%e

Floating-point format [-]d.precisione[+-]dd)—see the text after the table for the meaning of precision

%E

Floating-point format ([-]d.precisionE[+-]dd)

%f

Floating-point format ([-]ddd.precision)

%g

%e or %f conversion, whichever is shorter, with trailing zeros removed

%G

%E or %f conversion, whichever is shortest, with trailing zeros removed

%o

Unsigned octal value

%q

Causes printf to output the corresponding argument in a format that can be reused as shell input

%s

String

%u

Unsigned decimal value

%x

Unsigned hexadecimal number; uses a-f for 10 to 15

%X

Unsigned hexadecimal number; uses A-F for 10 to 15

%%

Literal %

%(datefmt)T

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.

Table A-14. Meaning of “precision” based on printf format specifier
Format What “precision” means

%d, %I, %o, %u, %x, %X

The minimum number of digits to print. When the value has fewer digits, it is padded with leading zeros. The default precision is 1.

%e, %E

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.

%f

The number of digits to the right of the decimal point.

%g, %G

The maximum number of significant digits.

%s

The maximum number of characters to print.

%b

[POSIX shell—may be nonportable to other versions of printf.] When used instead of %s, expands echo-style escape sequences in the argument string (see Table A-15).

%q

[POSIX shell—may be nonportable to other versions of printf.] When used instead of %s, prints the string argument in such a way that it can be used for shell input.

%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.

Table A-15. printf escape sequences
Escape sequence Meaning

\e

Escape character

\a

Bell character

\b

Backspace character

\f

Form feed character

\n

Newline character

\r

Carriage return character

\t

Tab character

\v

Vertical tab character

\'

Single-quote character

\"

Double-quote character

\\

Backslash character

\nnn

8-bit character whose ASCII value is the 1-, 2-, or 3-digit octal number nnn

\xHH

8-bit character whose ASCII value is the 1- or 2-digit hexadecimal number HH

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.

Table A-16. printf flags
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: %o has a preceding 0; %x and %X are prefixed with 0x and 0X, respectively; %e, %E, and %f always have a decimal point in the result; and %g and %G do not have trailing zeros removed.

0

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 %i, %d, %u, %f, %F, %g, or %G (although this is POSIX, it’s still not always implemented).

Examples

These examples for printf use some shell variables, assigned as follows in Table A-17:

PI=3.141592653589
Table A-17. printf examples
printf statement Result Comment

printf '%f\n' $PI

3.141593

Note the default rounding.

# not what you want printf '%f.5\n' $PI

3.141593.5

A common mistake—the format specifier should be on the other side of the %f; since it isn’t, the .5 is just appended like any text.

printf '%.5f\n' $PI

3.14159

Gives five places to the right of the decimal point.

printf '%+.2f\n' $PI

+3.14

Leading + sign, only two digits to the right of the decimal point.

printf '[%.4s]\n' s string

[s]

[stri]

Truncates to four characters; with only one character, we get only one-character-wide output. Note reuse of format string.

printf '[%4s]\n' s string

[ s]

[string]

Assures us of a minimum four-character field width, right-justified; doesn’t truncate, though.

printf '[%-4.4s]\n' s string

[s ]

[stri]

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...
Warning

It took a few bash releases for %(datefmt)T behavior to stabilize! Sometimes you can omit the -1 argument and sometimes you can’t, depending on which version of bash you have and what you’re doing. For maximum portability, do not omit the argument.

Date and Time String Formatting with strftime

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.

Table A-18. strftime format codes
Format Description

%%

A literal %.

%a

The locale’s abbreviated weekday name (Sun..Sat).

%A

The locale’s full weekday name (Sunday..Saturday).

%B

The locale’s full month name (January..December).

%b

The locale’s abbreviated month name (Jan..Dec). See also %h.

%c

The locale’s default/preferred date and time representation.

%C

The century (a year divided by 100 and truncated to an integer) as a decimal number (00..99).

%d

The day of the month as a decimal number (01..31).

%D

The date in the format %m/%d/%y (MM/DD/YY). Note that the United States uses MM/DD/YY while everyone else uses DD/MM/YY, so this format is ambiguous and should be avoided. Use %F instead, since it’s a recognized standard and it sorts well.

%e

The day of the month as a blank-padded decimal number ( 1..31).

%F

The date in the format %Y-%m-%d (the ISO 8601 date format CCYY-MM-DD, except when it’s the full month name, as on HP-UX).

%g

The two-digit year corresponding to the %V week number (YY).

%G

The four-digit year corresponding to the %V week number (CCYY).

%H

The hour (24-hour clock) as a decimal number (00..23).

%h

The locale’s abbreviated month name (Jan..Dec). See also %b.

%I

The hour (12-hour clock) as a decimal number (01..12).

%j

The day of the year as a decimal number (001..366).

%k

The hour (24-hour clock) as a blank-padded decimal number ( 0..23).

%l

The hour (12-hour clock) as a blank-padded decimal number ( 1..12).

%m

The month as a decimal number (01..12).

%M

The minute as a decimal number (00..59).

%n

A literal newline.

%N

Nanoseconds (000000000..999999999). [GNU]

%p

The locale’s equivalent of either “AM” or “PM”.

%P

The locale’s equivalent of either “am” or “pm”. [GNU]

%r

The locale’s representation of 12-hour clock time using AM/PM notation (HH:MM:SS AM/PM).

%R

The time in the format %H:%M (HH:MM).

%s

The number of seconds since the epoch, UTC (January 1, 1970 at 00:00:00).

%S

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.

%t

A literal tab.

%T

The time in the format %H:%M:%S (HH:MM:SS).

%u

The weekday (Monday as the first day of the week) as a decimal number (1..7).

%U

The week number of the year (Sunday as the first day of the week) as a decimal number (00..53).

%v

The date in the format %e-%b-%Y (D-MMM-CCYY). [Not standard]

%V

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 %G conversion specification.

%w

The weekday (Sunday as the first day of the week) as a decimal number (0..6).

%W

The week number of the year (Monday as the first day of the week) as a decimal number (00..53).

%x

The locale’s appropriate date representation.

%X

The locale’s appropriate time representation.

%y

The year without the century as a decimal number (00..99).

%Y

The year with the century as a decimal number.

%z

The offset from UTC in the ISO 8601 format [-]hhmm.

%Z

The time zone name.

Pattern-Matching Characters

Table A-19 lists the pattern-matching characters in bash. The material in this section is adapted from the Bash Reference Manual.

Table A-19. Pattern-matching characters
Character Meaning

*

Matches any string, including the null string

?

Matches any single character

[]

Matches any one of the enclosed characters

[!] or [^]

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.

extglob Extended Pattern-Matching Operators

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.

Table A-20. extglob extended pattern-matching operators
Grouping Meaning

@()

Only one occurrence

–0—()

Zero or more occurrences

–0—()

One or more occurrences

?()

Zero or one occurrence

!()

No occurrences of this, but anything else

tr Escape Sequences

Table A-21 lists the tr escape sequences.

Table A-21. tr escape sequences
Sequence Meaning

\ooo

Character with octal value ooo (one to three octal digits)

\\

A backslash character (i.e., escapes the backslash itself)

\a

“Audible” bell, the ASCII BEL character (since b was taken for backspace)

\b

Backspace

\f

Form feed

\n

Newline

\r

Return

\t

Tab (sometimes called a horizontal tab)

\v

Vertical tab

readline Init File Syntax

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).

See http://bit.ly/2wlB9iV.

Table A-22. readline configuration settings
Variable Description

bell-style

Controls what happens when readline wants to ring the terminal bell. If set to none, readline never rings the bell. If set to visible, readline uses a visible bell if one is available. If set to audible (the default), readline attempts to ring the terminal’s bell.

bind-tty-special-chars

If set to on, readline attempts to bind the control characters treated specially by the kernel’s terminal driver to their readline equivalents. The default is on.

blink-matching-paren

If set to on, readline attempts to briefly move the cursor to an opening parenthesis when a closing parenthesis is inserted. The default is off.

colored-completion-prefix

If set to on, when listing completions, readline displays the common prefix of the set of possible completions using a different color. The color definitions are taken from the value of the LS_COLORS environment variable. The default is off.

colored-stats

If set to on, readline displays possible completions using different colors to indicate their file type. The color definitions are taken from the value of the LS_COLORS environment variable. The default is off.

comment-begin

The string to insert at the beginning of the line when the insert-comment command is executed. The default value is #.

completion-display-width

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 0 will cause matches to be displayed one per line. The default value is -1.

completion-ignore-case

If set to on, readline performs filename matching and completion in a case-insensitive fashion. The default is off.

completion-map-case

If set to on and completion-ignore-case is enabled, readline treats hyphens (-) and underscores (_) as equivalent when performing case-insensitive filename matching and completion.

completion-prefix-display-length

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.

completion-query-items

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 100.

convert-meta

If set to on, readline will convert characters with the eighth bit set to an ASCII key sequence by stripping the eighth bit and prefixing an Esc character, converting them to a meta-prefixed key sequence. The default is on.

disable-completion

If set to on, readline will inhibit word completion. Completion characters will be inserted into the line as if they had been mapped to self-insert. The default is off.

echo-control-characters

When set to on, on operating systems that indicate they support it, readline echoes a character corresponding to a signal generated from the keyboard. The default is on.

editing-mode

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 emacs or vi.

emacs-mode-string

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 \1 and \2 escapes to begin and end sequences of nonprinting characters, which can be used to embed a terminal control sequence into the mode string. The default is @.

enable-bracketed-paste

When set to on, readline will configure the terminal in a way that will enable it to insert each paste into the editing buffer as a single string of characters, instead of treating each character as if it had been read from the keyboard. This can prevent pasted characters from being interpreted as editing commands. The default is off.

enable-keypad

When set to on, readline will try to enable the application keypad when it is called. Some systems need this to enable the arrow keys. The default is off.

enable-meta-key

When set to on, readline will try to enable any meta modifier key the terminal claims to support when it is called. On many terminals, the meta key is used to send eight-bit characters. The default is on.

expand-tilde

If set to on, tilde (~) expansion is performed when readline attempts word completion. The default is off.

history-preserve-point

If set to on, the history code attempts to place the point (the current cursor position) at the same location on each history line retrieved with previous-history or next-history. The default is off.

history-size

The maximum number of history entries to save in the history list. If set to 0, any existing history entries are deleted and no new entries are saved. If set to a value less than zero, the number of history entries is not limited. By default, the number of history entries is not limited. If an attempt is made to set history-size to a nonnumeric value, the maximum number of history entries will be set to 500.

horizontal-scroll-mode

If set to on, the text of the lines being edited will scroll horizontally on a single screen line when they are longer than the width of the screen, instead of wrapping onto a new screen line. The default is off.

input-meta

If set to on, readline will enable eight-bit input (it will not clear the eighth bit in the characters it reads), regardless of what the terminal claims it can support. The default is off. The name meta-flag is a synonym for this variable.

isearch-terminators

The string of characters that should terminate an incremental search without subsequently executing the character as a command. If this variable has not been given a value, the characters Esc and C–J will terminate an incremental search.

keymap

Sets readline’s idea of the current keymap for key binding commands. Acceptable keymap names are emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command, and vi-insert. vi is equivalent to vi-command; emacs is equivalent to emacs-standard. The default value is emacs. The value of the editing-mode variable also affects the default keymap.

keyseq-timeout

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 (rl_instream by default). The value is specified in milliseconds, so a value of 1000 means that readline will wait one second for additional input. If this variable is set to a value less than or equal to zero, or to a nonnumeric value, readline will wait until another key is pressed to decide which key sequence to complete. The default value is 500.

mark-directories

If set to on, completed directory names have a slash appended. The default is on.

mark-modified-lines

If set to on, readline will display an asterisk (*) at the start of history lines that have been modified. The default is off.

mark-symlinked-directories

If set to on, completed names that are symbolic links to directories have a slash appended (subject to the value of mark-directories). The default is off.

match-hidden-files

If set to on, readline will match files whose names begin with a dot (hidden files) when performing filename completion, unless the leading . is supplied by the user in the filename to be completed. The default is on.

menu-complete-display-prefix

If set to on, menu completion displays the common prefix of the list of possible completions (which may be empty) before cycling through the list. The default is off.

output-meta

If set to on, readline will display characters with the eighth bit set directly rather than as a meta-prefixed escape sequence. The default is off.

page-completions

If set to on, readline uses an internal more-like pager to display a screenful of possible completions at a time. The default is on.

print-completions-horizontally

If set to on, readline will display completions with matches sorted horizontally in alphabetical order, rather than down the screen. The default is off.

revert-all-at-newline

If set to on, readline will undo all changes to history lines before returning when accept-line is executed. By default, history lines may be modified and retain individual undo lists across calls to readline. The default is off.

show-all-if-ambiguous

Alters the default behavior of the completion functions. If set to on, words that have more than one possible completion cause the matches to be listed immediately instead of ringing the bell. The default is off.

show-all-if-unmodified

Alters the default behavior of the completion functions in a fashion similar to show-all-if-ambiguous. If set to on, words that have more than one possible completion without any possible partial completion (the possible completions don’t share a common prefix) cause the matches to be listed immediately instead of ringing the bell. The default is off.

show-mode-in-prompt

If set to on, a character is added to the beginning of the prompt indicating the editing mode: emacs, vi-command, or vi-insert. The mode strings are user-settable. The default is off.

skip-completed-text

If set to on, this alters the default completion behavior when inserting a single match into the line. It’s only active when performing completion in the middle of a word. If enabled, readline does not insert characters from the completion that match characters after point in the word being completed, so portions of the word following the cursor are not duplicated. For instance, if this is enabled, attempting completion when the cursor is after the first e in Makefile will result in Makefile rather than Makefilefile, assuming there is a single possible completion. The default is off.

vi-cmd-mode-string

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 \1 and \2 escapes to begin and end sequences of nonprinting characters, which can be used to embed a terminal control sequence into the mode string. The default is (cmd).

vi-ins-mode-string

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 \1 and \2 escapes to begin and end sequences of nonprinting characters, which can be used to embed a terminal control sequence into the mode string. The default is (ins).

visible-stats

If set to on, a character denoting a file’s type is appended to the filename when listing possible completions. The default is off.

Emacs Mode Commands

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.

Table A-23. Emacs 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.

vi Control Mode Commands

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.

Table A-24. vi mode commands
Command Meaning

h

Move left one character.

l

Move right one character.

w

Move right one word.

b

Move left one word.

W

Move to beginning of next nonblank word.

B

Move to beginning of preceding nonblank word.

e

Move to end of current word.

E

Move to end of current nonblank word.

0

Move to beginning of line.

.

Repeat the last a insertion.

^

Move to first nonblank character in line.

$

Move to end of line.

i

Insert text before current character.

a

Insert text after current character.

I

Insert text at beginning of line.

A

Insert text at end of line.

R

Overwrite existing text.

dh

Delete one character backward.

dl

Delete one character forward.

db

Delete one word backward.

dw

Delete one word forward.

dB

Delete one nonblank word backward.

dW

Delete one nonblank word forward.

d$

Delete to end of line.

d0

Delete to beginning of line.

D

Equivalent to d$ (delete to end of line).

dd

Equivalent to 0d$ (delete entire line).

C

Equivalent to c$ (delete to end of line, enter input mode).

cc

Equivalent to 0c$ (delete entire line, enter input mode).

x

Equivalent to dl (delete one character forward).

X

Equivalent to dh (delete one character backward).

k or -

Move backward one line.

j or +

Move forward one line.

G

Move to line given by repeat count.

/string

Search forward for string.

?string

Search backward for string.

n

Repeat search forward.

N

Repeat search backward.

f x

Move right to next occurrence of x.

F x

Move left to previous occurrence of x.

t x

Move right to next occurrence of x, then back one space.

T x

Move left to previous occurrence of x, then forward one space.

;

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 # (comment character) to the line and send it to history.

Table of ASCII Values

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.

Table A-25. ASCII values
Int Octal Hex ASCII

0

000

00

^@

1

001

01

^A

2

002

02

^B

3

003

03

^C

4

004

04

^D

5

005

05

^E

6

006

06

^F

7

007

07

^G

8

010

08

^H

9

011

09

^I

10

012

0a

^J

11

013

0b

^K

12

014

0c

^L

13

015

0d

^M

14

016

0e

^N

15

017

0f

^O

16

020

10

^P

17

021

11

^Q

18

022

12

^R

19

023

13

^S

20

024

14

^T

21

025

15

^U

22

026

16

^V

23

027

17

^W

24

030

18

^X

25

031

19

^Y

26

032

1a

^Z

27

033

1b

^[

28

034

1c

^\

29

035

1d

^]

30

036

1e

^^

31

037

1f

^_

32

040

20

33

041

21

!

34

042

22

"

35

043

23

#

36

044

24

$

37

045

25

%

38

046

26

&

39

047

27

'

40

050

28

(

41

051

29

)

42

052

2a

*

43

053

2b

+

44

054

2c

,

45

055

2d

-

46

056

2e

.

47

057

2f

/

48

060

30

0

49

061

31

1

50

062

32

2

51

063

33

3

52

064

34

4

53

065

35

5

54

066

36

6

55

067

37

7

56

070

38

8

57

071

39

9

58

072

3a

:

59

073

3b

;

60

074

3c

<

61

075

3d

=

62

076

3e

>

63

077

3f

?

64

100

40

@

65

101

41

A

66

102

42

B

67

103

43

C

68

104

44

D

69

105

45

E

70

106

46

F

71

107

47

G

72

110

48

H

73

111

49

I

74

112

4a

J

75

113

4b

K

76

114

4c

L

77

115

4d

M

78

116

4e

N

79

117

4f

O

80

120

50

P

81

121

51

Q

82

122

52

R

83

123

53

S

84

124

54

T

85

125

55

U

86

126

56

V

87

127

57

W

88

130

58

X

89

131

59

Y

90

132

5a

Z

91

133

5b

[

92

134

5c

\

93

135

5d

]

94

136

5e

^

95

137

5f

_

96

140

60

`

97

141

61

a

98

142

62

b

99

143

63

c

100

144

64

d

101

145

65

e

102

146

66

f

103

147

67

g

104

150

68

h

105

151

69

i

106

152

6a

j

107

153

6b

k

108

154

6c

l

109

155

6d

m

110

156

6e

n

111

157

6f

o

112

160

70

p

113

161

71

q

114

162

72

r

115

163

73

s

116

164

74

t

117

165

75

u

118

166

76

v

119

167

77

w

120

170

78

x

121

171

79

y

122

172

7a

z

123

173

7b

{

124

174

7c

|

125

175

7d

}

126

176

7e

~

127

177

7f

^?