LENS
LENS

Reputation: 95

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

Upvotes: 0

Views: 241

Answers (2)

user1585121
user1585121

Reputation:

Since /bin/false return false, it pass the || and return /bin/true

See it like this:

true && false || true -> true
true && true || false -> true

If you use

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

if will return false, as you expected?

See this

#!/bin/bash
[ 1 = 1 ] && echo "displayed because previous statement is true"

[ 1 = 0 ] && echo "not shown because previous statement is false"

[ 1 = 1 ] || echo "not shown because previous statement is true"

[ 1 = 0 ] || echo "displayed because previous statement is false"

Upvotes: 1

anubhava
anubhava

Reputation: 784938

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]

Upvotes: 1

Related Questions