Could someone explain me or point me out some document where the differences between "if () ..." and "if [] ..." can be clarified please?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With