Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are square brackets required in a Bash if statement?

Usually, I use square brackets in the if statement:

if [ "$name" = 'Bob' ]; then ... 

But, when I check if grep succeeded I don't use the square brackets:

if grep -q "$text" $file ; then ... 

When are the square brackets necessary in the if statement?

like image 913
Misha Moroshko Avatar asked Jan 19 '12 22:01

Misha Moroshko


1 Answers

The square brackets are a synonym for the test command. An if statement checks the exit status of a command in order to decide which branch to take. grep -q "$text" is a command, but "$name" = 'Bob' is not--it's just an expression. test is a command, which takes an expression and evaluates it:

if test "$name" = 'Bob'; then ... 

Since square brackets are a synonym for the test command, you can then rewrite it as your original statement:

if [ "$name" = 'Bob' ]; then ... 
like image 191
chepner Avatar answered Sep 28 '22 00:09

chepner