Automatic Attach/Create With tmux

I’ve read a few posts about tmux and am considering switching to it over screen. The most recent one was Faster TDD feedback with tmux, tslime.vim, and turbux.vim by Joshua Davey. I don’t use Ruby much but the post definitely gave me a lot of cool ideas so my interest in tmux has been reinvigorated. I’ll probably spend some time this weekend tweaking my .tmux.conf and getting comfortable in it.

One “feature” I really wanted was to not have to think about whether tmux has a session open or not. I get this behavior automatically with byobu (Ubuntu’s screen profile + UI) and if you use vanilla screen you can just use the -R option. As far as I can tell this is not possible in tmux so I wrote this bash function:

function tmux {
    if (( $# )); then
        command tmux $*
    else
        if (( $(tmux list-sessions 2> /dev/null | wc -l) )); then
            command tmux attach
        else
            command tmux
        fi
    fi
}

If you execute tmux with no arguments then it will attach to your existing session or create one if needed but if you pass any arguments then they just get passed along to tmux as normal.

Also on GitHub, .bashrc.d/tmux.sh.

One issue I have found so far is that it doesn’t work if I `ssh somebox tmux. I suspect it’s because Bash is evaluating the function on my box not on somebox so I’ll probably end up turning this into a script instead of a Bash function.

Comments are closed.