Bash && (and ||)

I was talking with someone about the && operator in bash. He said it was a way to append two statements onto one line. I tried to explain that it was much more than that and only exhibited that behavior ~sometimes~.

I think I found a decent resource to highlight the difference.

Both && and II are logical operators, which do mathematics on the success bits of commands or expressions. That is more powerful and also can cause unexpected behavior if a bash user thinks it’s just combining two statements onto one line.

There is optimizing logic in bash that comes into play and can be used for execution flow in bash scripts. If the first expression evaluates to 0, then the second expression will never execute because we already know that 0 && (anything) will evaluate to 0, so bash doesn’t even execute the second statement.

Likewise, using || will evaluate the first expression, but if it evaluates to 1, the second expression will never execute because an OR with 1 will come out 1 no matter what the second part is.

Anyhow, this should be a better explanation than simply, “Uh.. it’s more than just combining two statements on one line.”

About Brian

Engineer. Aviator. Educator. Scientist.
This entry was posted in Computers. Bookmark the permalink.

Leave a Reply