Can't capture output into variable in Bash

Solution 1:

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