So not long ago there was this thread on lobste.rs about useful shell aliases. I like reading this kind of thing. People can get very clever trying to be lazy.
But what stood out to me this time was the number of people that posted some variant of alias ..='cd ..'
. If you’re working your way back up a deeply-nested tree, you can get there much more easily than by mapping pairs of dots and slashes to directory names.
What’s better than ../
, you may ask? Words. Even better? Fragments of words. At-best fuzzily-remembered fragments of words. fzf
to the rescue.
If you know a few names in the directory you want to get to, you can fuzzy-jump down the tree:
And fuzzy-jump back up:
The jump forward can use a cache file instead of reading your home directory every time.
# For fuzzy-jumping down your home directory.
function fcd {
cache=~/.config/home-dirs-list
if (( $# == 0 )); then
if [ -e $cache ]; then
cd "`fzf --height=10 < ${cache}`"
else
echo "No directory cache."
cd `find ~ -type d | fzf --height=10`
fi
elif (( $# == 1 )); then
if [[ $1 == "--cache" ]]; then
echo "Making home directory cache."
find ~ -type d | sort > $cache
elif [ -e $cache ]; then
cd "`cat ${cache} | grep $1 | fzf --height=10`"
else
echo "No directory cache."
cd `find $1 -type d | fzf --height=10`
fi
else
echo "Usage: fcd [DIR]|--cache"
fi
}
The jump backward only needs the current directory.
# For fuzzy-jumping backwards.
function bwd {
dirs=()
dirs+="/\n"
dir=`pwd`
parts=("${(s|/|)dir}")
prev=""
for part in $parts
do
prev="${prev}/${part}"
dirs+="${prev}\n"
done
cd `echo ${dirs} | fzf --height=10`
}
Put those in your ~/.zshrc
and try it. It’s just like teleporting.
Weirdly, nobody in the Lobsters thread mentioned cal
. I fuzzy-jump all the time, but I also use cal
all the time, and I intensely dislike how the default cal
doesn’t highlight the current date.
So alias cal='ncal -C'
would make my list, too.