I'm trying to create a shell prompt that displays the $PWD
in a "smart" way. I want to display the top two directories rather than the full path. If $HOME
is the parent (or parent of the parent) directory, I want to show it like ~
.
Assuming my $HOME
is "/home/user"
, here are a few test cases with expected output according to several $PWD
values:
/ -> /
/home -> /home
/home/user -> ~
/home/user/foo -> ~/foo
/home/user/foo/bar -> foo/bar
/usr/local -> /usr/local
/usr/local/games -> local/games
/home/userr -> /home/userr
Currently, my solution is as follow:
path=$PWD
# $n is the number of "/" in the path indicating that there is more than 2 dirs
# In such case, the path should be truncated
# If the path contains root / (like "/home/usr"), 3 "/" implies 3 dirs
# If the path is "~/foo" then only 2 "/" are required
# If ${PWD} starts with ${HOME}, we can replace this part with "~"
# A slash need to be appended to "${HOME}" to avoid false positive
n=3
if [[ ${path}/ == ${HOME}/* ]]; then
path=~${path:${#HOME}}
n=2
fi
# Count the number of "/" in the path
# If there is more than $n "/", this means the path contains more than 2 dirs
# In this situation, we need to extract the two last dirs only from the path
slashes=${path//[^\/]}
if [[ ${#slashes} -ge $n ]]; then
dir=${path##*/}
parentpath=${path%/*}
parentdir=${parentpath##*/}
path=$parentdir/$dir
fi
echo $path
This function is intended to be used in my bash shell prompt. As this will be issued each time I type a command in my terminal, and as I will keep this in my .bashrc
for probably several years to come, I'm looking to "optimize" this function.
Could the solution have been implemented otherwise, or could this function be improved in some way in order to minimize it's overall "footprint"?