5

Is there any known tmux-function, like tmux has-session -t <session>, but to check if the tmux server is currently running? It would be handy when writing automation-scripts. When checking if a session exists with

$ tmux has-session -t SomeSession

the user is, unless the tmux server is already running, presented with the error

failed to connect to server

Therefore, I want to check beforehand if the server is currently running. If it is, check for sessions et cetera. Is there any way to silence this without piping to /dev/null?

10

Run

if tmux info &> /dev/null; then 
  echo running
else
  echo not running
fi
3
[[ -n $(pgrep tmux) ]] && echo true || echo false

If a process with “tmux” in it name is running, this will print true, otherwise it will print false.

This works because pgrep finds all process with "tmux" in their names and returns their PIDs. The "-n" basically tests whether the output of $(pgrep tmux) exists. If the output does exist (ex. "14204 23137"), then the test evaluates to true. If the output doesn't exist (or is undefined), the test evaluates to false.

If you prefer long-form:

if [[ -n $(pgrep tmux) ]]; then
  echo true
else
  echo false
fi

Note that what bnjmn said applies here. Namely, that this will give a false positive if a process is running other than tmux, but has "tmux" in its name.

1

You can use ps -e | grep -q program to check if program program is running in a general way.

As an example in a shell :

if $(ps -e | grep -q tmux); then echo "Tmux is running."; fi
  • Help me clarify this. You're treating the command $(ps -e | grep -q tmux) as a boolean since most shell commands return true/false, depending on the exit code? – krystah Jan 6 '14 at 15:57
  • @krystah Yes exactly. grep exit code is success only if at least one match is found, and switch -q suppress it's output. – Levans Jan 7 '14 at 6:49
  • YMMV. The problem with this is that there may be other processes that have the string program in them. For example, the process running grep -q program will actually cause a match (at least on my system) or an open text file like vim program-not-running.txt. So, this does not work for me at all because it always returns true if tmux is running or not. Buyer beware. – bnjmn May 26 '16 at 14:28

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.