Creating a file picker with fzf and bash

Published on: Sep 13, 2024 | 2 min read |

Introduction

I always wanted a way to fuzzy find any file(s) in all projects or my configuration, maybe I want to have a look at some code I wrote some time back. I used to always cd into the directory and then open the file in my preferred editor. Although this worked for me, it felt a bit slow and I wanted to improve my workflow, I wanted a way to find any file(s) from my computer without having to cd into the directory where the file is located.

That's why I decided to build a simple file picker shell script with fzf and bat.

The script is simple, it has couple of use-cases

  • finding files globally (search in my entire home directory).
  • finding files locally in the current working directory.

Here's the script to achieve the above mentioned tasks.

#!/usr/bin/bash

search_directory="./"

while getopts 'g:' flag; do
  case "${flag}" in
    g) search_directory="$HOME";;
  esac
done

selected_file=$(find $search_directory -type f | fzf --preview "batcat --color=always --style=numbers --line-range=:500 {}")

echo $selected_file

if [[ -z $selected_file ]]; then
  exit 0
fi

nvim $selected_file

The script accepts one flag specifying whether it should search globally or locally in the current directory, it then passes the output of the find command into fzf showing preview of the files with bat, and then opens the selected file in my preferred editor (neovim btw).

Usage

Search in the current working directory.

file-picker

Search in the entire home directory.

file-picker -g true

File picker in action

Screenshot 2024-09-08 201551

Adding an alias for the file picker.

I created a couple of aliases, so that I don't have to remember the script's name every time I wanted to search.

// .zshrc

alias ff="file-picker"
alias fg="file-picker -g true"

Improvements

I would like to create a flag like -d for searching inside a directory directly, exclude node_modules.

Related Tags
fzfbatbashshellscript
Loading comments...