puk
puk

Reputation: 16782

In bash, why does if [ 1 ] not fail?

In shell scripting (bash) why does the conditional get satisfied

if [ 1 ]
then
 echo should not enter
fi

#Output
should not enter

Upvotes: 3

Views: 129

Answers (3)

Telemachus
Telemachus

Reputation: 19705

What may not be obvious is that these two are very different:

if [ false ]

and

if false

The first, as thiton and Ignacio Vazquez-Abrams say, implicitly checks if the string false is empty. The second version tests the exit status of the command false. (The testing of an exit status isn't literally a true/false test. It checks for success or failure as represented by numeric codes. As you can imagine, the exit status of false is always failure. That's its job.)

For more on all of this, the BashGuide on Greg's Wiki is very clear.

Upvotes: 2

thiton
thiton

Reputation: 36049

The square brackets in bash are equivalent to calling test with the arguments within the brackets. man test says that

STRING equivalent to -n STRING

and

-n STRING the length of STRING is nonzero

, and 1 is not an empty string. if [ 0 ], if [ false ] and if [ no ] have the same result, but if [ "" ] has not.

Upvotes: 7

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798666

Because 1 is not an empty string; it has one character in it, which is the numeral "1".

Upvotes: 1

Related Questions