Execute Common Commands via Tmux

In a previous post, we tried to source our shell aliases and functions in remote environments thru Terminator. One month later, I found still too much keystorkes for running my shortcuts. It gets worse when executing commands on multiple VMs without devops tools. So this time let’s play around Tmux.

The goal is to execute commands from a pre-defined library, on any environment, directly without any loading or sourcing.

The Tmux Key Binding

Paste line below in your tmux.conf.

1
bind-key -n "M-c" run 'bash -ic "ask-and-run"'

This line simply say when you press Alt-C, execute the shell command ask-and-run.

Implemention

Now let’s implement the ask-and-run function in .bash-aliases.

1
2
3
4
5
6
7
8
9
10
11
12
13
# used in tmux, alt c, for quickly triggering pre-defined commands
function ask-and-run() {
  items=(
    "ifdown eth0; ifup eth0"
    "vim /etc/network/interfaces"
  )
  cmd=$(zenity --list --column=Commands --height=500 --width=400 "${items[@]}")
  if [[ "$cmd" != "" ]]; then
    chars=$(echo `echo "$cmd" | wc -c` "/2 -1" | bc)
    final=$(echo $cmd | head -c$chars)
    tmux send-keys "$final" Enter
  fi
}

The 2 lines after zenity --list is for converting output from ls|ls to ls. This is needed in zenity 3.8.0. Simply skip that if your zenity is 3.4.0.

That’s all for the setup! Put your favourite commands inside the array items, reload tmux and enjoy Alt-C.

Comments