15

I often use fzf to navigate the filesystem, especially the Alt-c key binding.

When invoked, fzf generates a list from the current working directory.

Is it possible to make fzf generate a list from a specified directory?

I have tried fzf <dir>, but it results in an error (unknown option). Also, I can't find any options like -C <dir> for specifying the start directory.

1

5 Answers 5

7

Assuming you're using bash or similar, this is built into the default completion options which get installed with fzf: https://github.com/junegunn/fzf#fuzzy-completion-for-bash-and-zsh

tldr; enter start file or directory, append ** and hit Tab. So if you'd enter cd /foo/** then tab opens fzf with /foo as start directory.

edit at the time of writing the commands for which this works are hardcoded in fzf's bash helpers, which is why this works for cat and cd but not for tac or nano. This is the complete list:

awk cat diff diff3
emacs emacsclient ex file ftp g++ gcc gvim head hg java
javac ld less more mvim nvim patch perl python ruby
sed sftp sort source tail tee uniq vi view vim wc xdg-open
basename bunzip2 bzip2 chmod chown curl cp dirname du
find git grep gunzip gzip hg jar
ln ls mv open rm rsync scp
svn tar unzip zip

To add other commands use this in e.g. your .bashrc, after the place where fzf gets sourced (something like [ -f ~/.fzf.bash ] && source ~/.fzf.bash):

__fzf_defc "tac" _fzf_path_completion "-o default -o bashdefault"

Alternatively: open an issue to ask for the commands you want to be added to fzf by default, things like tac and nano are super common anyway.

3
  • Nice, hadn’t thought about that! Which commands does that work for? It works for cat, but not for tac.
    – Shuzheng
    Commented Apr 12, 2021 at 10:26
  • I always assumed it works for everything (which is also what the documentation COMMAND [DIRECTORY/][FUZZY_PATTERN]**<TAB> seems to imply). So if it doesn't I'd say that's a bug. Well, or us not understanding the purpose correctly :)
    – stijn
    Commented Apr 12, 2021 at 13:05
7

I had a more general issue which might be useful for you. The following is from a blog post I wrote about it:

Configuring FZF to search useful directories beyond the working directory

I use fzf both as a command line tool and from within Vim using the fzf.vim plugin. It makes finding (and opening) files intuitive, fast, and frees you from needing to remember their location or exact name. By default, fzf searches recursively within the current directory, which is often just what you want. If you need to search for a file in some directory beyond the current working directory you need to specify that path as an argument to fzf, after which it's business as usual (fzf will recursively search the specified directory).

The Problem

It always felt a shame to have to occasionally precisely specify a path in order to get a fuzzy search going... precisely specifying a path is the exact thing that fzf is supposed to unburden your from! My initial approach was to supply the home directory path and let fzf search everything, the home directory path can be specified in only a couple of characters so there's no real burden in that case.

The problem with doing this is that you end up searching a lot of directories which you know don't have the file you want. The main offenders were directories you end up with if you install say, anaconda3. The results would be swamped with thousands of internal files, with very long paths. The long paths tended to 'soak up' any letters I entered in the search, so it was difficult for fzf to filter them out.

The Solution

You can choose which searching tool fzf uses under the hood. The default is the standard linux find command, but you can also use fd, ripgrep or silver searcher. Apart from being a lot faster than the default find, these latter tools respect .ignore files. This means that fzf will skip any files or directories listed in a .ignore file. We can turn this feature to our advantage.

First, we install fd. If you run Ubuntu 19.04 (Disco Dingo) or newer, you can install the officially maintained package:

sudo apt install fd-find

If you use an older version of Ubuntu, you can download the latest .deb package from the release page and install it via:

# adapt version number and architecture
sudo dpkg -i fd_8.2.1_amd64.deb

Now we configure fzf to use fd by adding the following line in your .bashrc:

export FZF_DEFAULT_COMMAND="fdfind . $HOME"

If you're using an older version than Ubuntu 19.10, the above line needs to be modified like so:

export FZF_DEFAULT_COMMAND="fd . $HOME"

Now fzf will always search recursively from the home directory, and respect any .ignore files. So let's make one in the home directory:

touch ~/.ignore

I find that the list of directories that I might conceivably (~15) want to recursively search with fzf is shorter that the list of directories that I would never want searched. The total number of files in the directories I want searched is about 5000 or so - easily handled by fd.

In the .ignore file, I first list all my home directories, each followed by a '/':

# start by igoring every home directory
anaconda3/
arch/
cache/
code/
Desktop/
  .
  .
  .

Then below those, put the directories that you want to be searched, each preceded by a '!' and followed by a '/':

# now un-ignore the ones I care about
!code/
!Desktop/
!documents/
!downloads/
  .
  .
  .

The '!' will 'cancel out' the previous ignore commands.

And there we have it. We can invoke fzf wherever we are in the file system and start typing vague things about the file(s) we have in mind and fzf will search in a set of predefined directories and find it with ease. This completely removes the barrier of thinking where a file might be and how precisely it was named.

N.B. I have noticed that, for some reason, a couple of subdirectories were not showing up in the fzf search, and so I explicitly created some '!path/to/missed/directory/' lines in this section...

N.B. You may be wondering "What if I find myself in an unusual directory not on the list, and want to use fzf?". I had the same concern so I put a couple of aliases in my .bashrc that can toggle the above configuration on and off at will (be sure to use 'fdfind' for Ubuntu 19.10+, as disused above):

# restore fzf default options ('fzf clear')
alias fzfcl="export FZF_DEFAULT_COMMAND='fd .'"

# reinstate fzf custom options ('fzf-' as in 'cd -' as in 'back to where I was')
alias fzf-="export FZF_DEFAULT_COMMAND='fd . $HOME'"

If you're using Vim to create the .ignore file, an easy way to get a list of all the directories in your home directory is the following command:

:.!ls ~/

Append a '/' to all lines by putting the cursor on the first directory in the list and entering the following command:

:.,$ norm A/

Similar to above, insert the '!' before each one by putting the cursor on the first directory in the list and entering the following command:

:.,$ norm I!
1
  • I find it rather inconvenient that search results are scoped to the home directory by default, so you have to temporarily override the environment variable to be able to move to a location outside of $HOME. In such a scenario, three steps are required to perform a simple task. See my answer for a more flexible solution. Also, ls is the wrong tool for processing files or data - it is not meant for that. It may work on your local machine, but people with different locale settings may get unexpected results.
    – dbran
    Commented Dec 3, 2023 at 15:58
5

You can do something like:

  • find <dir> | fzf
  • fd . <dir> | fzf

Source.

0

mattb's solution works brilliantly!

With the function below you can ignore setting the behavior with fzfcl/fzf- and provide directly path as an argument to fzf:

f () {
    # is path provided
    if [[ "$1" != "" && -d $1 ]]
    then
            export FZF_DEFAULT_COMMAND="fd . $1"
    else
            export FZF_DEFAULT_COMMAND='fd . $HOME'
    fi
    fzf
}

So for example if you want fzf to search starting in particular dir you can execute:

# current dir
f .
# or another dir:
f <path>

When no arg is provided, then it will execute in $HOME dir according to .ignore rules:

# this executes in $HOME:
f

!Disclaimer:
If fzf is used in other tools/scripts that have a chance of calling this function, it might not be a good idea to overwrite the "f" name with the function.

EDIT: changed naming from fzf to f - overwritting original binary names with functions is a bad idea

0

I would like to suggest an alternative solution:

Instead of overwriting the fzf environment variables, why not just define the options for fzf and fd inside function-scoped variables?

cc() {
    local fd_options fzf_options target

    fd_options=(
        --hidden
        --type directory
    )

    fzf_options=(
        --preview='tree -L 1 {}'
        --bind=ctrl-space:toggle-preview
        --exit-0
    )

    target="$(fd . "${1:-.}" "${fd_options[@]}" | fzf "${fzf_options[@]}")"

    cd "$target" || return 1
}

The advantages

  • If you want the current directory to be the starting point, just run cc (or whatever name you prefer) with no arguments, otherwise pass the desired path (which can be either relative or absolute) as an argument, e.g. cc ~/Downloads. It's simple and easy to remember.
  • Since this method doesn't touch any environment variables, you don't have to re-set them to the default options you need for other command line operations. So you can be as specific as you want without affecting the overall behavior of fzf.

Optional: Include files in search results

Sometimes you can't remember the directory name, only the file name, so it would be nice to be able to select a file and cd to its parent instead.

It's basically the same as the first approach, you just have to include files in your search and check if the selected item is a file to strip the filename from it:

test -f "$target" && target="${target%/*}"

For completeness, here is the full function:

# cc - cd with fuzzy finder
# Usage: cc [path]
cc() {
    local fd_options fzf_options target

    fd_options=(
        --hidden
    )

    fzf_options=(
        --preview='tree -L 1 {}'
        --bind=ctrl-space:toggle-preview
        --exit-0
    )

    target="$(fd . "${1:-.}" "${fd_options[@]}" | fzf "${fzf_options[@]}")"

    test -f "$target" && target="${target%/*}"

    cd "$target" || return 1
}

Note that tree is used to display the file structure of the selected search result. You can, of course, add or remove options to make it the way you prefer.

Examples

Use current directory as starting point:

$ cc

Use another directory as starting point:

$ # absolute path
$ cc ~/Downloads
$ 
$ # from root
$ cc /etc
$ 
$ # relative path
$ cc projects/

Use home directory as starting point:

$ cc ~

In my opinion, this is a more user-friendly approach that doesn't force you to do extra work to reset the environment variables to their initial values, while providing the flexibility to customize the functionality.

1
  • cc is an existing unix tool already. Its used for compiling. Its better to name it other than cc Commented Feb 22 at 20:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.