unixorn/fzf-zsh-plugin

View on GitHub
bin/tm

Summary

Maintainability
Test Coverage
#!/usr/bin/env bash
#
# tm - create new tmux session, or switch to existing one. Works from within tmux too. (@bag-man)
# `tm` will allow you to select your tmux session via fzf.
# `tm irc` will attach to the irc session (if it exists), else it will create it.
#
# Source: https://github.com/junegunn/fzf/wiki/examples

set -o pipefail
if [[ -n "$DEBUG" ]]; then
  set -x
fi

function fail() {
  printf '%s\n' "$1" >&2  ## Send message to stderr. Exclude >&2 if you don't want it that way.
  exit "${2-1}"  ## Return a code specified by $2 or 1 by default.
}

function has() {
  # Check if a command is in $PATH
  which "$@" > /dev/null 2>&1
}

tm() {
  [[ -n "$TMUX" ]] && change="switch-client" || change="attach-session"
  if [ "$1" ]; then
    tmux "$change" -t "$1" 2>/dev/null || (tmux new-session -d -s "$1" && tmux "$change" -t "$1"); return
  fi
  session=$(tmux list-sessions -F "#{session_name}" 2>/dev/null | fzf --exit-0) &&  tmux "$change" -t "$session" || echo "No sessions found."
}

if has tmux; then
  tm "$@"
else
  fail "Can't find tmux in $PATH"
fi