Could someone explain me or point me out some document where the differences between "if () ..." and "if [] ..." can be clarified please?
Asked
Active
Viewed 7,591 times
6
-
4() is for specifying function and [ ] for test condition/evaluation .. – Nitin4873 Jun 05 '13 at 18:08
-
3Here 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 Answers
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
-
Ok, based in your last sentence, can you explain why it is not working? I mean, after "crontab -l > /dev/null 2>&1" $? is 1. if (crontab -l > /dev/null 2>&1); then echo "There is something scheduled" else echo "There is nothing scheduled" fi – VeryNiceArgumentException Jun 05 '13 at 18:34
-
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