basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Bash prompt: a color per server, exit code, and git branch

    The prompt is the example-user@web1:~$ string before the cursor, controlled by PS1. On Ubuntu it’s the same green on every server, and root gets no color at all. One block in ~/.bash_aliases gives each server its own color, turns root red, and adds the last failed exit code and git branch.

    Why server windows look identical

    You have three SSH windows open, one per server. Every prompt is the same shade of green, and the only difference is the hostname tucked in the middle of the line. Run docker compose down in the wrong window and you stop sites on the wrong server.

    Default
    web1
    example-user@web1:~$ systemctl is-active nginx
    inactive
    example-user@web1:~$ cd /var/lib/apt/lists
    example-user@web1:/var/lib/apt/lists$

    web2
    example-user@web2:~$ cd ~/infra
    example-user@web2:~/infra$ test -f .env
    example-user@web2:~/infra$

    web2 · sudo -i
    example-user@web2:~$ sudo -i
    root@web2:~# cd /etc/ssh
    root@web2:/etc/ssh#
    With the block
    web1
    example-user@web1:~$ systemctl is-active nginx
    inactive
    [4] example-user@web1:~$ cd /var/lib/apt/lists
    example-user@web1:.../lib/apt/lists$

    web2
    example-user@web2:~$ cd ~/infra
    example-user@web2:~/infra (main *)$ test -f .env
    [1] example-user@web2:~/infra (main *)$

    web2 · sudo -i
    example-user@web2:~$ sudo -i
    root@web2:~# cd /etc/ssh
    root@web2:/etc/ssh#
    Output from web1 (Ubuntu 24.04) and web2 (26.04). Colors come from the site theme; exact shades depend on your terminal.

    Ubuntu’s defaults don’t help:

    • Every server gets the same colors: green username and host, blue directory.
    • Root gets no color at all. /root/.bashrc colors the prompt only when the terminal reports xterm-color, while ssh from Windows sends xterm-256color. root@web2:~# differs from a normal prompt only by the name and the trailing character.
    • In PuTTY, even a regular user gets no color because PuTTY reports TERM=xterm by default.
    • A command that fails silently — grep with no match, test -f, systemctl is-active — looks identical to one that succeeded.

    With the block in this guide, each server gets its own color (web1 red, web2 magenta), root’s username turns red with # at the end, and [4] or [1] in red before the username flags a non-zero exit code from the previous command (nothing shows after success). .../ trims the start of long paths, and (main *) shows the git branch plus unstaged changes.

    How Ubuntu builds the prompt

    The prompt comes from the PS1 variable. Before printing each prompt, Bash expands \u, \h, \w and any variables inside it. For a regular Ubuntu user, PS1 looks like this (declare -p PS1):

    \[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$
    Part What it outputs
    \[\e]0;\u@\h: \w\a\] invisible in the line: sets the terminal window or tab title to example-user@web1: ~
    ${debian_chroot:+($debian_chroot)} chroot name in parentheses; empty on a normal server
    \[\033[01;32m\] switches to bold green
    \u@\h example-user@web1
    \[\033[00m\] resets color
    :\[\033[01;34m\]\w\[\033[00m\] colon, then current directory in blue
    \$ and space $ for a regular user, # for root

    Other escapes Bash expands in PS1:

    Escape Expands to
    \u username
    \h hostname up to the first dot: web1 from web1.example.org
    \H full hostname
    \w current directory, with home shortened to ~
    \W basename of the current directory only: dynamic
    \A time, 14:05
    \$ # for root, $ for everyone else
    \e ESC character that starts a color sequence; \033 is identical
    \[ and \] non-printing boundaries: anything inside takes zero screen width

    A color sequence is \e[, semicolon-separated numbers, and m: \e[1;31m is bold red, \e[0m resets. Your terminal’s color scheme decides the exact shade.

    Code Color
    31 red
    32 green
    33 yellow
    34 blue
    35 magenta
    36 cyan
    1;37;41 white on red background
    38;5;208 orange, from the 256-color palette

    1; before a color makes it bold. Many terminals also render bold colors as their bright variant — Tabby and other xterm.js-based terminals do this by default. In Tabby’s dark Default theme, bright yellow 1;33 is so pale it blends into normal text and fails to stand out. Preview all six colors in your own terminal before picking:

    for c in 31 32 33 34 35 36; do printf '\e[1;%sm%s\e[0m %s  ' "$c" "web1" "$c"; done; echo

    Wrap every color sequence in \[ … \] inside PS1. Bash tracks the prompt’s visible length so it knows where the command starts; without those brackets it counts escape codes as printed characters, and editing a long command garbles the line.

    Ubuntu’s ~/.bashrc sets PS1 on lines 59–73, and sources ~/.bash_aliases lower down on line 104. Setting PS1 in ~/.bash_aliases replaces Ubuntu’s prompt completely — including the window title unless you keep that escape sequence.

    Ubuntu 26.04 also adds /etc/profile.d/80-systemd-osc-context.sh from systemd: a PROMPT_COMMAND function and PS0 report user, hostname, working directory, and exit code to the terminal (the OSC 3008 spec). That doesn’t change how the prompt looks — terminals that don’t support it ignore the sequence. The part that matters here is that PROMPT_COMMAND becomes an array ([0]="" [1]="__systemd_osc_context_precmdline"), so append your own function with +=.

    Custom prompt: a block in ~/.bash_aliases

    Put the block at the end of ~/.bash_aliases — the same file that holds your aliases (Bash aliases). The case statement lists all your servers in one place, so you copy the exact same file everywhere and each host picks its color by name. Works on Ubuntu 24.04 and 26.04 with no extra packages.

    ~/.bash_aliases — prompt
    # Prompt: one color per server
    case "${HOSTNAME%%.*}" in
      web1) host_color='1;31' ;;
      web2) host_color='1;35' ;;
      *)    host_color='1;32' ;;
    esac

    Hostname color. ${HOSTNAME%%.*} strips everything from the first dot onward, matching \h, so both web1 and web1.example.org match web1). Give production servers high-contrast colors — red, magenta, cyan — after checking how they look in your terminal with the loop above. Any unlisted server stays green, like Ubuntu’s default.

    if [ "$EUID" -eq 0 ]; then
      user_color='1;31'
    else
      user_color='0'
    fi

    Turns root red. Root has $EUID equal to 0, so this kicks in under both sudo -i and sudo -s once root has a copy of the file (step below). A normal username uses the default text color so the hostname color stands out next to it.

    prompt_code() {
      local code=$?
      prompt_code_text=
      if [ "$code" -ne 0 ]; then prompt_code_text="[$code] "; fi
    }
    PROMPT_COMMAND+=(prompt_code)
    Key part

    Shows a non-zero exit code as red [1] before the username, and nothing after success. The function grabs $? on its first line: Bash passes the interactive command’s exit code to every PROMPT_COMMAND entry, even after systemd’s hook on 26.04. +=( ) appends without clobbering history -a or systemd.

    PROMPT_DIRTRIM=3

    Keeps only the last three path components: /opt/traefik/data/dynamic displays as .../traefik/data/dynamic. Short paths and ~ stay untouched.

    PS1=
    case "$TERM" in xterm*|rxvt*) PS1='\[\e]0;\u@\h: \w\a\]' ;; esac
    PS1+='\[\e[1;31m\]$prompt_code_text\[\e[0m\]'
    PS1+="\[\e[${user_color}m\]\u\[\e[0m\]@"
    PS1+="\[\e[${host_color}m\]\h\[\e[0m\]"
    PS1+=':\[\e[1;34m\]\w\[\e[0m\]'

    Starts with the same window-title prefix Ubuntu uses, for the same terminals, so the tab reads example-user@web1: ~. Next come the exit code, user@host, and the blue directory. $prompt_code_text is in single quotes so Bash evaluates it before every prompt. Color variables are in double quotes so they expand once when the file loads.

    if [ -r /usr/lib/git-core/git-sh-prompt ]; then
      . /usr/lib/git-core/git-sh-prompt
      GIT_PS1_SHOWDIRTYSTATE=1
      PS1+='$(__git_ps1 " (%s)")'
    fi

    Shows the git branch inside a repository: (main *). The git package provides __git_ps1. Ubuntu loads it automatically on SSH logins, but not under sudo -s, so source the file explicitly. GIT_PS1_SHOWDIRTYSTATE=1 adds status symbols next to the branch — see “Git branch in the prompt”.

    PS1+='\$ '

    $ for a regular user, # for root, followed by a space before your command.

    1. Append the block to ~/.bash_aliases

      nano ~/.bash_aliases

      Paste the block above at the bottom of the file — the Copy button grabs all chunks at once — and put your own server names in case. If the file doesn’t exist yet, nano creates it.

    2. Check the syntax

      bash -n ~/.bash_aliases

      No output means no syntax errors. On an error, Bash prints the file and line number: /home/example-user/.bash_aliases: line 6: syntax error near unexpected token.

    3. Restart the shell

      exec bash

      Bash replaces itself with a fresh shell and reads startup files cleanly. source ~/.bash_aliases also applies the block, but every repeat appends another copy of prompt_code to PROMPT_COMMAND. The prompt looks the same — the function runs twice, and the extra copy disappears on the next login.

    4. Do the same for root

      sudo cp ~/.bash_aliases /root/

      Both sudo -i and sudo -s read /root/.bashrc, which loads /root/.bash_aliases. A fresh Ubuntu install has no /root/.bash_aliases; if one already exists, append the block instead of overwriting it.

    5. Copy to other servers

      scp ~/.bash_aliases web2:

      The case list is shared, so web2 picks its own color. On the remote server, repeat “Do the same for root”.

    Git branch in the prompt

    __git_ps1 prints the current branch whenever you’re inside a repository — handy in /opt if server configs live in git. With GIT_PS1_SHOWDIRTYSTATE=1, symbols appear after the branch name:

    Symbol Meaning
    * modified files not yet staged
    + staged changes not yet committed
    # repository has no commits yet, such as right after git init

    To print those symbols, __git_ps1 runs git diff --quiet and git diff --cached --quiet before every prompt. The more files a repo holds, the longer the prompt waits. If a particular repo feels sluggish, turn dirty state off for that repo alone:

    git config bash.showDirtyState false

    The branch name stays; only * and + disappear. If no branch appears at all in a repo owned by root, see the /opt case in “If it doesn’t work”.

    Starship instead of a custom PS1

    Starship is a standalone binary that builds a prompt from modules: git branch, duration of slow commands, Python and Node versions inside project directories. Ubuntu 26.04 packages starship (1.22.1); 24.04 does not. Enable it with one line in ~/.bash_aliases:

    eval "$(starship init bash)"

    Its default prompt spans two lines: example-user in 🌐 web2 in ~ followed by ❯ on the second line. ❯ turns green after a zero exit code and red after an error, without the numeric code. In a small repository, starship prompt finishes in around 6 ms.

    Starship shows the username and hostname only when it detects SSH via SSH_CONNECTION; in a provider web console you see only ~ and ❯. Its git branch icon is Unicode U+E0A0 from Powerline and Nerd Fonts, so your local terminal needs one of those fonts installed. Settings live in ~/.config/starship.toml. That config has no hostname conditionals, so giving each server its own color means keeping a different config file on each server.

    If… Use
    you want a per-server color from one shared file on 24.04 and 26.04, with nothing to install the PS1 block in this guide
    your servers run 26.04, you want language versions and command durations, and you have a Nerd Font Starship

    If it doesn’t work

    On a long command line, Ctrl+A moves the cursor to the end of the first line and new typing overwrites the command

    Cause
    Color codes in PS1 aren’t wrapped in \[ … \]. Bash counts them as visible characters, thinks the prompt is wider than it is on screen, and miscalculates where the command begins.
    Fix
    Wrap every color code: \[\e[1;31m\], \[\e[0m\].

    Everything after the prompt — both the command you type and its output — takes the color of the directory

    Cause
    PS1 is missing the reset code \[\e[0m\] at the end. A color stays active until reset, affecting both input and output.
    Fix
    Close every colored segment with \[\e[0m\].

    The prompt has no color in PuTTY, while Windows Terminal shows color

    Cause
    PuTTY defaults to TERM=xterm, and Ubuntu’s ~/.bashrc enables color only when TERM is xterm-color or ends with -256color.
    Fix
    The block in this guide colors the prompt for any TERM. Without it, set Connection › Data › Terminal-type string in PuTTY to xterm-256color.

    Under sudo -i, the prompt has no color: root@web1:~#

    Cause
    Root uses /root/.bashrc, which enables color only for TERM=xterm-color, whereas ssh from Windows sends xterm-256color.
    Fix
    Copy the block to root: sudo cp ~/.bash_aliases /root/.

    After setting a custom PS1, the terminal tab stopped showing the server name

    Cause
    Ubuntu sets the window title inside PS1 via the invisible prefix \[\e]0;\u@\h: \w\a\]. Replacing PS1 dropped it.
    Fix
    Start your PS1 with that prefix, as in the block below.

    After Ctrl+C the prompt shows [130], and pressing Enter doesn’t clear it

    Cause
    Ctrl+C interrupts the command or input line and sets exit code 130 (128 + SIGINT, which is 2). Pressing Enter on an empty line doesn’t run a command, so the exit code stays unchanged.
    Fix
    Do nothing: the code clears after the next command runs.

    A custom prompt with a git branch shows [0] after every command, and [128] outside a repository

    Cause
    $( … ) appears before $? in PS1, so $? reflects the substitution instead: git branch --show-current exits with 0 inside a repo and 128 outside.
    Fix
    Capture $? first in a PROMPT_COMMAND function (like prompt_code below), or place $? before any $( … ) in PS1.

    Under sudo -s, every prompt prints __git_ps1: command not found

    Cause
    On Ubuntu, __git_ps1 is loaded by bash-completion on SSH logins and sudo -i. Under sudo -s, root reads /root/.bashrc, where bash-completion is commented out.
    Fix
    Source the file explicitly before using __git_ps1: . /usr/lib/git-core/git-sh-prompt.

    No git branch shows up in /opt, even though /opt is a repository

    Cause
    The repository is owned by root, and since git 2.35.2 git refuses to inspect another user’s repo: git status says fatal: detected dubious ownership in repository at '/opt'. __git_ps1 hides the error and omits the branch.
    Fix
    Mark the directory safe for your user: git config --global --add safe.directory /opt.

    After adding the prompt on Ubuntu 24.04, command history stopped saving immediately

    Cause
    ~/.bash_aliases has PROMPT_COMMAND=prompt_code without +=. Plain assignment overwrites the first element of the array, where history -a from Command history lived. On 26.04 systemd leaves element 0 empty, so the same bug hides.
    Fix
    Use PROMPT_COMMAND+=(prompt_code) to append to the array. Check with declare -p PROMPT_COMMAND.

    You changed the server’s hostname, yet the prompt still shows the old one

    Cause
    Bash reads the hostname for \h and $HOSTNAME once, at startup.
    Fix
    Run exec bash or log in again. To change the hostname, see First login to a server, step “Set the hostname”.

    How to check

    false
    # [1] example-user@web1:~$
    true
    # example-user@web1:~$
    cd /var/lib/apt/lists
    # example-user@web1:.../lib/apt/lists$

    Red [1] confirms prompt_code works, and disappears after true. .../ in the path confirms PROMPT_DIRTRIM. The terminal tab title shows example-user@web1: .../lib/apt/lists.

    sudo -i
    # root@web1:~#

    Red root and a trailing # confirm root loaded its copy. Check what your next SSH login gets:

    bash -lic 'declare -p PROMPT_COMMAND'
    # declare -a PROMPT_COMMAND=([0]="" [1]="__systemd_osc_context_precmdline" [2]="prompt_code")

    That’s how the array looks on Ubuntu 26.04; on 24.04 it holds only prompt_code, plus history -a if you set up Command history.