Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 95 ยท Advanced Bash

Customizing Bash: Prompts, Completion and Readline

Design your own Bash prompt with PS1 and PROMPT_COMMAND, write programmable tab completion with complete and compgen, and tune keys and history with readline.

You spend hours a day inside your shell, so small improvements pay off every day. Three of them are easy and safe: a prompt that shows what you need to know (where you are, whether the last command failed, which Git branch), tab completion that knows your own scripts, and readline settings that make editing and history pleasant. All three are plain Bash, and none of them needs an external tool.

Most of this is interactive, so you would normally try it in a live terminal. The editors on this page are not interactive, but Bash lets us test the pieces anyway. The expansion ${var@P} prints what a prompt string would look like, and a completion function is an ordinary function that fills an array, so we can call it by hand. That also teaches you how to debug your own setup without opening a new terminal for every change. Before you start editing your real configuration, read Environment, Profiles and Configuration to know where it lives.

The prompt: PS1 and friends

Bash uses four prompt variables:

Variable Shown when Default
PS1 waiting for a command often \u@\h:\w\$
PS2 a command continues on another line >
PS3 a select menu asks for a choice (see case Statements and Menus) #?
PS4 set -x traces a command (see Debugging Shell Scripts) +

PS1 is a string with backslash escapes that Bash replaces each time it prints the prompt:

Escape Meaning
\u, \h, \H user name, short host name, full host name
\w, \W current directory (with ~ for home), or only its last component
\$ $ for a normal user, # for root
\t, \T, \@, \d time (24h, 12h, am/pm), date
\n newline
\j number of background jobs
\!, \# history number, command number
\e the escape character, used for colors
\[ and \] start and end of a non-printing sequence

Because PS1 is only a string, you can preview it without a terminal. Bash 4.4 and newer expand a string as a prompt with ${string@P}. PROMPT_DIRTRIM=1 shortens long directories to their last component:

Bash Previewing prompt strings with @P

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The last line shows the raw bytes: ^[ is the escape character, and [1;32m selects bold green, [0m resets. You normally never see them because the terminal interprets them.

Colors and the [ ] rule

Colors are ANSI escape sequences: \e[ then a code then m. Common codes are 0 (reset), 1 (bold), 31 red, 32 green, 33 yellow, 34 blue, 36 cyan. In a prompt you must wrap every such sequence in \[ and \]:

Terminal
PS1='\[\e[1;32m\]\u@\h\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]\$ '

Those brackets tell readline that the enclosed bytes take no space on screen. Without them, readline miscounts the prompt width, and long commands wrap onto the wrong line, overwrite the prompt, or break history navigation. If your terminal acts up after a prompt change, a missing \[ \] is the first suspect. The sandbox cannot show color, but the preview above proves the sequences are what you meant.

A dynamic prompt: PROMPT_COMMAND

PS1 can contain $(...) command substitutions that run each time, but for anything beyond a one-liner it is cleaner to use PROMPT_COMMAND: Bash runs this code before every prompt, and your function can assemble PS1 from pieces. The usual job list is "show the exit status of the last command, show the Git branch, shorten the path".

The most common mistake is checking $? too late. Every command you run, even local, replaces it, so save it on the very first line:

Bash A prompt function with exit status and branch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Several habits are visible here. The function is small and fast, because it runs before every prompt; do not call slow commands. (Full git status in a huge repository can make each prompt take a second, which is why real prompts read .git/HEAD directly or use a helper such as __git_ps1 from Git's own git-prompt.sh.) The \$ is escaped inside PS1="..." so that the command substitution runs when the prompt is drawn, not once when you assign it. And the status-aware mark gives instant feedback without checking echo $? by hand.

To add your function without removing what other tools put in PROMPT_COMMAND, append:

Terminal
PROMPT_COMMAND="set_prompt${PROMPT_COMMAND:+; $PROMPT_COMMAND}"

A related use is PROMPT_COMMAND='history -a', which appends each command to the history file immediately, so a crash or a second terminal does not lose it.

Programmable tab completion

Press Tab after git ch and Bash completes checkout or lists candidates. That is programmable completion: Bash keeps a table that maps each command name to a rule, and you can add your own. Two builtins do the work:

  • complete registers a rule for a command: complete -W "dev staging production" setenv completes setenv with a fixed word list; complete -F _myfunc mycmd calls a function; complete -p prints the rules; complete -r mycmd removes one.
  • compgen generates matches: compgen -W "alpha beta bravo" -- b prints beta and bravo. It is the building block inside completion functions, and you can use it in a normal script too. Useful options are -W (word list), -f (files), -d (directories), -A function, -A variable and -X (filter pattern).
sequenceDiagram
  participant U as You
  participant R as Readline
  participant B as Bash
  participant F as Your function
  U->>R: types "deploy st" and presses Tab
  R->>B: which rule is registered for "deploy"?
  B->>F: call _deploy with COMP_WORDS and COMP_CWORD set
  F-->>B: fill the COMPREPLY array
  B-->>R: candidate words
  R-->>U: completes the word, or lists the choices

A completion function receives the words typed so far in variables and answers by filling an array.

Inside a completion function Bash sets these variables for you:

Variable Content
COMP_WORDS array of the words on the command line
COMP_CWORD index in COMP_WORDS of the word under the cursor
COMP_LINE the whole line as text
COMP_POINT cursor position in COMP_LINE
COMPREPLY you fill this array with the candidates

Because the function is just code that reads COMP_WORDS and writes COMPREPLY, we can fake the inputs and test it. The deploy command below has subcommands, options that depend on the subcommand, and options that take a value (--env, --config):

Bash A completion function for a deploy command, tested by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Study the cases. With deploy st, compgen -W keeps only words that start with st, in the order of the word list. With --env (note the trailing space), the previous word decides what comes next. The --config case filters files with -X '!*.yml' so that notes.txt is not offered. An unknown subcommand yields no matches, and Bash then falls back to nothing (or to filenames, if you registered the rule with -o default).

A few practical points:

  • Use mapfile -t COMPREPLY < <(compgen ...) (or COMPREPLY=($(compgen ...)) in older scripts). The mapfile form keeps words with special characters intact; always quote "$cur".
  • Options for the rule: complete -o nospace stops the trailing space (useful for --option=), -o filenames adds slashes to directories and escapes special characters, and -o default falls back to normal filename completion when you return nothing. Inside a function, compopt changes these for one call.
  • Where to put the code. For one machine, source the function in ~/.bashrc. The bash-completion package (installed by default on most desktop distributions) loads files lazily: put one named after the command in ~/.local/share/bash-completion/completions/, or /etc/bash_completion.d/ for all users. It also provides helpers such as _init_completion and _filedir that handle --opt=value splitting and directories for you.
  • Many tools generate their own. kubectl completion bash, docker completion bash, gh completion -s bash and others print a script, which you load with source <(tool completion bash).
  • Completion functions run on every Tab press, so they must be fast and silent. Anything printed to standard output, or a slow network call, ruins the experience. Cache slow results in a file.

Readline: editing, history and key bindings

The line editor behind Bash is the readline library. Programs such as python, psql and mysql use it too, so your settings affect all of them. You configure it in ~/.inputrc (or system-wide in /etc/inputrc). Here is a useful, conservative starting point, read-only because it must live in your home directory:

TEXT
# ~/.inputrc
$include /etc/inputrc               # keep the system defaults, then add ours

set completion-ignore-case on       # "doc<Tab>" finds Documents
set show-all-if-ambiguous on        # list choices at once, not after a second Tab
set colored-stats on                # colour the completions like ls does
set mark-symlinked-directories on   # add / after a symlink to a directory
set bell-style none                 # no beep

# type a few letters, then Up/Down searches only matching history lines
"\e[A": history-search-backward
"\e[B": history-search-forward

$include /etc/inputrc matters: a personal ~/.inputrc replaces the system file instead of adding to it, so without that line you lose its default bindings. Apply changes to the current terminal with bind -f ~/.inputrc or the key sequence Ctrl-x Ctrl-r. To see what is bound, run bind -P | grep -i history. A single binding can also be set from a script or .bashrc, for example bind '"\C-l": clear-screen', but only in an interactive shell (in the sandbox it prints a warning that line editing is not enabled).

If you prefer vi keys, set editing-mode vi switches the whole editing model. Everyone benefits from knowing the default Emacs-style keys:

Keys Action
Ctrl-a / Ctrl-e start / end of line
Alt-b / Alt-f back / forward one word
Ctrl-w / Alt-d delete the word before / after the cursor
Ctrl-u / Ctrl-k cut to the start / end of the line
Ctrl-y paste what you cut
Ctrl-r search history backward as you type
Alt-. insert the last argument of the previous command
Ctrl-l clear the screen

History settings

History is configured with variables in ~/.bashrc (again read-only, because it needs a real shell session):

Terminal
HISTSIZE=10000                          # commands kept in memory
HISTFILESIZE=20000                      # lines kept in ~/.bash_history
HISTCONTROL=ignoreboth:erasedups        # skip lines starting with a space, drop duplicates
HISTTIMEFORMAT='%F %T '                 # record timestamps: shown by the history command
shopt -s histappend                     # append to the file; do not overwrite it on exit
shopt -s checkwinsize cdspell           # re-check window size; fix small typos in cd

ignoreboth is a handy privacy trick: start a line with a space and it is not stored, which is useful when a command contains a secret. (Better still, never type secrets on a command line; see Reading Input and Interactive Scripts for read -s.)

Safe ways to experiment

  • Test in a throwaway shell: run bash --norc or bash --rcfile ~/test-rc before editing your real ~/.bashrc.
  • Keep a working terminal open while you change startup files, so a syntax error cannot lock you out.
  • Bash only reads ~/.bashrc in interactive non-login shells. Login shells read ~/.bash_profile (or ~/.profile), which should source ~/.bashrc. The details are in Environment, Profiles and Configuration.
  • Do not export PS1. It is a per-shell setting; exporting it can leak a Bash prompt into other shells.
  • Guard interactive-only code with [[ $- == *i* ]] || return at the top of ~/.bashrc, so scripts that source it do not break.
  • Keep dotfiles in a Git repository so you can restore your setup on a new machine in minutes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must color escape sequences in PS1 be wrapped in [ and ]?

    Readline counts every character of the prompt to place the cursor. Non-printing bytes must be marked, or long commands wrap in the wrong place.
  2. 2. In a PROMPT_COMMAND function, why do you store $? in a variable on the very first line?

    $? always holds the status of the most recent command. By the time you build the prompt, other commands have replaced the value you wanted to show.
  3. 3. What does the command compgen -W "alpha beta bravo" -- b print?

    compgen -W filters the word list to those that start with the given prefix. Both beta and bravo start with b.
  4. 4. In a completion function, how does it hand its candidates back to Bash?

    Bash reads the COMPREPLY array after the function returns. Printing to stdout only garbles the terminal.
  5. 5. Why does a personal ~/.inputrc usually start with $include /etc/inputrc?

    readline reads ~/.inputrc instead of /etc/inputrc. Including the system file first keeps its defaults, and you only add your changes.

Summary

  • PS1 is a string with backslash escapes (\u, \h, \W, \$, \e); wrap non-printing color sequences in \[ ... \]. Preview a prompt anywhere with ${string@P}.
  • PROMPT_COMMAND runs before each prompt: save $? first, keep the function fast, and append to it instead of overwriting.
  • complete -F func cmd registers a completion function; it reads COMP_WORDS and COMP_CWORD and fills COMPREPLY, usually with compgen -W, -f or -d.
  • Test completion by setting COMP_WORDS and COMP_CWORD yourself; load real ones lazily from bash-completion directories or source <(tool completion bash).
  • ~/.inputrc tunes readline ($include /etc/inputrc first); learn the default keys, and set HISTCONTROL, HISTSIZE and histappend for useful history.
  • Experiment in a throwaway shell (bash --norc) and keep a working terminal open.

Next: Project: A Backup Script