15

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)

3
  • Note that if [[ -z $test ]] will almost certainly expand to if [[ -z ]] when $test becomes empty, which seems likely to break the conditional. To protect against this, simply put the variable in quotes: if [[ -z "$test" ]] ; then.
    – user
    Aug 16 '16 at 15:30
  • I actually think that newer versions of bash handle that. Seems to work in my tests anyway.
    – DarkNeuron
    Aug 16 '16 at 17:22
  • Well then, good for you. :-) I tend to like the additional safety net, if nothing else to preserve my sanity when looking at the code later...
    – user
    Aug 16 '16 at 17:24
21

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
2
  • Ah, of course. It's an error! :)
    – DarkNeuron
    Aug 16 '16 at 14:12
  • Also, it's asking for trouble (if only a little bit) to use the name of a built-in command (and executable) - "test" for a variable name, so just testing the exit status as in the second solution is better for that reason too.
    – Joe
    Aug 19 '16 at 6:49

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.