7

I use tmux on most boxes, but not all.

I have the following line in my .bashrc file:

[ -z "$TMUX" ] && export TERM=xterm-256color && exec tmux

which invoke tmux if it exists.

I thought the [ -z $TMUX ] meant that it would only be used if tmux exists.

However on another system, without tmux, I get

-bash: exec: tmux: not found

and the login attempt fails

On my main system I see

$ echo $TMUX
/private/var/folders/ks/266xy5lj7x35gfj4csc66444b48rvq/T/tmux-373580663/default,55084,4

I also tried just [ $TMUX ] (i.e. no -z) but that didn't help

I'm also looking for a robust solution that works in Ubuntu as well as OSX

7

Did you do echo $TMUX, while in a tmux session? Because TMUX is only set, when in a session.

Try that instead:

[ -z "$TMUX" ] && command -v tmux >/dev/null && TERM=xterm-256color exec tmux
  • 2
    A cleaner solution is which tmux &>/dev/null && .... Capturing the output and testing if empty is just dirty :-) – Patrick Jul 23 '14 at 14:40
  • @Patrick Thanks, I adapted it to your comment ;) – polym Jul 23 '14 at 14:44
  • 5
    @polym which(1) is an external program used to search PATH for an executable. It behaves differently on different systems and you can't rely on a useful exit code; use (from most to least portable) ''command -v'' or ''type -P'' (to find the path) or ''hash'' (to check) instead. See mywiki.wooledge.org/BashFAQ/081 – Valentin Bajrami Jul 23 '14 at 14:45
  • 1
    Another nitpick: TERM=xterm-256color exec tmux :-) – Patrick Jul 23 '14 at 14:46
  • 1
    @VolkerSiegel Depends on how this is being implemented. If this is simply being placed at the top of the .bashrc, then you are correct, it's a problem. A complete solution would involve a combination of checking to see if $TMUX is empty, and if the executable is present. – Patrick Jul 23 '14 at 14:48
5

Ok, so if you want to start tmux only when it exists in $PATH and when it isn't already running then you can do:

command -v tmux >/dev/null && ${TMUX+:} TERM=xterm-256color exec tmux

Shorter still:

tmux -c "${TMUX+!} :" 2>/dev/null && exec tmux -2

The second one asks tmux to return 0 if ${TMUX} is not set && if true, the shell execs tmux -2 to force 256-color. It will only ever return true if tmux can be run in $PATH and if the environment variablete $TMUX does not exist.

  • 1
    The "variable is not defined or we comment out the whole command with :" is interesting! – Volker Siegel Jul 23 '14 at 14:51
  • Thanks for pointing it out! Changed it the comment above. – Volker Siegel Jul 23 '14 at 14:56
-1

Use

which tmux && export TERM=xterm-256color && exec tmux

If there is tmux, which tmux will evaluate to path to tmux binary, therefore to true. If there is no tmux, it will evaluate to empty string, so to false.

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.