BugHunterUK
BugHunterUK

Reputation: 8958

How does -d work in if statements when checking for return codes?

I can across some code in a bash script that has confused me a little.

The code checks to see if the directory/file exists. If the return code is 0 ... success, otherwise the file doesn't exist:

if [ -d /usr/local/bin ]
then
    echo "Exists"
else
    echo "Does not exist"
fi

What program is -d /usr/local/bin using to check if the file exists? The other example in the book is:

test -d /usr/local/bin

if [ "$?" -eq 0 ]
then
    echo "Exists"
else
    echo "Does not exist"
fi

Which leads me to believe the first example us using test within the if. And if so, why does this happen automatically without having to specify the test program?

Upvotes: 0

Views: 444

Answers (1)

William Pursell
William Pursell

Reputation: 212354

The square brackets are not part of the shell grammar. Rather [ is a command with the very odd feature of requiring its last argument to be the literal string ]. The command you are executing is [ with the 4 arguments N, -eq, 0, and ] where N is the value that the shell variable ? currently expands to (likely either 0 or 1). In the past, /bin/[ was often literally a link to the same file as /bin/test, and that executable behaved slightly differently when it was invoked through that link (it checked that the last argument was ]). Other than the check on the last argument, [ is exactly the same as the command test.

It might be clearer if the second example did not explicitly check $? but had instead simply been written:

if test -d /usr/local/bin
then
    echo "Exists"
else
    echo "Does not exist"
fi

Upvotes: 2

Related Questions