M
M
MuuNu2021-12-16 12:10:35
linux
MuuNu, 2021-12-16 12:10:35

How do logical operators work in BASH?

Imagine a simple sequence of commands

cd ~/dir1 && cd ~/dir2 && echo "Success" || echo "Failed"

If dir1 and dir2 exist in the user's home directory, then each command (cd) will return True, and echo "Success" will be executed as a result . Failed 1 && 0 || echo "Failed" However, the question arises - how exactly does BASH convert the result of executing a certain command into a boolean value? Where does he write this value, and where does he store it? How can this value be deduced? It doesn't look like an error code. Since the successful execution of the command returns 0. Which is completely contrary to the algebra of logic. Due to what and how is the mechanism of interaction of commands with logical operators implemented in BASH?
1 && 1 && echo "Success"


Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FanatPHP, 2021-12-16
@MuuNu

As always, the title is "How do logical operators work?", but in fact the question is "why is error code 0 interpreted as true". "Where is the logic, where is the reason?" :)
While the voiced question is actually interesting.
This is how logical operators work, not only in bash. In PHP, you can write exactly the same

true /*false*/ and print "Success" or print "Failed";
and get the same result.
The bottom line here is that logical operators are made "lazy". They do not evaluate an operand that does not affect the final result.
Respectively:
  • if the operation returned true, then we must execute the operand that comes after and, because otherwise we will not be able to get the total result of the and operation. which will only be true if both operands returned true
  • if the operation returned true, then it makes no sense to execute the operand that comes after or, since its result will not affect anything - the final result will be true anyway, since for or it is important that only one result is true. get "Success"
  • if the operation returned false, then we do not need to execute the operand that comes after and, because in any case the result will be false
  • if the operation returned false, then we must execute the operand that comes after or, since it will be decisive for the entire expression. get "Failed"

K
ky0, 2021-12-16
@ky0

Since the successful execution of the command returns 0. Which is completely contrary to the algebra of logic.

Because for some reason you identify the status code with a boolean variable, and this is wrong - it can take on different values.
All this is easy to google , in short.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question