DEV Community

neymarsabin
neymarsabin

Posted on

Fuzzy find project and auto attach-session in tmux

I wrote this handy shell script to fuzzy find my projects and auto attach them to a new tmux session. It is minimal and it works!

#!/usr/bin/env sh
# define the fzf command: ./.fzfdir.sh pet
# syntax: ./.fzfdir.sh <working_directory>
# note: I have base_dir as ~/projects
# FZF_COMMAND="fzf-tmux"
FZF_COMMAND="fzf-tmux -p --with-nth 1"

# find in directories
workdir=$1
base_dir=~/projects
find_dir=$base_dir/$1

# execute command
RESULT=$(ls $find_dir | $FZF_COMMAND)

# create a new tmux session and attach to it
window_name=$RESULT
session_name="neymarsabin/$window_name"
workdir=$find_dir/$RESULT
send_command="cd $workdir"

if ! tmux has-session -t $session_name 2>/dev/null; then
  ## create new session, provide SESSION and WINDOW name
  new_session=$(TMUX= tmux new-session -A -d -s $session_name -n $window_name)

  ## switch and cd into project
  tmux switch-client -t $session_name
  tmux send-keys -t $session_name:$window_name "$send_command; clear" C-m
else
  tmux switch-client -t $session_name
fi
Enter fullscreen mode Exit fullscreen mode

And, let's bind this to a keybinding in tmux.

bind-key "t" run "~/.fzfdir.sh oss"
Enter fullscreen mode Exit fullscreen mode

You can modify the shell script to your use case. You can checkout the implementation at: https://github.com/neymarsabin/dotfiles_reloaded/blob/trail/scripts/fzfdir.sh

Top comments (0)