alligator's blog

k, z but smaller

Jun 24, 2020

You may have heard of z or zoxide. These tools keep track of frequently visited directories and provide a command to jump to them. For example, if you are often in /var/www then executing z www will take you there from any directory.

I present a tiny shell script alternative to these, k:

k() {
    if [ -z $1 ]; then
        echo $PWD >> ~/.k
        case $1 in
        clean)  sort $K | uniq > ${K}.tmp && mv ${K}.tmp ${K};;
        rm) sed -i -E "\#^${PWD}\$#d" ${K};;
        ls) cat ${K};;
        *)  cd "$(grep -e "$1" ${K} | head -n 1)";;

I've also created fish and (somewhat limited) batch script versions, available in this gist along with the original.

I can take no credit for this, I discovered it in this comment and have had it in my bashrc ever since. Sometimes all you really need is thirteen lines of bash.

It is used like so:

go to some directory
  $ cd /var/www

add it to the list
  $ k

go somewhere else
  $ cd /

go back to the saved directory
  $ k www
  $ pwd

show the saved directories
  $ k ls

remove a saved directory
  $ k rm /var/www

Saved directories are stored in ~/.k. This list must be built manually by running the k command in directories you want to save, but I didn't find this difficult. There's only a handful of directories I need quick access to.

Finally, a comparison of the lines of code in k, z and zoxide (as reported by cloc):

tool loc
k 13 (shell)
z 191 (shell)
zoxide 1093 (rust), 110 (shell)

This isn't to disparage z and zoxide (especially z, it's quite marvellous for a few hundred lines of shell script), just a lighthearted reminder that worse can often be better.

blog index