top | item 45342943

Zoxide: A Better CD Command

324 points| gasull | 5 months ago |github.com

194 comments

order

Latty|5 months ago

I tried zoxide for a while but I really disliked how it made things fuzzy, and most of the use cases for it I found were 90% solved by using ZSH's history search which I use routinely anyway.

It gives you this potentially constantly shifting set of shortcuts, essentially, and the problem is that means I have to constantly check I did get the result I wanted, and that I haven't accidentally gone to the wrong place. I found that more annoying to me than just using tab completions or history, which are much more predictable.

I can see how someone who has different workflows or environments might find it great though.

robenkleene|5 months ago

How are you using Zsh history to navigate to specific folders? E.g., does that mean you always start your `cd` from the home directory (e.g., `~`)? I'm asking because it's usually less key strokes to `cd` to a relative directory (assuming you're working in several related directories). But then the `cd` entry in your history would assume a specific starting path (and therefore wouldn't be universally helpful to recall from history)?

Also, re:

> the problem is that means I have to constantly check I did get the result I wanted, and that I haven't accidentally gone to the wrong place.

Is there a reason you don't add your current path to your prompt? I don't know how I'd work without that, never knowing which directory I'm in.

yonatan8070|5 months ago

I generally work in only a few folders (we'll call them project a, project b, project c), so once I taught it these are high priority, it just works when I type any part of their names

mrcarrot|5 months ago

Yeah, I've been trying it recently and I'm not entirely convinced I want to keep using it.

My biggest annoyance at the moment (and this may be me missing something), is that I have two directories: "thing" and "thing-api". I'm doing work in "thing" much more often than in the "thing-api", but whenever I run "z thing", it takes me to "thing-api" first, and I have to "z thing" again to get to where I wanted to go. It ends up being more effort than if I'd just tab-completed or history searched a plain cd command.

eviks|5 months ago

You're right, "z d" to always to always go to your downloads folder if way more powerful than whatever fuzzy match can achieve, and unfortunately the project didn't want to add a predictable input mechanism, though maybe that'll change in the future...

sandreas|5 months ago

I use fzf completitions

  source <(fzf --zsh) > /dev/null
and the ** shortcut followed by <TAB>, e.g.

  cd ~/** # <TAB>
along with cd - to change to the directory before

  cd -

stared|5 months ago

For me, this simple tools is the single best command line changer! Instead of a lot of commands to traverse the folder tree, I jump where and when I want.

Other nice tools I use: Fish for shell (https://fishshell.com/), Starship for prompt (https://starship.rs/), bat "a cat with wings" for file preview (https://github.com/sharkdp/bat).

zem|5 months ago

rg and fd are the ones I use the most, much improved user experiences over grep and find respectively

kritr|5 months ago

One useful thing I discovered recently about zoxide is that it has a basedir flag, so in theory you scan scope your query to the directory you’re in or based off some git root.

something like

alias zg=‘zoxide —basedir $(git rev-parse --show-toplevel)’

https://github.com/ajeetdsouza/zoxide/pull/1027

hannesfur|5 months ago

Wow! That's really useful!

elcapitan|5 months ago

cd alternatives always give me PTSD from one of my earliest computer memories, aged 13 or so. That was on DOS 3.3 on my parents 286, and I had recently installed some Norton utilities, among them ncd (Norton Change Directory), which kept its own database of directories and allowed for fuzzy cd with regex.

It was quite cool to see the power of such a tool, until the day I wanted to ncd into a directory with some code experiments I had built and just delete them all. Unfortunately the completion sent me into another directory, which I noticed after deleting all my parents tax documents.

DOS 3.3 didn't have an undelete command like later versions of DOS, so a colleague of my dad had to spend an evening trying to restore some of that data with some external tools. On the positive side, he also installed DOS 6.22 (we were really behind).

esafak|5 months ago

I guess you learned what a FAT was that evening.

brontosaurusrex|5 months ago

I've been using autojump, called with 'j'. Any pros of zoxide over that? https://packages.debian.org/sid/autojump

joelthelion|5 months ago

Initial creator of autojump here: just use zoxide. I passed autojump mainternship to someone else a few years ago but it has now been abandoned. Rust is superior to python for this application anyway.

neobrain|5 months ago

I don't use autojump, but glancing over its readme it's missing nushell integration that zoxide provides.

It being a native binary instead of Python-based might also help it execute more instantaneously. Most Python-based CLI helpers that I tried add a slight but noticeable delay to simple commands, whereas zoxide is so quick it's easy to forget you even invoked a helper in the first place.

jgb1984|5 months ago

I was using autojump for years (on debian) until I lost my jump history several times in the past few months. Turns out it's a known race condition bug fixed in a newer version:

https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1110899

Migrated to zoxide instead, seems to work fine! Only need to get used to using z instead of j, muscle memory hard to adjust, might set an alias :)

donatj|5 months ago

This has me lamenting just how fiddly it really is to implement a standalone "cd" that isn't a builtin.

I am certainly there are a whole host of security reasons not to, but it sure would be handy if a parent process could easily just read the final state of all environmental variables of a child process and possibly integrate them back into its own.

Shells could just have a syntax for accepting sub process environmental variables. I'd propose something easy like starting a line with = absorbing all set environmental variables.

We could build a custom cd tool, "custom-cd-bin" in this example and all that would need to do is change the PWD variable.

  $ =custom-cd-bin ./foo
Maybe this will be something for my dream shell I'm never going to actually get around to building. It would take something gross like wrapping setenv though

ffsm8|5 months ago

Mmh, that's kinda... Exactly what `source` is.

It's just rarely used beyond dotfiles because... Well.. it inherits all variables etc

https://docs.vultr.com/how-to-use-the-source-command-in-bash

If you want to make the transition explicit at the end of the script, you can do what the sister comment did, essentially

"source <(bash the-script|grep -Pom "xx inherited variables\n(.*?)\n yy inherited variables")"

linsomniac|5 months ago

So you're thinking something like before the wait(2) reading /proc/$PID/environ ?

tcoff91|5 months ago

It’s just so good.

fzf and zoxide are probably my two most game changing cli tools. They make the terminal feel so good.

tcoff91|5 months ago

I actually made a git worktree aware function called w that wraps zoxide and will basically switch to the main worktree, execute z, and then switch back to the worktree you came from. That way you don’t run into zoxide switching from one worktree to another annoyingly, and new worktrees immediately inherit your zoxide scores. You purge all other worktrees from the zoxide database and use w instead of z inside git repos.

I haven’t used it in a while though because I switched from git to jj.

GNOMES|5 months ago

I have been testing this as a daily driver since the last big mention on HN to simplify my .bashrc file.

I use it with `eval "$(zoxide init bash --cmd cd)"` so I can continue to use CD due to muscle memory.

    - I like that if there are multiple /foo directories known by Zoxide, say /foo/ and /abc/foo/, that you can do `cd abc foo` to go the path containing both.

    - I am not a fan of having to do `cd foo**` for tab completion to folders outside CWD. I feel it slows me down as a tab complete fanatic.

    - Also don't enjoy if I `cd foo/bar/batz` directly, then try `cd bar`, Zoxide has no reference. You would need to CD into each directory individually to build the database. I have seen scripts kicking around online to put a complete directory structure into Zoxide database by CD'ing to each subdirectory for you.
Not sure if I am officially sold, or I'll go back to aliases and simple tab completes forwards, and backwards (logic I use for tab complete backwards to exact directory name backwards from CWD instead of `cd ../../../etc` https://gist.github.com/GNOMES/6bf65926648e260d8023aebb9ede9...)

jmarchello|5 months ago

I love shell tools, and by no means disparage the use of zoxide, z, etc. But I find I get 90% of the usefulness of these tools using the native cd command and adding my most used directories to CDPATH.

This additionally is consistent and works without needing to “train” it first.

stavros|5 months ago

I agree, but I get 100% of the usefulness of these tools by installing them with one command and using them. Why settle for 90% when 100% takes a second?

achristmascarl|5 months ago

I used zoxide for a while before realizing that the `zi` command allows you to search for your desired destination before changing directories. I use it instead of the default `z` command the vast majority of the time now.

xwowsersx|5 months ago

I had no idea about this. Super helpful. Thank you!

BeetleB|5 months ago

I see several comments saying they use fzf instead of zoxide.

You should use both in tandem!

Several years ago, I set up a keybinding that presents me all the directories stored in the zoxide[1] DB in fzf - in rank order. With just a few keystrokes, I get where I need to be, and I'm not presented with all possible directories - just ones I've visited in the past.

This solves the problem of "I want to go to a directory that's not the most ranked one for the string I typed, and zoxide keeps putting me in the other one".

Once you have this flow, there's no going back!

[1] Actually, I use autojump, but it should work with zoxide as well.

a3w|5 months ago

I barely use pushd/popd, for me this would be overkill, and I dislike the side effects. I mostly use my history, so same command needs to reliably do same thing. Workaround for cd-ing:

cd ~/foo; $COMMAND ; #optional cd ~ here

My history is full of this

larusso|5 months ago

I can’t see myself using this. I have a mental map of my folder structure and am actually proud that I can navigate and type the structure fast enough to move around. I feel that remembering which directory was last and adding some matching overhead is too much for my use case. I also use the zfs history heavily with fzf. And similar to another comment I usually work from same paths, be it a project root or my home directory. In any case I think it’s still valuable to break with the norm and explore other ways of using the shell. This time around it ain’t for me though.

cb321|5 months ago

Once you have a little frecency command-line utility like https://github.com/c-blake/adix/blob/master/util/lfreq.nim (inspired by this very HN thread!) and then either fzf, vip (https://github.com/c-blake/bu/blob/main/doc/vip.md), or whatever, the essence of the idea is really just two lines of Zsh code (https://github.com/c-blake/bu/blob/main/doc/vip.md#combining...). It's only a couple dozen more to have a more robust/complete system, though with shared-across-shells PWD histories and long-term saving somewhere with lock files.

As another example of why a simple CL utility for frecency alone is nice, you can basically replicate https://github.com/kantord/frecenfile with a shell 1-liner:

    git log --pretty=format: --name-only | tac | sed '/^$/d' | lfreq -n9 -o.999
In a little timing test I did this morning, that was about 270X faster than the git log itself on the Linux kernel (61 seconds to git log, but only 227 ms to `lfreq` it).

Besides all that, there's also the distributed-with-Zsh `cdr` (`man zshcontrib` or similar to read all about that).

mythz|5 months ago

zoxide alongside fzf, eza, bat and starship were my killer CLI productivity tools I discovered after ditching Windows for Fedora. I have it aliased to `cd` so I don't really notice when I'm using it until moving to a Terminal that doesn't have it.

anhkhoakz|5 months ago

Love starship but it may slow your first command @@

tqwhite|5 months ago

I installed it as cd. I do not think I ever, even a single time, used it differently from normal cd. It turns out that my system is organized so that I know where everything is.

On the rare occasion something is lost, it's a file, not a directory. Then I Spotlight (Mac super find) because it also searches content

stavros|5 months ago

Eh, all my stuff is, say, in Code/Projects/Django/deadmansswitch, but it's great to be able to do `z dead` instead of typing the whole thing out.

rukenshia|5 months ago

I tried zoxide, but at the end settled for using fzf to quickly find and enter directories:

  qcd () {
   local d
   dirs=$(fd -t d -t l --ignore-file ~/.gitignore . $@)
   d="$(echo ${dirs} | fzf +m --height=50%)"  && cd "${d}"
  }
  
  alias hd="qcd ${HOME}"

Zizizizz|5 months ago

There's a built-in shortcut with fzf to change directories I think it's alt+d

tpoacher|5 months ago

This is nice, but ... I wish the doc didn't introduce it as "a better cd command", that's very misleading.

With the exception of the fuzzy part, which can be added separately, Bash already has facilities for all of those functionalities.

The "remembering" part can be done via dirs/pushd/popd. The "using the basename only" part can be done via CDPATH. The "automated" remembering could be done via a super simple function wrapper over 'cd', adding things onto the the dirstack or the CDPATH respectively (and with a selection menu, possibly fuzzy, when clashes occur)

Putting it all together to achieve the same effect feels like a very simple 10-liner bash function at best.

Not dissing the author's work or idea, nor is there anything wrong with reinventing the wheel in another language for fun; but if you're going to claim that "z is a better cd" because it bundles all that other functionality for things that are unrelated to cd, and for which there are already pretty decent unix-philosophy-adhereing commands that you could be using effectively already, then if you fail to mention these things in your documentation, it feels a bit ignorant / disingenuous. I would have preferred examples with "without z you'd have to use CDPATH for this, and dirstack for that, and maybe this 5-line wrapper for the menu thing, etc".

Otherwise it feels a bit like saying "grep is a better ed" or something.

robenkleene|5 months ago

I think you're misunderstanding the authors intention. Fuzzy finding is the banner feature of zoxide, i.e., it's only a better cd because it includes that feature. Everything else is just the necessary table stakes features in order to make zoxide a viable cd alternative. E.g., it's not notable that zoxide copies the rest of the useful features from cd in Bash, because that's exactly what it would need to do in order to be a cd replacement.

What you could argue with is whether there's a point to replacing the cd built-in in order to include fizzy finding (personally I don't see the point of this either). But the reason all the other cd features are included is in order to make that viable.

bjackman|5 months ago

Does anyone know if zoxide has any fancy logic to ignore strings that appear in common prefixes?

For example I have a big ~/src dir where I keep all my code checkouts. If I type 'z src' intending to go to ~/src/foo/bar/src, will it be clever enough to realise that I am referring to the second instance of the string 'src'?

I currently use a Fish port of the original 'z'. It does ignore the common prefix of _all_ matches (so if I only ever used it within my ~/src tree, the problem would disappear) but after that binary exclusion it works exclusively on frecency.

neobrain|5 months ago

Adding to the other answer: You can also pass multiple keywords to zoxide and they are expected to match in order. So in your example, `z foo src` would reliably cd into `~src/foo/bar/src` even if `src/foo` has a higher visit frequency.

ShinTakuya|5 months ago

As far as I'm aware it keeps a history of the frequency you visit each directory so yes it will select the one you've visited more often (assuming you don't always start at the base one and work your way down).

desireco42|5 months ago

I think this is awesome tool, but somehow using fish shell does most of what I need and rarely I reach for it. This is not a critique of Zoxide, but just the fact that this is not as big of a problem once it was.

carlosneves|5 months ago

I was going to say that. Gratitude to the creators of fish shell. The history-based rank is immediate as you type. Lately I've simply done:

abbr --add c cd

And then the "most used paths" are just present in the history filtered by the prefix I already typed.

maherbeg|5 months ago

huh, I don't seem to have this enabled at all. My cd in fish only shows the current directory choices

ktosobcy|5 months ago

I tried some alternatives and while some works (bat, rg, fd) others don't (fzf and said `zoxide`)... most of the time they usually get in the way more…

serial_dev|5 months ago

Interesting to read the different threads, it sounds like most of the shortcomings of this tool can be somehow "configured away", but at that point, just configure your terminal by adding suggestions, plugins, etc, then you'll have all what you need for every command, not just CD.

dayvster|5 months ago

Zoxide is a bit more than just that, it creates and index as you are using it, the more you CD into dirs the higher priority they will be.

mkw2000|5 months ago

I wouldnt say I cant live without it , but it saves me a few seconds here and there and its a great tool!

rollcat|5 months ago

If you want a simpler and less invasive "improved cd", you can do this in ZSH:

    chpwd() {
        ls
    }
It does what it says: after changing the cwd, list its contents. You can try other things, e.g. "[ -d .git ] && git status".

akdor1154|5 months ago

What i really want is a `mkdir --cd` - annoying to code without shadowing real mkdir though.

linsomniac|5 months ago

I have a shell function "md" that does a "mkdir -p" and then cds into it. In fish:

    function md
      if test -z "$argv"
        echo "md: Must supply an argument: The directory to create+cd into"
        return 1
      end
      mkdir -p "$argv"
      cd "$argv"
    end

quesera|5 months ago

This works in sh, bash, zsh, etc:

  mkdircd() { mkdir -p "$1" && cd "$1" }

  mkdircd /tmp/new/directory/at/arbitrary/depth

ramon156|5 months ago

it's weird how most IDE's already figured out people want this. I can type in "New File" > "/foo/bar/baz" and it will work just fine. Is there any limitation as to why mkdir can't support recursive generation?

mubu|5 months ago

How is this any different from z?

OJFord|5 months ago

Not having heard of either of these before, but now seeing z linked by sibling comment too, I would guess 'z oxide' is a Rust re-implementation of z.

aquova|5 months ago

There's a few different versions of this same idea, I think zoxide is the third one I've used. Years ago, I started using z.lua, then switched to a fish shell plugin implementation of z, finally to zoxide. I don't think there's any real difference between them, aside from their implementation language and the ease of installation.

stranges|5 months ago

The main difference is speed (Rust vs shell script)

UK-AL|5 months ago

Zoxide normally aliases to z. Is this not z?

dag11|5 months ago

This is z, no?

kh_hk|5 months ago

Ctrl+r in zsh already gives you fuzzy search. In the rare case I have to go to a long path that I can't remember I use that, but for most cases, cd <tab> [...] <tab> <enter> suffices if I am feeling really lazy

Starlevel004|5 months ago

I tried using z for a while but I got mad every time I typoed, failed a tab-complete, and ended up in some random directory halfway across my disk instead of doing nothing.

thibran|5 months ago

zoxoide, rg, fd, jj and Nushell are my command line favorites.

ivanstame|5 months ago

Rust people trying to replace stuff that already works...

k__|5 months ago

Seems like a bit fancier "cd -" to me.

pmkary|5 months ago

To know haw bad CD, is to realize it's the second time in half of a year that Zoxide is featured in the main page.

amelius|5 months ago

I have a lot of paths that end with ".../src"

Looks like the tool doesn't handle that case very well.

jbrnh|5 months ago

I would say it might, with the 'zi' variant (cd with interactive selection (using fzf)).

Zizizizz|5 months ago

One of those fundamental work-changing tools. I use it dozens of times a day. It's fantastic

smartmic|5 months ago

Is it just me, or is it actually a new trend that the first thing on the README page is an advertisement? Could this perhaps even be related to the AI glut?

In any case, aberrations such as the excessive use of emojis and exaggeration are becoming increasingly common, which is yet another reason for me to distance myself from GitHub. For me, a README that more closely follows the conventions and minimalism of a classic man page is a sign of quality, and it could perhaps even be rendered in plain text to achieve a high signal-to-noise ratio.

benrutter|5 months ago

Warp seems to have sponsored more or less every CLI tool these days- I don't think I've ever seen other companies advertised though somehow?

hannesfur|5 months ago

It definitely got more widespread, but I am not sure that it's related to AI. If it's a way for open source maintainers of awesome tools I use to fund their development, I am totally fine with that.

OJFord|5 months ago

It's older than AI, I think people do it because it seems to work - where 'work' means builds hype and 'community' and GitHub stars fast.

transitivebs|5 months ago

love zoxide; been using it for a long while as a replacement for built-in `cd`

dayvster|5 months ago

Zoxide is amazing and I can't live without it since I switched to it.

esafak|5 months ago

nushell supports going up arbitrary number of levels like so: cd ..../foo, and that's the only feature I've ever missed in cd, so I'm all set.

peauc|5 months ago

I couldn’t live without it now. Very simple yet effective tool

ulfbert_inc|5 months ago

Please replace CD with cd in the title, it's misleading.

yerlantemir|5 months ago

super happy to be a super of such an amazing tool, thank you!

lproven|5 months ago

Is it just me or does this description sound like an improved hammer?

I mean, it's a hammer. It's fine. You can hit things. And pull out nails.

This thing runs on batteries and needs syncing and it's a hammer. It didn't need improving. It's an improvement on a rock, and it's all improved out.

ryzvonusef|5 months ago

there are CLI tools that are combining most of these package in one go, like Yazi, that are gaining popularity in the TUI community.

Svoka|5 months ago

Honestly, love seeing some cool Rust written memory safe CLIs at HN at the same time as blog post of zig fanboys who couldn't.

Way to go.

tehryanx|5 months ago

this feels like a hundred accidents waiting to happen.

jlnthws|5 months ago

Those kind of tools should have the same name as the command they replace, I don’t want to change my workflow with this or that. I think a simple wrapper over cd with fzf is good enough and much simpler. Claude can probably write it in a few minutes.

jlnthws|5 months ago

Of course you can alias, but I was not very clear indeed. My point is that these tools ship multiple commands (z, zi, etc. autojump does too). I treat core shell commands as interfaces: keep the name, swap the implementation. If there's just one command, you can of course alias it (but why should I do this final step); if there are many, it turns into clutter. These tools should enhance existing commands instead of reinventing them: the goal is the same result, just faster and better. The philosophy is non-intrusive augmentation, like bash_completion or fzf.

tristan957|5 months ago

That's what an alias is for. I don't want that behavior, but you are free to do it for yourself.

squigz|5 months ago

Or you could use shell aliases.