In Bash script, what is the difference between the following snippets?
1) Using single brackets:
if [ "$1" = VALUE ] ; then
# code
fi
2) Using double brackets:
if [[ "$1" = VALUE ]] ; then
# code
fi
What is the Bash if Statement? Bash scripts help automate tasks on your machine. The if elif else statement in bash scripts allows creating conditional cases and responses to specific code results. The if conditional helps automate a decision-making process during a program.
The if statement is composed of the if keyword, the conditional phrase, and the then keyword. The fi keyword is used at the end of the statement. The COMMANDS gets executed if the CONDITION evaluates to True. Nothing happens if CONDITION returns False; the COMMANDS are ignored.
The if statement starts with the if keyword followed by the conditional expression and the then keyword. The statement ends with the fi keyword. If the TEST-COMMAND evaluates to True , the STATEMENTS gets executed.
If specified condition is not true in if part then else part will be execute. To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.
The [[ ]] construct is the more versatile Bash version of [ ]. This is the extended test command, adopted from ksh88.
Using the [[ ... ]] test construct, rather than [ ... ] can prevent many logic errors in scripts. For example, the &&, ||, <, and > operators work within a [[ ]] test, despite giving an error within a [ ] construct.
More info on the Advanced Bash Scripting Guide.
In your snippets, there's no difference as you're not using any of the additional features.
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