Skip to content

Instantly share code, notes, and snippets.

@xmgr
Last active January 10, 2024 23:10
Show Gist options
  • Save xmgr/9fe32c7f292e3d840d6e7e2b0f5803f4 to your computer and use it in GitHub Desktop.
Save xmgr/9fe32c7f292e3d840d6e7e2b0f5803f4 to your computer and use it in GitHub Desktop.

My prompt

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.

Prompt

# 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).

Composition

Let me break down the components of that Bash prompt (PS1) step by step:

($?) (optional)

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.

($0) (optional)

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.

\[\033[01;32m\]\u\[\033[0m\]

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.

@\[\033[01;32m\]\H\[\033[0m\]

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.

:\[\033[01;34m\]$(pwd)\[\033[0;33m\]

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\]).

$(git rev-parse --abbrev-ref HEAD 2>/dev/null|sed -r -e "s/^(.+?)$/ (\1)/gi")

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.

\[\033[0m\]

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.

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