LENS LENS - 2 months ago 13
Bash Question

functions /bin/false in shell script makes negative effect

I was confused:

#!/bin/sh
[ -f /etc/init.d/functions ] && . /etc/init.d/functions

[ 0 -eq 0 ] && action "Test" /bin/false || action "Test" /bin/true

echo "###############"

[ 0 -eq 0 ] && action "Test" /bin/true || action "Test" /bin/false


the result is:

Test [FAILED]
Test [ OK ]
###############
Test [ OK ]


does the action /bin/false function return false value that makes the statement behind || to be executed?
if I have to put /bin/false in "&&" block, what to do

Answer

The thing is that:

action "Test" /bin/false

returns 1 that causes command after || to execute as the failure action. Effectively this behaves like this:

[ 0 -eq 0 ] && { action "Test" /bin/false || action "Test" /bin/true; }

This is more of a reason to use if/else/fi and get the right behavior:

echo "###############"
if [ 0 -eq 0 ]; then
   action "Test" /bin/false
else
   action "Test" /bin/true
fi

This will output:

Test                                                       [FAILED]