prompt-ps1-code.org 2.1 KB

Abbreviated current working directory

The following PS1 code will result in a prompt with abbreviated current working directory:

##########

########## function nonzero_return() { RETVAL="${?}" # printf "RETVAL is: %s\n" "${?}" if [ ${RETVAL} -ne 0 ]; then RESULT="\[$(tput setaf 196)\][${RETVAL}]\[$(tput sgr0)\]" printf ${RESULT@P} else printf "[0]" fi }

function abbreviate() { MAX_LEN="${2}" STR_LEN="${#1}" STR="${1}" if [ "${STR_LEN}" -gt "${MAX_LEN}" ]; then START_POS=$((${STR_LEN}-${MAX_LEN})) echo "...${STR:${START_POS}}" else echo "${STR}" fi }

PS1_USER="\u" PS1_USER_STYLED="\[$(tput setaf 39)\]${PS1_USER}\[$(tput sgr0)\]"

PS1_HOST="\h" PS1_HOST_STYLED="\[$(tput setaf 10)\]${PS1_HOST}\[$(tput sgr0)\]"

CURRENT_DIR_MAX_LEN=20

export PS1="${PS1_USER_STYLED}@${PS1_HOST_STYLED}:\$(nonzero_return):\[$(tput setaf 203)\]\$(abbreviate \"\$(pwd)\" ${CURRENT_DIR_MAX_LEN})\[$(tput sgr0)\]\\$ "