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/apps/shell/bash/prompt
2019-12-02 09:31:28 -06:00

38 lines
1.3 KiB
Bash

#!/usr/bin/env bash
COLOR_RESET='\[\e[0m\]'
# TODO: if root, background instead?
PROMPT_SUCCESS_COLOR='\[\e[0;34m\]'
PROMPT_FAILURE_COLOR='\[\e[0;31m\]'
DIR_COLOR='\[\e[0;35m\]'
MAX_PATH_PIECE_CHARS=${BASH_PROMPT_MAX_PATH_PIECE_CHARS:-3}
# prompt rendering functions
preprocess_pwd() {
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]}}}}')"
# 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]}}}')"
}
export -f "preprocess_pwd"
prompt_command_func()
{
RET=$?
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
STATUS_COLOR=$PROMPT_SUCCESS_COLOR
else
STATUS_COLOR=$PROMPT_FAILURE_COLOR
fi
PS1="$STATUS_COLOR\u@\h$COLOR_RESET $DIR_COLOR$(preprocess_pwd)$COLOR_RESET "
}
export -f "prompt_command_func"
export PROMPT_COMMAND="prompt_command_func"