Skip to content

Instantly share code, notes, and snippets.

@askhat
Last active December 13, 2016 20:08
Show Gist options
  • Select an option

  • Save askhat/784dbd1b856a0e138fd6192abee67abc to your computer and use it in GitHub Desktop.

Select an option

Save askhat/784dbd1b856a0e138fd6192abee67abc to your computer and use it in GitHub Desktop.
Cruise between tmux sessions easily
#!/usr/bin/env bash
ARG=$1
function name {
if [ -n "$ARG" ]; then
echo $ARG
else
echo $(basename $(pwd))
fi
}
function sessions {
echo $(tmux ls -F '#S')
}
function exists {
if [[ $(sessions) =~ $(name) ]]; then
true
else
false
fi
}
function not_in_tmux {
if [ -n "$TMUX" ]; then
false
else
true
fi
}
if exists && not_in_tmux; then
tmux attach -t `name`
elif exists; then
tmux switch-client -t `name`
else
tmux new -ds `name` && tmux switch-client -t `name`
fi
@matthiasbeyer
Copy link

matthiasbeyer commented Dec 12, 2016

Waaaay to verbose.

Here is a version without all the unecessary stuff around (untested, though):

#!/usr/bin/env bash
name=$([ -n "$1" ] && echo $1 || echo $(basename $(pwd)))

function exists {
  [[ $(tmux ls -F '#S') =~ "$name" ]]
}

if exists && [ -n "$TMUX" ]; then
  tmux attach -t $name
elif exists; then
  tmux switch-client -t $name
else
  tmux new -ds $name && tmux switch-client -t $name
fi

@jferguson-gnubio
Copy link

name=${1-$(basename $(pwd))}

@jferguson-gnubio
Copy link

jferguson-gnubio commented Dec 12, 2016

My slight variation would then be:

#!/usr/bin/env bash

name=${1-$(basename $(pwd))}

if [[ $(tmux ls -F '#S') =~ "$name" ]]; then
    if [ -n "$TMUX" ]; then
        tmux attach -t "$name"
    else
        tmux switch-client -t "$name"
    fi
else
  tmux new -ds "$name" && tmux switch-client -t "$name"
fi

@runar
Copy link

runar commented Dec 12, 2016

I don’t remember where I found it, but I’ve been using this without any issues for quite some time:

#!/usr/bin/env bash

function tnew() {
  if [ -z "$1" ]; then
    session_name=$(basename $PWD:gs/./)
  else
    session_name=$1
  fi
  tmux new-session -As $session_name -n 'main'
}

From the manual: The -A flag makes new-session behave like attach-session if session-name already exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment