Last active
May 12, 2025 08:00
-
-
Save Loupax/86d8f824b1b0e0eec0f92b6def918321 to your computer and use it in GitHub Desktop.
Custom bash prompt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
C_BLUE="\[\033[0;34m\]" | |
C_GREEN="\[\033[0;32m\]" | |
C_RED="\[\033[0;31m\]" | |
C_RESET="\[\033[0m\]" | |
__prompt_git_info() { | |
if $(git rev-parse --is-inside-git-dir 2>/dev/null); then | |
echo "" | |
return | |
fi | |
if ! (git rev-parse --is-inside-work-tree > /dev/null 2>&1); then | |
echo "" | |
return | |
fi | |
local branch_name_or_hash | |
local final_git_string="" | |
branch_name_or_hash=$(git symbolic-ref --short HEAD 2>/dev/null) | |
if [[ -z "$branch_name_or_hash" ]]; then | |
branch_name_or_hash=$(git rev-parse --short HEAD 2>/dev/null) | |
if [[ -z "$branch_name_or_hash" ]]; then | |
echo "" | |
return | |
fi | |
fi | |
local dirty=false | |
local state="" | |
if git status --porcelain 2>/dev/null | \grep -q '^??'; then | |
dirty=true | |
state="+" | |
elif ! git diff --quiet HEAD 2>/dev/null || ! git diff --quiet 2>/dev/null; then | |
dirty=true | |
state="+" | |
fi | |
local git_content="(${branch_name_or_hash})${state}" | |
if [[ "$dirty" == true ]]; then | |
final_git_string="${C_RED}${git_content}${C_RESET}" | |
else | |
final_git_string="${C_BLUE}${git_content}${C_RESET}" | |
fi | |
echo "${final_git_string}" | |
} | |
__set_custom_prompt() { | |
local EXIT="$?" | |
local current_pwd_display | |
local current_pwd=$PWD | |
local home_dir=$HOME | |
local err="${C_RED}\$${C_RESET}" | |
if [[ "$EXIT" -eq "0" ]]; then | |
err="${C_GREEN}\$${C_RESET}" | |
fi | |
if [[ "$current_pwd" == "$home_dir" ]]; then | |
current_pwd_display="~" | |
elif [[ "$current_pwd" == "$home_dir"/* ]]; then | |
current_pwd_display="~${current_pwd#$home_dir}" | |
else | |
current_pwd_display="$current_pwd" | |
fi | |
local git_info | |
git_info=$(__prompt_git_info) | |
if [[ ! -z ${git_info} ]]; then | |
git_root=$(git rev-parse --show-toplevel 2>/dev/null) | |
if [[ "$git_root" == "$PWD" ]]; then | |
PS1="${git_info} ./${PWD##*/} ${err} " | |
else | |
PS1="${git_info} ${git_root##*/}${PWD#$git_root} ${err} " | |
fi | |
return | |
fi | |
PS1="${current_pwd_display} ${err} " | |
} | |
PROMPT_COMMAND=__set_custom_prompt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment