Home > Back-end >  Why is this test condition fails to produce the expected outcome in bash?
Why is this test condition fails to produce the expected outcome in bash?

Time:04-12

if [[ ! `cat /etc/passwd > /dev/null 2>&1` ]]; then
    echo "not working"
fi

I get 'not working' in the output.

But running the cat command followed with echo $? returns 0, so I was expecting not to see the output.

CodePudding user response:

To test the exit status, don't use [[ and `:

if ! cat /etc/passwd > /dev/null 2>&1 ; then
    echo "not working"
fi

Backquotes, also called Command Substitution, expand to the output of the command, which is always empty here, because stdout is redirected to /dev/null. [[ ! $string ]] is equivalent to [[ ! -n $string ]] or [[ -z $string ]], i.e. it tests whether $string is empty, which it always is (explained above).

  • Related