ThePrimeagen / .dotfiles

3.01k stars 303 forks source link

fix: tmux sessionizer now works when not attached #36

Closed brunobmello25 closed 1 year ago

brunobmello25 commented 1 year ago

This PR fixes a bug that happens when you already have tmux running and you are not attached to it. I handled the following use cases:

saccarosium commented 1 year ago

Hi @brunobmello25, I will suggest some changes to the script for make it a little more robust.

#!/usr/bin/env bash

if [[ $# -eq 1 ]]; then
    selected=$1
else
    selected=$(find ~/work/builds ~/projects ~/ ~/work ~/personal ~/personal/yt -mindepth 1 -maxdepth 1 -type d | fzf)
fi

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

selected_name=$(basename "$selected" | tr . _)

# you are not in tmux
if [[ -z $TMUX ]]; then
    if ! tmux has-session -t "$selected_name" 2>/dev/null; then
        tmux new-session -ds "$selected_name" -c "$selected"
    fi
    tmux attach -t "$selected_name"
# you are in tmux
elif [[ -n $TMUX ]]; then
    if ! tmux has-session -t "$selected_name" 2>/dev/null; then
        tmux new-session -ds "$selected_name" -c "$selected"
    fi
    tmux switch-client -t "$selected_name"
fi

Basically the idea is that the if the variable $TMUX is empty (checked with the flag -z) you are not currently in tmux. If $TMUX is not empty (checked with the flag -n) you are inside tmux.

Also because tmux has-session -t "$selected_name" 2>/dev/null returns a boolean. There is not need to have separate checks, you can check it ones.

I highly suggest you that you should start to lint your scripts with shellcheck (it has also integration with neovim with null-ls). Also another great resource to learn bash is the bash-bible.

Warning Shameless plug

Also if you want a more feature full script you can check out my take on tmux sessionazier.