2

I'm working on a bash function to check if a tmux session is running. The function works but if no session is running it outputs "failed to connect to server". How do I output that error to null without appending 1>&2 to every function call?

tmux_checker()
{
    if [ -z $(tmux ls  | grep -o servercontrol) ]
    then
        tmux new -d -s servercontrol
    fi
}

tmux_checker #> /dev/null 2>&1 or 1>&2
2
  • “without appending 1>&2 to every function call?”, suggests to me that you want a way to append it once, to affect all functions. But this does not match the accepted answer. Did you mean “without it affecting every function” Commented Apr 20, 2017 at 8:34
  • @richard as far as I can tell, the OP calls tmux_checker multiple times in the script and didn't want to have to call it as tmux_checker 2>&/dev/null each time. Commented Apr 20, 2017 at 8:39

2 Answers 2

3

Redirect the output in the function itself:

tmux_checker()
{
    if [ -z $(tmux ls 2>/dev/null | grep -o servercontrol) ]
    then
        tmux new -d -s servercontrol
    fi
}

tmux_checker
0
2

To test for an existing tmux session (and start a new one in the background if none exists), use

if ! tmux has-session 2>/dev/null; then
    tmux new-session -d
fi

To check for a session with a specific name:

if ! tmux has-session -t name 2>/dev/null; then
    tmux new-session -d -s name
fi

As a shell function:

start_tmux () {
    set -- "${1:-servercontrol}"

    if ! tmux has-session -t "$1" 2>/dev/null; then
        tmux new-session -d -s "$1"
    fi
}

This may be used as

$ start_tmux

or

$ start_tmux mysession

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.