Bash script for selecting tmux session

Problem

You want to list and select from several available tmux sessions

Solution

If necessary, install iselect:

sudo apt-get install iselect

Create an executable script called tsel:

#!/usr/bin/env bash

CHOICE=`tmux ls | iselect -a`
[[ ${#CHOICE} == 0 ]] && exit 0 # Just exit if nothing selected

SESS=${CHOICE/:*/}
tmux att -t "$SESS"

Obviously, the script must be stored somewhere on your $PATH.

Discussion

iselect is a tool that has many uses. It takes in a list of items, and displays them in a console as a menu. The user can then select one of those items, which is printed out. In the script above, CHOICE is set to the user’s selection of tmux sessions.

The script just exits if the length of the choice is 0. This can happen if the user types q to quit iselect.

tmux ls has output in the form of the session name, followed by a colon, followed by other information. The script needs just the session name, and needs to discard all of the other output. This is achieved using bash’s pattern-matching facilities:

SESS=${CHOICE/:*/}

At this stage, the script has the session name in its pure form. This session name is passed to tmux’s attach command.

Advertisements

About mcturra2000

Computer programmer living in Scotland.
This entry was posted in Computers and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s