17

Having trouble with redis-cli. I wanna check if the connection to redis is refused (server down), through BASH.

Simple test

#!/bin/bash
test=$(redis-cli exit) #exit out of the "not connected console"
if [[ -z $test ]] ; then
    echo "I'm empty :("
fi

I would expect Could not connect to Redis at 127.0.0.1:6379: Connection refused to be stored in $test, but this text is output to the console instead.

I'm not sure whats going on. Anyone have any ideas?

(Ubuntu 14.04.1)

heemayl
  • 93,925

1 Answers1

26

That's because the error message is being sent to the STDERR stream (file descriptor 2), not STDOUT (file descriptor 1) which you are capturing with command substitution $().

Just focusing on getting the string, either on STDOUT or STDERR:

test="$(redis-cli exit 2>&1)"

in that case the [ -z "$test" ] test will result in false positives as the error message will be stored in the variable. Instead you can do:

#!/bin/bash
test="$(redis-cli exit 2>/dev/null)"
if [[ -z $test ]] ; then
    echo "I'm empty :("
fi

Also i think, this should get what you want given the exit status is trivial:

if redis-cli exit &>/dev/null; then
    echo 'Succeeded!!'
else
    echo 'Failed!!'
fi
heemayl
  • 93,925