Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between [] and () in an "if" condition [duplicate]

Tags:

bash

shell

Could someone explain me or point me out some document where the differences between "if () ..." and "if [] ..." can be clarified please?

like image 594
VeryNiceArgumentException Avatar asked Jun 05 '13 18:06

VeryNiceArgumentException


2 Answers

if simply takes an ordinary shell command as an argument, and evaluates the exit code of the command. For example, you can do

if grep pattern file; then ...; fi

() in bash executes the contents in a subshell, so you can specify basically any command in the subshell.

[] in bash is a shell command (technically the [ command), which evaluates an expression according to a specific syntax.

So, if (...) is used to test the exit code of a command (in most cases the () are redundant), while if [...] is used to test an expression using the syntax of test.

like image 179
nneonneo Avatar answered Oct 24 '22 08:10

nneonneo


The [ symbol is actually a command. It is equivalent to the test command.

For instance

if test "$foo" = 'bar'; then ...

is the same as

if [ "$foo" = 'bar' ]; then ...

Whereas, if (command) executes command in a subshell.

like image 32
Colonel Panic Avatar answered Oct 24 '22 07:10

Colonel Panic