1

As a very confused newbie, what's up with the IF statement and [ ], [[ ]], ( ), (( ))

why is

if [ $jengnr -eq 1 ]; then

correct, but here it's double:

if [[ -f "$jdir$object.eng.dat" ]]; then

and then I read that a nested if inside an if should be (( )) (not my code)

#!/bin/bash
# Nested if statements
if [ $1 -gt 100 ]
then
echo Hey that\'s a large number.
if (( $1 % 2 == 0 ))
then
echo And is also an even number.
fi
fi

but I used [[ ]] in an if statement that was inside an if [[ ]] statement, and that worked to?

Can somebody please explain what, who and why there are 4 different if?

.. and when to use them correctly?

JoBe
  • 397
  • 5
  • 17

1 Answers1

3

[

This is the shell test command (sometimes also a builtin) and is a portable method to perform shell tests.

[[

This is often referred to as the "extended test", it is supported mostly only by ksh and bash and allows more features than the shell test but is not as portable

(

This is not a test command at all, single parenthesis will create a subshell. if statements simply evaluate the return code from the command following them so using if ( command ); then would work but it would simply be evaluating the return of the subshell.

((

This allows for shell arithmetic which can be used to in conjunction with if when you are testing on arithmetic related conditions.


Additionally note that there is no such rule for nested if statements, you can use any combination of these methods at any level of nesting.

jesse_b
  • 37,005
  • so with other words, if I'm working is bash, it's better to use [[ ]] instead of [ ], since this is the "old" way, and [[ ]] is more and better? – JoBe Aug 11 '20 at 19:47
  • @JoBe: not necessarily. Often in shell scripting portability is strongly desired so if [ works for you there is nothing wrong with using it. – jesse_b Aug 11 '20 at 19:49
  • 1
    I c, but if I'm writing one for only me, to be run on only one computer, with bash, wouldn't using [[ ]] everywhere eliminate any mistakes I might do when writing [ ] and trying to test something that's not supported in the [ ] test? – JoBe Aug 11 '20 at 20:01