1

Background: I use Tilix as my main terminal emulator. In the Tilix preferences (attached screenshot), I have set it up so that when Tilix is launched, it will run this command:

/usr/bin/zsh -c "if [[ $(tmux ls 2>/dev/null | grep -q -E '^main.*attached.*'; echo $?) -ne 0 ]]; then tmux attach -t main || tmux new -s main; else /usr/bin/zsh; fi"

Tilix Preferences

This checks:

  • if a tmux session named main is running and a window is attached to it
    • If it fails, it will then try to attach to the tmux session named main
      • If that fails, then it will go ahead and create a new tmux session named main and attach to it
    • Else (If successful), just launch plain zsh

The reason for all this complexity so that when I launch tilix for the first time, it will launch it with tmux running and connected to it. Any new tilix session or new tilix window lauched will not create or try to connect to the existing tmux session named main. (Tilix has its own multi window and pane which is not to be confused with tmux sessions)

What I would like to know if it is possible to condense the codeblock above, or if it is possible to come up with a better version of the codeblock above.

2 Answers 2

1

The command substitution is a bit over the top, but otherwise it looks fine. Just use the exit code directly in the if

If the pattern ^main.*attached.* is found then the pattern ^main.*attached will also be found, and likewise if the longer pattern is not found then neither will the shorter. The matching for the shorter pattern will probably be quicker.

/usr/bin/zsh -c "if ! tmux ls 2>/dev/null | grep -q -E '^main.*attached'; then tmux attach -t main || tmux new -s main; else /usr/bin/zsh; fi"
0
0

If your tmux is new enough you could do something like:

[ "$(tmux display -pt=main: '#{session_attached}' 2>/dev/null)" -gt 0 ] && exec tmux new -Asmain || exec zsh
4
  • I must need /usr/bin/zsh in the beginning otherwise tilix does not accept the command
    – GMaster
    Commented May 8, 2020 at 6:08
  • Well yes, I assumed you would realise that. Commented May 8, 2020 at 7:34
  • Your solution looks promising. The thing is when there is no tmux sessions called main running this outputs null: tmux display -pt=main: '#{session_attached}' 2>/dev/null and the -gt condition fails
    – GMaster
    Commented May 8, 2020 at 8:45
  • Well you could probably check for that too, but why don't you put this in a script like ~/.run-tmux.sh and ask Tilix to run that, then you could make it as long as you like and don't have to worry about it being compact? Commented May 8, 2020 at 10:19

You must log in to answer this question.

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