Customizing the Bash Prompt (PS1)

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 145 of 205

The prompt is the text an interactive Bash prints when it is ready for the next command, such as ana@laptop:~/projects$. Its content comes from the shell variable PS1 (prompt string 1). Bash reads PS1 again before every prompt, so changing the variable changes the prompt immediately, and putting the assignment in ~/.bashrc makes the change permanent.

A good prompt is a small dashboard. It can show who you are logged in as and on which machine (important when several SSH sessions are open), the current folder, the Git branch, whether the last command failed, and whether background jobs are still running. This lesson covers the special codes Bash understands in PS1, colors and the rule that keeps long prompts from breaking line editing, the related variables PS2 and PROMPT_COMMAND, and a complete two-line prompt.

The Prompt Variables

VariablePrinted when
PS1the shell is ready for a new command
PS2a command continues on the next line (default > )
PS3select asks for a choice (lesson 86)
PS4before each line of an xtrace debug trace (default + , lesson 126)

PS0 also exists: it is printed after you press Enter and before the command runs, and is rarely used. Only interactive shells print PS1 and PS2; scripts never show a prompt.

Prompt Escape Sequences

Inside PS1, Bash replaces special backslash sequences with current information. The @P operator (lesson 152) expands a string exactly as Bash would expand a prompt, which makes it easy to try sequences without changing your real prompt. This test script ran in the folder /home/ana/projects with HOME set to /home/ana:

show() { local PS1=$1; printf '%-22s -> %s\n' "$1" "${PS1@P}"; }
show '\u@\h:\w\$ '
show '\W\$ '
show '\H'
show '\s-\v (\V)'
show '\d \t'
show '\T \@ \A'
show '\D{%Y-%m-%d %H:%M}'
show 'jobs:\j'
show 'shell level ${SHLVL}'
\u@\h:\w\$             -> root@vm:/home/ana/projects#
\W\$                   -> projects#
\H                     -> vm
\s-\v (\V)             -> bash-5.2 (5.2.21)
\d \t                  -> Tue Nov 24 04:00:35
\T \@ \A               -> 04:00:35 04:00 AM 04:00
\D{%Y-%m-%d %H:%M}     -> 2026-11-24 04:00
jobs:\j                -> jobs:0
shell level ${SHLVL}   -> shell level 2
SequenceExpands to
\uthe user name
\h, \Hthe host name up to the first dot, and the full host name
\wthe current folder, with your home folder shortened to ~
\Wonly the last part of the current folder
\$# for the root user, $ for everyone else
\dthe date as "Tue Nov 24"
\t, \T, \@, \Athe time: 24-hour with seconds, 12-hour with seconds, 12-hour with AM/PM, 24-hour HH:MM
\D{format}the time in any strftime format, like date +format
\jthe number of jobs the shell is managing
\s, \v, \Vthe shell name, its version, and its version with patch level
0, 1the history number and the command number of this command
\na new line
\ethe escape character, used for colors
0, 1start and end of non-printing characters (see below)
0a literal backslash

The test ran as root, so \$ printed #. The same prompt string expanded for the unprivileged user nobody ends with $:

nobody@vm:/home/ana/projects$

After the escape sequences, Bash also performs parameter expansion, command substitution and arithmetic expansion on the prompt (the shell option promptvars, on by default), which is why ${SHLVL} worked.

Shortening Long Paths

Deep folders make \w long. PROMPT_DIRTRIM=N keeps only the last N folder names and replaces the rest with ...:

HOME=/home/ana; show '\w'
PROMPT_DIRTRIM=2; cd /home/ana/projects/notes/2026/nov; show '\w'
\w                     -> ~/projects
\w                     -> ~/.../2026/nov

Setting PS1: Quoting Matters

Two quoting details catch many people. Both were tested in an interactive Bash running as root, whose prompt started as ~/projects# .

Command substitution in double quotes runs only once. In double quotes, $(...) is expanded at the moment of the assignment, and the prompt stores the result. In single quotes, the $(...) text itself is stored, and Bash runs it again for every prompt:

~/projects# PS1="[$(date +%S)] \$ "
[56] $ true
[56] $ PS1='[$(date +%S)] \$ '
[57] # true
[58] #

With double quotes, the seconds stayed at 56. With single quotes, they changed with every prompt.

\$ in double quotes loses its backslash. Inside double quotes, \$ is the shell's own escape for a literal dollar sign, so PS1 received a plain $. That is why the first prompt showed $ although the user was root; in single quotes, \$ reached the prompt and correctly became #.

The simple rule: write PS1 in single quotes. Use double quotes only for parts that should be fixed at assignment time, as the complete example does with color codes.

PS2: The Continuation Prompt

When a command is not finished at the end of a line, such as an open quote or a for loop without done, Bash prints PS2 and waits for more:

~/projects# echo "one
> two"
one
two
~/projects# PS2="more> "
~/projects# for i in 1 2
more> do echo $i; done
1
2

Colors and the [ ] Rule

Terminals change colors when they receive ANSI escape sequences: the escape character, [, a list of numbers and the letter m. In PS1, the escape character is written \e:

CodeEffectCodeEffect
0reset all attributes1bold
31red text32green text
33yellow text34blue text
35magenta text36cyan text

\e[1;32m starts bold green and \e[0m resets. Codes 90-97 are bright variants, and 38;5;N selects one of 256 colors on terminals that support it.

Bash needs to know how wide the prompt is on screen, so that line editing, the history keys and long command lines wrap correctly. Escape sequences take bytes but no space on screen, and Bash cannot recognize them by itself. Every escape sequence in PS1 must be wrapped in 0 and 1, which tell Bash "these characters take no space":

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

Without the brackets, the prompt looks correct at first, but Bash counts the invisible bytes as characters. Long commands then wrap at the wrong position, and moving through history with the arrow keys leaves pieces of old text on the line. If a colored prompt behaves strangely during editing, a missing 0 or 1 is almost always the reason.

The 0 and 1 markers belong in PS1 only. In echo or printf output they are not needed and would be printed literally.

tput (from ncurses) is an alternative to hard-coded codes: tput setaf 2 prints the sequence for green on the current terminal, and tput colors reports how many colors the terminal supports. The complete example uses tput colors to switch colors off on terminals that cannot show them:

TERM=xterm-256color tput colors
TERM=dumb tput colors
256
-1

PROMPT_COMMAND: Building the Prompt with Code

PROMPT_COMMAND holds a command that Bash runs before printing each PS1. It is usually set to a function that inspects the situation and assigns a new PS1. This is more flexible than packing everything into PS1:

  • the function can use if, case and local variables
  • it can capture $?, the exit status of the command you just ran, before anything else changes it
  • it can decide to show a piece of information only when it matters

Since Bash 5.1, PROMPT_COMMAND may also be an array, and Bash runs each element in turn. A plain string works in every version.

The first line of the function must save $?. Every command, including a test, changes $?, so the status of the user's last command is available only at the very beginning:

_p_build() {
  local status=$?    # first: the status of the user's last command
  ...
}
PROMPT_COMMAND=_p_build

Keeping the Prompt Fast

Bash runs PROMPT_COMMAND and every $(...) in PS1 before each prompt. A command that takes a quarter of a second makes the whole shell feel slow. Prefer prompt escapes and variables (\j, \w, $?) to external commands, keep the number of $(...) calls small, and be aware that version-control commands can be slow in very large repositories. The complete example runs two short Git commands per prompt, which is fast in ordinary repositories.

A Complete Example: A Two-Line Informative Prompt

prompt.bash builds a prompt with two lines: the first shows the user, host, folder, Git branch and background jobs; the second shows the exit status of the last command when it failed, the time, and $ or #. Commands are typed on the short second line, so long folder names never push them to the right.

# prompt.bash: a two-line prompt, loaded from ~/.bashrc with
#   [[ -f ~/prompt.bash ]] && source ~/prompt.bash
#
# Line 1: user@host, folder, Git branch (* = uncommitted changes), jobs
# Line 2: exit status of the last command if it failed, time, $ or #

# Colors only when the terminal supports them. \[ and \] mark the
# escape sequences as zero-width so Bash can measure the prompt.
if (( $(tput colors 2>/dev/null || echo 0) >= 8 )); then
  _p_user='\[\e[1;32m\]' _p_dir='\[\e[1;34m\]' _p_git='\[\e[33m\]'
  _p_err='\[\e[1;31m\]'  _p_off='\[\e[0m\]'
else
  _p_user= _p_dir= _p_git= _p_err= _p_off=
fi
PROMPT_DIRTRIM=3                 # show at most 3 trailing folders in \w

# _p_git_branch: print " (branch)" or " (branch*)" inside a Git work tree
_p_git_branch() {
  local branch
  branch=$(git symbolic-ref --short HEAD 2>/dev/null) ||
    branch=$(git rev-parse --short HEAD 2>/dev/null) || return 0
  if [[ -n $(git status --porcelain --untracked-files=no 2>/dev/null) ]]; then
    branch+='*'
  fi
  printf ' (%s)' "$branch"
}

# _p_build: runs before every prompt (PROMPT_COMMAND) and rebuilds PS1
_p_build() {
  local status=$?                # must come first: the last command's status
  local jobs='\j' line1 line2=
  jobs=${jobs@P}                 # expand \j now: the number of jobs

  line1="${_p_user}\u@\h${_p_off} ${_p_dir}\w${_p_off}"
  line1+="${_p_git}$(_p_git_branch)${_p_off}"
  if (( jobs == 1 )); then line1+=" [1 job]"
  elif (( jobs > 1 )); then line1+=" [$jobs jobs]"
  fi

  (( status != 0 )) && line2="${_p_err}[exit $status]${_p_off} "
  line2+='\A \$ '

  PS1="$line1\n$line2"
}
PROMPT_COMMAND=_p_build

How It Works

  • Color detection runs once, when the file is sourced. tput colors prints the number of colors of the current terminal; if tput fails (for example, TERM is not set), || echo 0 supplies 0. With fewer than 8 colors, all color variables are empty and the prompt is plain text.
  • The color variables contain 0...1 around each escape sequence, so every place they are used is automatically marked as zero-width.
  • _p_git_branch asks Git for the current branch name. Outside a repository both Git commands fail and the function prints nothing. In a "detached HEAD" state (a commit checked out without a branch), git symbolic-ref fails and git rev-parse --short HEAD supplies the short commit ID instead. git status --porcelain prints one line per changed file, so non-empty output means uncommitted changes, shown as *. --untracked-files=no ignores new files that Git does not track, which keeps the check fast.
  • _p_build saves $? on its first line. It counts jobs by expanding the prompt sequence \j with ${jobs@P}, which reads the shell's own job table without starting a subshell. It then assembles both lines and assigns PS1. The second line uses single quotes for \A \$ so the backslashes survive.
  • The [exit N] marker appears only after a failed command, so a successful command leaves the prompt calm, and a failure is impossible to miss.

Running the Complete Example

prompt.bash was copied to /home/ana, and an interactive Bash was started with a startup file containing only the source line. TERM=dumb was set so that the output below contains no color codes. A Git repository with one commit on the branch main existed in ~/projects/site:

root@vm ~
04:01 # cd projects/site
root@vm ~/projects/site (main)
04:01 # echo "<p>new</p>" >> index.html
root@vm ~/projects/site (main*)
04:01 # git switch -q -c feature
root@vm ~/projects/site (feature*)
04:01 # ls nope
ls: cannot access 'nope': No such file or directory
root@vm ~/projects/site (feature*)
[exit 2] 04:01 # git commit -qam "add paragraph"
root@vm ~/projects/site (feature)
04:01 # sleep 60 &
[1] 1585
root@vm ~/projects/site (feature) [1 job]
04:01 # sleep 61 &
[2] 1591
root@vm ~/projects/site (feature) [2 jobs]
04:01 # cd /home/ana/projects/notes/2026/nov
root@vm ~/.../notes/2026/nov [2 jobs]
04:01 # kill %1 %2
[1]-  Terminated              sleep 60  (wd: ~/projects/site)
(wd now: ~/projects/notes/2026/nov)
[2]+  Terminated              sleep 61  (wd: ~/projects/site)
(wd now: ~/projects/notes/2026/nov)
root@vm ~/.../notes/2026/nov [2 jobs]
04:01 # cd /tmp
root@vm /tmp
04:01 # exit

Each prompt reacted to the previous command: the branch appeared inside the repository, the * appeared after index.html changed and disappeared after the commit, [exit 2] reported the failed ls, the job counter followed the background sleep commands, and PROMPT_DIRTRIM=3 shortened the deep notes folder.

One timing detail is visible near the end. Directly after kill %1 %2, the next prompt still showed [2 jobs], and only the prompt after that showed none. (The wd lines are Bash's job notices: the jobs were started in another folder.)

PROMPT_COMMAND runs before Bash removes the jobs it has just reported as ended, so the count it sees still includes them. A \j written directly into PS1 is expanded later and does not show this delay, but it cannot be hidden when there are no jobs. For a prompt, being one command late here is a reasonable price for showing the counter only when it is needed.

With a color terminal (TERM=xterm-256color), the same function produces escape sequences. Calling _p_build in a test script right after false, and printing the expanded prompt through cat -v, which shows the escape character as ^[:

source /home/ana/prompt.bash
false
_p_build
printf '%s' "${PS1@P}" | cat -v; echo
echo ---
printf '%s\n' "$PS1"
^[[1;32mroot@vm^[[0m ^[[1;34m~/projects/site^[[0m^[[33m (feature)^[[0m
^[[1;31m[exit 1]^[[0m 04:02 #
---
\[\e[1;32m\]\u@\h\[\e[0m\] \[\e[1;34m\]\w\[\e[0m\]\[\e[33m\] (feature)\[\e[0m\]\n\[\e[1;31m\][exit 1]\[\e[0m\] \A \$

The second part shows the stored PS1: the Git branch is already filled in, because _p_build ran the Git command when it built the string, while the prompt escapes \u, \w, \A and \$ are still waiting to be expanded each time the prompt is printed. With a commit checked out without a branch (git switch --detach HEAD~1), the first line showed the short commit ID instead, and outside any repository the Git part was simply absent:

root@vm ~/projects/site (12cb41f)
[exit 1] 04:02 #
root@vm ~
[exit 1] 04:02 #

To make the prompt permanent, add [[ -f ~/prompt.bash ]] && source ~/prompt.bash to ~/.bashrc (lesson 146 explains which startup file Bash reads in which situation) and open a new terminal.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Customizing the Bash Prompt (PS1) and get answers drawn from it.

Signed-in readers only.