[bash] cmd priority with logical operator and parenthesis

숭글·2022년 10월 20일
1
post-thumbnail

Logical operator

There are two logical operators, && and ||. These are used to combine the results of previous two commands.
If there is command left to execute then The result affects whether to execute them or not.

AND, OR truth table

  • AND truth table
---------------------------------------
condition 1  |  condition2  |  output
---------------------------------------
      0      |      0       |    0
---------------------------------------
      0      |      1       |    0
---------------------------------------
      1      |      0       |    0
---------------------------------------
      1      |      1       |    1
  • OR truth table
---------------------------------------
condition 1  |  condition2  |  output
---------------------------------------
      0      |      0       |    0
---------------------------------------
      0      |      1       |    1
---------------------------------------
      1      |      0       |    1
---------------------------------------
      1      |      1       |    1

Let's try to consider that we try to make a result 1 all the time, but we are very very lazy so not gonna work if the result is decided even if it's a middle of the whole command.
If the result of first command's execution is true(1) and it connected with a AND then we must check next command's result by executing that.
on the contrary, If the result is false(0) then we don't need to check and execute next one. Since It already be false anyway.

&&, ||

&& (AND_IF)

: execute the next command only if the previous one exited successfully(it means exit code is 0).

|| (OR_IF)

: execute the next command only if the previous one exited unsuccessfully(exit code > 0).

cmd priority with parenthesis

existance and location of parenthesis can change the command priority.
see how it works with below example.

Example with Tree

command 1 : a || (b && c) && d

command 2 : a || (b && (c && d))

command1 and command 2 have same 4 commands and 1 or_if, 2 and_if and 2 pair of parenthesis but these located differently.
It seems like a little different but these two make a totally different tree. (🌳 make tree )

See the left tree, If a is true then b and c which is located in OR's right won't be executed but d will be.
But In right tree case, b, c and d won't be executed.

It means parenthesis affects the priority of commands.

profile
Hi!😁 I'm Soongle. Welcome to my Velog!!!

0개의 댓글