Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between parentheses and brackets in Bash conditionals

While learning a bit about bash, I come to see four types of ways of working with if statements:

  • Single Parenthesis - ( ... )
  • Double Parenthesis - (( ... ))
  • Single Square Bracket - [ ... ]
  • Double Square Brackets - [[ ... ]]

What is the difference between Parenthesis and Square Brackets in bash.

like image 370
Luis Alvarado Avatar asked Oct 07 '12 01:10

Luis Alvarado


People also ask

What do parentheses () and brackets [] In differ?

3. Brackets are used to enclose parenthetical materials within the parentheses while parentheses are used to enclose words, numbers, phrases, sentences, symbols, and other items in a sentence.

What does parentheses mean in bash?

( Single Parentheses ) This means that they run through all of the commands inside, and then return a single exit code. Any variables declared or environment changes will get cleaned up and disappeared.

What is the difference between using and == In a bash double square bracket if conditional?

Double Brackets i.e. [[]] is an enhanced (or extension) version of standard POSIX version, this is supported by bash and other shells(zsh,ksh). In bash, for numeric comparison we use eq , ne , lt and gt , with double brackets for comparison we can use == , !=

What does (( mean in bash?

so you can use this if you want to print the name of shell script. $- $- (dollar hyphen) bash parameter is used to get current option flags specified during the invocation, by the set built-in command or set by the bash shell itself. Though this bash parameter is rarely used. $?


1 Answers

The tests you had listed :

  • Single Parenthesis - ( ... ) is creating a subshell
  • Double Parenthesis - (( ... )) is for arithmetic operation
  • Single Square Bracket - [ ... ] is the syntax for the POSIX test
  • Double Square Brackets - [[ ... ]] is the syntax for bash conditional expressions (similar to test but more powerful)

are not exhaustive, you can use boolean logic

if command; then ... 

too, because the commands have exit status. In bash, 0 is true and > 0 is false.

You can see the exit status like this :

command echo $? 

See :

http://wiki.bash-hackers.org/syntax/basicgrammar
http://wiki.bash-hackers.org/syntax/arith_expr
http://mywiki.wooledge.org/BashGuide/TestsAndConditionals

like image 178
Gilles Quenot Avatar answered Sep 21 '22 21:09

Gilles Quenot