A handy fzf function for jumping into nested directories

0
1
Asked By MellowPine47! On

I got tired of typing long, deeply nested paths with cd, so I put together this small Bash function:

```bash
fcd() {
local dir
dir=$(find "${1:-.}" -type d 2>/dev/null | fzf) && cd "$dir" || return
}
```

After adding it to .bashrc and starting a new shell, running fcd lists directories beneath the current location. You can type to filter the list, press Enter, and jump straight into the selected directory. Passing a path such as fcd ~/projects lets you search from a specific starting point instead.

It works well for me, but I'm wondering whether there's a faster or cleaner approach for very large directory trees.

5 Answers

Answered By CobaltMango82 On

There’s already a similar directory picker included with fzf, usually available through the Alt-C key binding. It may be worth enabling the shell integration before maintaining a separate function.

MellowPine47! -

Thanks, I’ll check out the built-in version.

Answered By VelvetOrbit31 On

With fzf’s shell completion enabled, you may not need a function at all. In Bash, a pattern such as `cd **` can open an interactive directory search, after which you can type to narrow the results. The exact setup depends on where the fzf completion and key-binding scripts are installed.

Answered By SilverKite904 On

For frequently visited locations, zoxide or another directory jumper can be faster than scanning the filesystem every time. These tools rank paths based on your history, so the directory you want is often near the top. An fzf picker is still useful when searching an unfamiliar subtree.

AmberField27 -

That trade-off makes sense: history-based jumpers are faster for common paths, while a filesystem scan is better when exploring somewhere new.

Answered By NorthStar_Q8 On

One subtle Bash issue is declaring and assigning the variable in the same command, such as `local dir="$(...)"`. The exit status can become the status of local rather than the command substitution, which may cause the function to continue even when fzf is cancelled. Keeping the declaration separate, as in the original example, avoids that problem and lets the `&& cd` check work properly.

Answered By QuietHarbor6 On

Using fd instead of find can make this noticeably quicker and gives you simpler syntax:

```bash
fd . -t d "${1:-.}"
```

You can pipe that into fzf in the same way.

MellowPine47! -

Good suggestion—I’ll try fd for larger directory trees.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.