Monades

Weekly Command: jumping directories with z

April 12th, 2018 weekly-command xnix

This week we are going to review one of my favorite and most used commands. If you move around the command line, you may have experienced the pain of recalling directory structures and typing them over and over to access directories that are distant from each other.

z is specifically designed to fix this pain by allowing you to jump trough directories.

h/t to @luislavena for sharing the existence of z with me.

The basics

z [-chlrtx] [regex1 regex2 ... regexn]

As simple as it sounds, z will take you directly to a directory that matches the regexes you provide, no matter where you are.

It’s worth emphasizing that the argument is a regex, which is especially useful if you are lazy: I usually type the first two or three letters of the directory that I want to access and it’s enough.

z is very easy to install, if you are anxious to try it by yourself head to the install instructions in the README.

An important gotcha: z is only able to take you to directories that you already visited before: it needs a learning phase because of how it works.

How it works

z does its magic by storing the directories you visit in a flat file database and matching your query against this list. This file is located by default in $HOME/.z, but the directory can be changed via the $_Z_DATA variable.

z works so well because this list of directories is ordered based on what the author refers as “frecency” (a term apparently coined by Firefox developers, if you have more info please let me know!) which combines frequency: the amount of time you spend in a directory with recentness: how recently you were in a directory.

A bash session using `z` on the left, the flat file database on the right, notice how it gets updated everytime a directory is visited.
Session using z on the left, flat file database on the right: notice how it gets updated every time a directory is visited.

As you keep navigating directories, the rank maintained by z undergoes aging based on a simple formula:

The rank of each entry is incremented every time it is accessed. When the sum of ranks is over 9000, all ranks are multiplied by 0.99. Entries with a rank lower than 1 are forgotten.

Examples

Command Functionality
z foo cd to most frecent dir matching foo
z foo bar cd to most frecent dir matching foo, then bar
z -r foo cd to highest ranked dir matching foo
z -t foo cd to most recently accessed dir matching foo
z -l foo list all dirs matching foo (by frecency)

Sources



Roberto Dip