0

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?

BugHunterUK
  • 8,346
  • 16
  • 65
  • 121
  • 1
    square brackets are a synonym for `test` http://stackoverflow.com/a/8934070/12016 – mana Mar 31 '17 at 11:38

1 Answers1

2

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
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • Very interesting to know. I just did `file /bin/[` and it shows as an executable. `man [` is the same man page for `test` which confirms your answer. Thanks for the detailed explanation. The book I'm reading is "Mastering Unix Shell Scripting". The last example your provided is also listed :) – BugHunterUK Mar 31 '17 at 11:50