Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean operators ( &&, -a, ||, -o ) in Bash

What is the difference between the &&, ||, -a, and -o Unix operators?

What are the restrictions on the usage of both types?

Is it simply that the && and || operators should be used when using flags in the condition?

As in:

[ "$1" = "yes" ] && [ -r $2.txt ] 

versus:

[ "$1" = "yes" -a $2 -lt 3 ] 
like image 345
Victor Brunell Avatar asked Dec 08 '13 03:12

Victor Brunell


People also ask

What is an example of a Boolean operator?

The most common Boolean operators are AND, OR, NOT or AND NOT, quotation marks “”, parentheses (), and asterisks *.

What are the different types of Boolean operations?

The three basic boolean operators are: AND, OR, and NOT.

What are the most common Boolean operators?

The most popular Boolean commands are AND, OR, and NOT.


2 Answers

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

like image 116
John Kugelman Avatar answered Sep 22 '22 01:09

John Kugelman


-a and -o are the older and/or operators for the test command. && and || are and/or operators for the shell. So (assuming an old shell) in your first case,

[ "$1" = 'yes' ] && [ -r $2.txt ] 

The shell is evaluating the and condition.

In your second case,

[ "$1" = 'yes' -a $2 -lt 3 ] 

The test command (or builtin test) is evaluating the and condition.

Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference.

In modern shells, the if statement can be written:

[[ $1 == yes && -r $2.txt ]] 

Which is more similar to modern programming languages and thus is more readable.

like image 35
Brad Lanam Avatar answered Sep 21 '22 01:09

Brad Lanam