Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script if statements

Tags:

bash

unix

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
like image 308
Jonhnny Weslley Avatar asked Apr 14 '10 21:04

Jonhnny Weslley


People also ask

Can you use if statements in bash script?

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.

What is if condition in bash?

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.

What statement ends an if statement in a bash script?

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.

How do you write an if else condition in shell script?

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.


1 Answers

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.

like image 123
mgv Avatar answered Sep 28 '22 16:09

mgv