Skip to content

Instantly share code, notes, and snippets.

@kpengboy
Last active December 20, 2018 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kpengboy/ab6dc4398b09165c61cee5d984362132 to your computer and use it in GitHub Desktop.
Save kpengboy/ab6dc4398b09165c61cee5d984362132 to your computer and use it in GitHub Desktop.
Abbreviate working directory in bash PS1
# Copyright 2018 Google LLC.
# SPDX-License-Identifier: Apache-2.0
_abbrev_pwd () {
local dir="$PWD"
if [ -n "$HOME" ] && ([ "$dir" = "$HOME" ] || [[ "$dir" == $HOME/* ]]); then
echo -n "~"
dir="${dir#$HOME}"
fi
local -a dir_components
mapfile -d / -t dir_components <<< "$dir"
local n="${#dir_components[@]}"
for ((i=0; i<n-1; i++)); do
local first_letter="${dir_components[i]::1}"
if [ "$first_letter" = "." ]; then
printf %s/ "${dir_components[i]::2}"
else
printf %s/ "$first_letter"
fi
done
echo -n "${dir_components[n - 1]}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment