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

I saw the following bash statement used on the web:

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 goal true at the end of the condition. Any idea?

+5
source share
4 answers

try running: (Pay attention to bla )

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

You will get RC=0 . This means that it is a construction for a successful transition to the next team. Here we know that python_bla or python3_bla_bla does not exist, but still the command gave RC=0 Example: check the RC of the next three commands, I changed the spelling of the date command to the wrong one, but true causes 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 the operator : instead of true to get the same results. Example:

 command || : 
+2
source

To be more strict, I think.

eg:

if aaa not an existing global binary. After doing which aaa you can execute echo $? , and the result is 1 .

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

+1
source

Simple It will check that your system has out of the box python (the python version that comes with your OS), or it has a version of python version 3. It will also confirm the python executable path, you can simply print a variable named PYTHON_BIN_PATH by doing echo "$PYTHON_BIN_PATH" and you can check it once.

EDIT: Here is a simple example to understand. Let them say that we have a variable named val with a value of NULL, and we do this:

 echo $val || true 

The output will be NULL, while the previous command did not return any result. Let, say, we have val=4 , then we execute it as follows.

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

The idea is to set PYTHON_BIN_PATH to nothing if both of which fail.

Apparently there is no difference between

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

and

 PYTHON_BIN_PATH=$(which python || which python3) 

But executing one command makes things more obvious. Assume python does not 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 gives a zero exit status for

  $( command || true ) 
-1
source

Source: https://habr.com/ru/post/1273232/


All Articles