What is the idea in this bash statement ( command || true )?

Viewed 988

I saw the following bash statement being used on the internet:

PYTHON_BIN_PATH=$(which python || which python3 || true)

I understand that if which python fails, then which python3 will be executed, but I don't understand the purpose of the true at the end of the condition. Any idea?

4 Answers

try running:(Note the bla)

which python_bla || which python3_bla_bla || true
echo $?
0

You will get RC=0. It means it a construct to successfully proceed to next command. Here we know python_bla or python3_bla_bla does not exist,but still command gave rc=0 Example: Check the RC of following three commands, I have changed the spelling of date command to incorrect but true is causing RC to remain 0.

date;echo $?
Thu Nov  9 01:40:44 CST 2017
0
datea;echo $?
If 'datea' is not a typo you can use command-not-found to lookup the package that contains it, like this:
    cnf datea
127
datea||true;echo $?
If 'datea' is not a typo you can use command-not-found to lookup the package that contains it, like this:
    cnf datea
0

Note: You can also use : operator instead of true to get the same results.Example:

command || :

To be more rigorous I guess.

for example:

if aaa isn't an existed global binary file. After executing which aaa,you can execute echo $? and the result is 1.

But if you execute which aaa | true the result will be 0.

Simple. It will check either your system has out of the box python(version of python which has come with your O.S) or it has python version 3 in it. It will also confirm python's executable path too, you could simply print variable named PYTHON_BIN_PATH by doing echo "$PYTHON_BIN_PATH" and could check it too once.

EDIT: Here is a simple example to understand. Let's say we have a variable named val with NULL value and we do this:

echo $val || true

Output will be NULL then as it's previous command didn't give any output. Let's say we have val=4 then we run it as follows.

val="4"
echo $val || true
4

The idea is to set the PYTHON_BIN_PATH to nothing if both which fails.

Visibly there is no difference between

PYTHON_BIN_PATH=$(which python || which python3 || true)

and

PYTHON_BIN_PATH=$(which python || which python3)

But running the command alone makes things more obvious. Suppose that python doesn't exist on the system.

$(which python || which python3)
echo $? #Returning the exit status of the previous command
1 # A non zero status generally means the previous statement failed
$(which python || which python3 || true)
echo $?
0

In short, using true at the end always give a zero exit status for

 $( command || true )
Related