I'm currently using gnome-terminal and tmux together: every time I start gnome-terminal, a tmux is started:


if type tmux > /dev/null; then
  args+=('-e' "tmux new-session")

exec gnome-terminal "${args[@]}" "$@"

But how can I start tmux with the working dir of the most recently active tmux session if there is one existing active tmux session?


What might help is the list-panes command which you can use with -a for all. By default it does not provide what you want, but you can give it a format and in that include, for example, the pane_current_path, and perhaps enough other values for you to decide which of the panes you want to copy. Eg

$ tmux list-panes -a -F 'uniq=#D pane=#P title="#T" sess=#S windex=#I winnam=#W activ=#{pane_active} pwd=#{pane_current_path}'
uniq=%0 pane=0 title="myhost 2" sess=0 windex=0 winnam=bash activ=0 pwd=/home/meuh
uniq=%1 pane=1 title="myhost 3" sess=0 windex=0 winnam=bash activ=1 pwd=/home/meuh
uniq=%2 pane=0 title="myhost 4" sess=1 windex=0 winnam=bash activ=0 pwd=/tmp
uniq=%4 pane=1 title="myhost 5" sess=1 windex=0 winnam=bash activ=1 pwd=/usr/lib
uniq=%3 pane=0 title="myhost 1" sess=2 windex=0 winnam=bash activ=1 pwd=/tmp

The meaning of each variable eg #D for unique pane id is described in the man page under FORMATS. You might choose the largest of these ids as the most recent pane, and the pwd= value as the desired directory. Eg pipe the above tmux command into

 | awk '{id=substr($1,7)+0;if(id>max){max=id;pwd=$NF}} END{print substr(pwd,5)}'

Using the window_activity variable in later tmuxes, which gives the time in seconds since the epoch of last activity in the window, you can simplify the above to listing just this value and the current path, and taking the path for the maximum activity value:

tmux list-panes -a -F '#{window_activity} #{pane_current_path}' |
awk '{time=$1+0;if(time>max){max=time;pwd=substr($0,length($1)+2)}} END{print pwd}'
| improve this answer | |
  • Thank you! I suggest to use session with the largest window_activity as the last used session. Do you agree? Can we put it into the answer? – xuhdev Oct 8 '16 at 17:38
  • My tmux doesn't have a window_activity variable. Do you mean window_activity_flag or window_active? Both of these are only 0 or 1, so there may be many panes that have the same value. – meuh Oct 8 '16 at 17:59
  • It is available on 2.3 at least: "window_activity Integer time of window last activity" – xuhdev Oct 8 '16 at 21:46
  • That's a great solution. I don't have the newer tmux but I looked through its man page and updated my answer. Thanks. – meuh Oct 9 '16 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.