3

I have a section in my .bashrc that fires up the tmux program (terminal multiplexor).

However if the tmux program isn't installed (say I'm setting up a new computer) then having this in my .bashrc file stops any terminal window from successfully opening at all.

Of course installing tmux fixes this, but that isn't my problem.

How can I make this conditional so that if tmux isn't installed it doesn't crap out / give an error message?

Currently I have:

if [[ ! $TERM =~ screen ]]; then
  exec tmux
fi

I want something like:

if tmux; then
  if [[ ! $TERM =~ screen ]]; then
    exec tmux
  fi
fi

but that gives me

The program 'tmux' is currently not installed.  You can install it by typing:
sudo apt-get install tmux

Though it does at least give me a terminal prompt instead of closing the window! Also if/when tmux is installed this doesn't give any error / cause any issue when opening a new terminal window.

2 Answers 2

6

You can use the command type to see if the executable is present on your box:

if [ -n "$(type -P tmux)" ]; then

    ...tmux is installed...

else

    ...tmux isn't installed...

fi

I've often used this code snippet to do it:

$ [ -n $(type -P tmux) ] && echo "installed" || echo "not installed"
installed

I can fake it out using the alternative to -n (not empty string), -z (empty string).

$ [ -z $(type -P tmux) ] && echo "installed" || echo "not installed"
not installed
7
  • I'm sure you're aware of this, just posting it for future readers: the syntax cmd1 && cmd2 || cmd3 is actually a common Bash pitfall. It's not likely to trip up the flow in this case, however.
    – Joseph R.
    Commented Aug 4, 2013 at 13:25
  • @JosephR. - yes thanks for mentioning that. Thanks for that link, never saw that it before, good stuff.
    – slm
    Commented Aug 4, 2013 at 13:27
  • Honest question: Wouldn't it be better to check for execution permission with -x?
    – rahmu
    Commented Aug 4, 2013 at 13:29
  • @rahmu - always good to ask questions. Yes it can be done that way as well. The trouble with that method is it isn't as portable since you'll have to hardcode the path the executable. [ -x /usr/bin/tmux ].
    – slm
    Commented Aug 4, 2013 at 13:40
  • [ -x $(which tmux) ]? The only problem I found with this is that which behaves differently on zsh if ran against an alias.
    – rahmu
    Commented Aug 4, 2013 at 13:54
1

Or, if all you want to do is decide on which executable to fire off, you can do this:

executable=$(type -P tmux)
executable=${executable:-xterm} # For example
exec $executable

The expansion var=${var:-string} assigns the value "string" to var if and only if nothing has been assigned to var before.

You must log in to answer this question.

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