Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this test condition fails to produce the expected outcome in bash?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading