6

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

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • 4
    () is for specifying function and [ ] for test condition/evaluation .. – Nitin4873 Jun 05 '13 at 18:08
  • 3
    Here is another question where this has already been answered: http://stackoverflow.com/questions/12765340/difference-in-bash-between-if-statements-with-parenthesis-and-square-brackets – betseyb Jun 05 '13 at 18:11
  • http://stackoverflow.com/questions/2188199/bash-double-or-single-bracket-parentheses-curly-braces – Cloud Jun 05 '13 at 18:11
  • 2
    @NSD, `()` in this context would be for running a command pipeline in a subshell and `if` would act on the exit status. – glenn jackman Jun 05 '13 at 19:46

2 Answers2

16

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.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
6

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.

Colonel Panic
  • 1,604
  • 2
  • 20
  • 31