Skip to content

Instantly share code, notes, and snippets.

@mathias-bevers
Last active May 16, 2025 13:39
Show Gist options
  • Select an option

  • Save mathias-bevers/55a82a49473e6abc0b6178d28c9dd23a to your computer and use it in GitHub Desktop.

Select an option

Save mathias-bevers/55a82a49473e6abc0b6178d28c9dd23a to your computer and use it in GitHub Desktop.
my take for a simple shell prompt
# run the prompt after every command.
PROMPT_COMMAND=prompt_command_hook
function prompt_command_hook()
{
# get the current branch in the format (branch)
GIT_BRANCH=$(__git_ps1 "(%s)")
# if the branch is null, only display user, pwd
# else add an @ and the branch
if [[ -z "$GIT_BRANCH" ]]; then
PS1='┌\e[0;92m[\u] \e[0;36m$(get_pwd)\n\e[0m└$ '
else
PS1='┌\e[0;92m[\u] \e[0;36m$(get_pwd)\e[0;37m@\e[0;95m$GIT_BRANCH\n\e[0m└$ '
fi
}
function get_pwd() {
# set default variables
CURRENT_DIR="${PWD/"$HOME"/"~"}"
LENGTH=${#CURRENT_DIR}
MAX_LENGTH=20
# if the current_directory is smaller than the max length
# then echo the dir and exit.
if [[ $LENGTH -le $MAX_LENGTH ]]; then
echo $CURRENT_DIR
exit
fi
# split the path into directories.
IFS="/" read -r -a SPLIT_DIRECTORIES <<< $CURRENT_DIR
# if the directory only has one or less subdirectory just
# return the current directory.
if [[ ${#SPLIT_DIRECTORIES[@]} -le 1 ]]; then
echo $CURRENT_DIR
exit
fi
# set the tmp_dir variable to the last directory in the array
# and set the current_dir to tmp_dir.
# loop backwards though the directory array starting from the
# second to last element in the array.
TMP_DIR="${SPLIT_DIRECTORIES[-1]}"
CURRENT_DIR=$TMP_DIR
for (( idx=${#SPLIT_DIRECTORIES[@]} - 2; idx >= 0; idx-- )); do
# add the current element to the existing directory.
TMP_DIR="${SPLIT_DIRECTORIES[idx]}/$TMP_DIR"
# if the last added directory is the home directory
# return with the ~ regardless if it is "too long".
# else if the newly created directory is too long return the last
# directory with '.../' as prefix.
if [[ "${SPLIT_DIRECTORIES[idx]}" = "~" ]]; then
echo "~/$CURRENT_DIR"
exit
elif [[ ${#TMP_DIR} -gt $(( $MAX_LENGTH - 4 )) ]]; then
echo ".../$CURRENT_DIR"
exit
fi
# set the current_directory to the new tmp_dir.
CURRENT_DIR=$TMP_DIR
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment