This prompt is a colorful and informative representation of the shell, user, hostname, working directory, Git branch (if applicable), and the exit status of the last command. The use of ANSI escape sequences allows for color formatting in the terminal.
# Optional: prepend "($?)($0)"
PS1='\[\033[01;32m\]\u\[\033[0m\]@\[\033[01;32m\]\H\[\033[0m\]:\[\033[01;34m\]$(pwd)\[\033[0;33m\]$(git rev-parse --abbrev-ref HEAD 2>/dev/null|sed -r -e "s/^(.+?)$/ (\1)/gi")\[\033[0m\] ~\$ '
You can run this command whenever you like, or persist the prompt by adding that
line to your ~/.profile
or ~/.bashrc
or ~/.bash_aliases
(whatever option applies to your environment).
Let me break down the components of that Bash prompt (PS1) step by step:
This part represents the exit status of the last command. $?
is a special variable in Bash that holds the exit status of the last executed command. If the previous command was successful, it will be 0. If there was an error, it will be a non-zero value.
This part represents the name of the shell or shell script. $0
is a special variable that holds the name of the shell or script being executed.
This part sets the color of the username (\u
). \[\033[01;32m\]
is the ANSI escape sequence for setting the text color to bold green, and \[\033[0m\]
resets the color back to the default.
This part sets the color of the "@" symbol and the hostname (\H
). Similarly, it uses ANSI escape sequences to set the text color to bold green for the hostname.
This part displays the current working directory ($(pwd)
) in bold blue (\[\033[01;34m\]
). The text color is then set to bold yellow (\[\033[0;33m\]
).
This part uses a command substitution to get the current Git branch (git rev-parse --abbrev-ref HEAD
) and format it. The command substitution is wrapped in $()
and the output is processed by sed to format it. It adds parentheses around the branch name. The 2>/dev/null
part suppresses error messages if the directory is not a Git repository.
This part resets the text color and formatting back to the default.
This part represents the prompt symbol, where ~
indicates the home directory, and $
is the default prompt symbol.