Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash/sh if statement syntax

Tags:

linux

bash

In various guides and scripts I come across people tend to use different syntax of if statements. What's the difference and what are best practices? I believe all the following statements, and many more variants, will return true:

bar="foo"
if [ "foo" = "foo" ]
if [[ "foo" == $bar ]]
if [ "foo" = "$bar" ]
if [[ "foo" = "$bar" ]]
if [[ "foo" -eq $bar ]]
like image 904
Jacob Rask Avatar asked Aug 07 '10 13:08

Jacob Rask


People also ask

How do I do an if statement in bash?

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 TEST-COMMAND returns False , nothing happens; the STATEMENTS get ignored.

What Is syntax for if-else in shell script?

Syntax: if [ expression ] then statement fi. if-else statement. If specified condition is not true in if part then else part will be execute. Syntax if [ expression ] then statement1 else statement2 fi. if..elif..else..fi statement (Else If ladder)

What is bash if [- N?

A null string in Bash can be declared by equalizing a variable to “”. Then we have an “if” statement followed by the “-n” flag, which returns true if a string is not null. We have used this flag to test our string “name,” which is null.


1 Answers

As I understand it

= expects strings

-eq expects integers

"$bar" is for literal matches, i.e. z* may expand but "z*" will literally match the wildcard char.

The difference between [] and [[]] is that in the latter word splitting and path name expansion are not done, but are in the former.

Plus [[]] allows the additional operators :

&& (AND), || (OR), > (String1 lexically greater than String2), < (String1 lexically less than String2)

The == comparison operator behaves differently within a double-brackets test than within single brackets.

[[ $a == z* ]] # True if $a starts with an "z" (pattern matching).

[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).

[ $a == z* ] # File globbing and word splitting take place.

[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).

Check out http://tldp.org/LDP/abs/html/comparison-ops.html for more info

like image 138
lucas1000001 Avatar answered Oct 05 '22 14:10

lucas1000001