Skip to content

Instantly share code, notes, and snippets.

@Agent-E11
Last active November 15, 2024 06:30
Show Gist options
  • Save Agent-E11/a1cab631e854e36318321bbfa4c1041e to your computer and use it in GitHub Desktop.
Save Agent-E11/a1cab631e854e36318321bbfa4c1041e to your computer and use it in GitHub Desktop.
A simple profile to define a custom Bash prompt. Should be put in `/etc/profile.d/` (to be applied to all users), or sourced from your personal `.bashrc` file.
# Exit if non-interactive
[[ -z "$PS1" ]] && return
_colors=false
if [[ -x /usr/bin/tput ]] && tput setaf 1 >&/dev/null; then
# tput is executable, and it doesn't fail when trying to set the foreground color
_colors=true
else
case "$TERM" in
xterm-color|*-256color) _colors=true
esac
fi
if $_colors; then
PS1='[\[\e[32m\]\u@\h \[\e[34m\]\w\[\e[0m\]]\$ '
else
PS1='[\u@\h \w]\$ '
fi
unset _colors

Example Prompts

See man bash and search for "PROMPTING".

Also useful, is a reference to ANSI escape codes.

# Simple prompt

# [user@host ~/working/dir]$

# Color
PS1='[\[\e[32m\]\u@\h \[\e[34m\]\w\[\e[0m\]]\$ '
#     ^^^^^^^^^^      ^^^^^^^^^^  ^^^^^^^^^
#     + Green         + Blue      + Reset
# No color
PS1='[\u@\h \w]\$ '
# Multi-line prompt

# $[user@host ~/working/dir]
# >

# Color
PS1='\$[\[\e[32m\]\u@\h \[\e[34m\]\w\[\e[0m\]]\n> '
#       ^^^^^^^^^^      ^^^^^^^^^^  ^^^^^^^^^
#       + Green         + Blue      + Reset
# No color
PS1='\$[\u@\h \w]\n> '
# Color prompt based on last exit code (only the ">" is colored)

# ~/working/dir>

PS1='\w$([[ "$?" = "0" ]] && echo -e "\033[32m" || echo -e "\033[31m")>\[\e[0m\] '
#                                     ^^^^^^^^              ^^^^^^^^   ^^^^^^^^^
#                                     + Green               + Red      + Reset
@Agent-E11
Copy link
Author

You can also just run the PS1=... lines directly in your terminal to get a preview of what they look like.

bash-5.1$ PS1='\$[\[\e[32m\]\u@\h \[\e[34m\]\w\[\e[0m\]]\n> '

$[user@host ~/working/dir]
> echo "wow! so cool!"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment