sleepsort
sleepsort

Reputation: 1331

shell: why [ -d ] returns true instead of false?

As is told here, the command [ -d FILE ] is used to check whether a file is directory.

However, when we miss the FILE parameter in the expression, it still returns true.

Why? How does shell interpret this expression then?

Example should be straightforward enough :)

$ [ -d /tmp ]
$ echo $?          # prints 0
$ [ -d ]
$ echo $?          # why prints 0 as well?

Upvotes: 1

Views: 75

Answers (2)

hammar
hammar

Reputation: 139890

It gets interpreted as [ -n -d ]. In other words, since you've only provided one argument -d gets treated as if it were any other string, and as you can read in the man page:

-n STRING
the length of STRING is nonzero

STRING
equivalent to -n STRING

Upvotes: 3

chepner
chepner

Reputation: 531683

-d is only treated as an operator if [ receives 2 arguments. [ -d] is a one-argument form of the [ command, which exits with 0 if its single argument is non-null. Since -d is a non-null string, it exits 0.

[ -d "" ], on the other hand, is a two-argument form of the [ command, with the two arguments "-d" and "". Now the first argument is treated as a primary operator that acts on the second argument.

Upvotes: 5

Related Questions