This repository has been archived on 2024-03-28. You can view files and clone it, but cannot push or open issues or pull requests.
dotfiles/shell/bash/prompt

39 lines
1.3 KiB
Plaintext
Raw Normal View History

2017-02-07 16:16:45 -06:00
#!/usr/bin/env bash
COLOR_RESET='\[\e[0m\]'
2019-10-30 17:57:30 -05:00
# TODO: if root, background instead?
2017-02-07 16:16:45 -06:00
PROMPT_SUCCESS_COLOR='\[\e[0;34m\]'
PROMPT_FAILURE_COLOR='\[\e[0;31m\]'
DIR_COLOR='\[\e[0;35m\]'
2017-02-07 16:16:45 -06:00
MAX_PATH_PIECE_CHARS=${BASH_PROMPT_MAX_PATH_PIECE_CHARS:-3}
2019-10-30 17:57:30 -05:00
2017-02-07 16:16:45 -06:00
# prompt rendering functions
preprocess_pwd() {
2019-10-30 17:57:30 -05:00
p="$PWD"
[[ "$p" == "/" ]] && echo "/" && return 1
[[ "$p" == "${NICE_HOME}" ]] && echo "~" && return 0
# with ellipsis
#echo "$(<<< "$p" cut -c2- | awk '{split($0,p,"/");for(k in p){if(k==length(p)){printf "/%s",p[k]}else{if(length(p[k])>'"$((MAX_PATH_PIECE_CHARS+1))"'){printf "/%.'"$((MAX_PATH_PIECE_CHARS))"'s…",p[k]}else{printf "/%s",p[k]}}}}')"
2019-10-30 17:57:30 -05:00
# without ellipsis
echo "$(<<< "$p" cut -c2- | awk '{split($0,p,"/");for(k in p){if(k==length(p)){printf "/%s",p[k]}else{printf "/%.'"$MAX_PATH_PIECE_CHARS"'s",p[k]}}}')"
2017-02-07 16:16:45 -06:00
}
export -f "preprocess_pwd"
prompt_command_func()
{
RET=$?
2019-10-30 17:57:30 -05:00
history -a # commit history to prevent data loss from edge cases
# set the color of user@host based on the result of the previous command
if [[ $RET -eq 0 ]]; then
2017-02-07 16:16:45 -06:00
STATUS_COLOR=$PROMPT_SUCCESS_COLOR
else
STATUS_COLOR=$PROMPT_FAILURE_COLOR
2019-10-30 17:57:30 -05:00
fi
PS1="$STATUS_COLOR\u@\h$COLOR_RESET $DIR_COLOR$(preprocess_pwd)$COLOR_RESET "
2017-02-07 16:16:45 -06:00
}
export -f "prompt_command_func"
export PROMPT_COMMAND="prompt_command_func"