Currently I have my terminal (alacritty) run tmux new -A -s 0 at start to start a new session 0, or attach to it if it already exists. One problem is, I sometimes use open in directory from file manager (Dolphin). In that case, I am just reconnected to the older session and not in the desired directory.

What I want to achieve is to open a new window in the session 0 with my desired path as working directory if no such window exists in the given session. Otherwise, I want to switch to that existing window.

If that is not possible, I'm happy with just creating a new window every time. Maybe it can be detected if a process is running in the current active window, and if not, using cd to switch the directory?

If anyone has any ideas on how to achieve this, it will be greatly appreciated.


1 Answer 1


As @KamilMaciorowski pointed out, a very similar problem was solved by them here. I modified the script a little bit to suit my needs i.e. I want to ignore "busy" panes i.e. that have some program running on them, for which I check if the #{pane_current_command} is a known shell. Also, I don't pass an argument and just try to open the current directory as that is what I have to work with when running from alacritty.

Otherwise, it's just a rewrite of their script. The following is what I ended up using:

#!/usr/bin/env bash

target_path="$(pwd -P)"

tmux list-panes -s -F '#{window_id} #{pane_id} #{pane_current_path} #{pane_current_command}' \
| while IFS=' ' read -r window pane path cmd; do
    [[ "$path" = "$target_path" && " fish bash zsh " =~ " $cmd " ]] \
        && tmux select-pane -t "$pane" && tmux select-window -t "$window" && exit 0
done || tmux new-window -c "$target_path"

tmux attach -d

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .