Sunday, November 27, 2022

If else example in bash shell script,explanation on the difference ofusage of no bracket and single bracket after if

 #!/bin/bash

salary=1000

expenses=800

#Check if salary and expenses are equal

if test  $salary == $expenses ;

then

    echo "Salary and expenses are equal"

#Check if salary and expenses are not equal

elif test  $salary != $expenses ;

then

    echo "Salary and expenses are not equal"

fi



Now if we omit the single bracket [ after if we will encounter an error,the explanation is given below

[ is actually a command, equivalent (almost, see below) to the test command. It's not part of the shell syntax. (Both [ and test, depending on the shell, are often built-in commands as well, but that doesn't affect their behavior, except perhaps for performance.)

An if statement executes a command and executes the then part if the command succeeds, or the else part (if any) if it fails. (A command succeeds if it exits with a status ($?) of 0, fails if it exits with a non-zero status.)

In

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

the command is

[ "$name" = 'Bob' ]

(You could execute that same command directly, without the if.)

In

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

the command is

grep -q "$text" $file

man [ or man test for more information.

FOOTNOTE: Well, the [ command is almost equivalent to the test command. The difference is that [ requires ] as its last argument, and test does not -- and in fact doesn't allow it (more precisely, test doesn't treat a ] argument specially; for example it could be a valid file name). (It didn't have to be implemented that way, but a [ without a matching ] would have made a lot of people very very nervous.)


Source:https://stackoverflow.com/questions/8934012/when-are-square-brackets-required-in-a-bash-if-statement

No comments:

Post a Comment