tags:

views:

68

answers:

3

I'm not able to check the return values of the function test; man test didn't help me much.

#!/bin/bash
test=$(test -d $1)
if [ $test -eq 1 ]
then
    echo "the file exists and is a directory"
elif [ $test -eq 0 ]
    echo "file does not exist or is not a directory"
else 
    echo "error"
fi
+3  A: 

$(test -d $1) is going to be substituted with what test outputs, not its return code. If you want to check its return code, use $?, e.g.

test -d $1
test=$?
if [ $test -eq 1 ]
...
Eric Warmenhoven
William Pursell
Well yes, for test you wouldn't check $? since the point of it is just to return 0/1. But the general case is to use $? for programs that have many return values.
Eric Warmenhoven
+5  A: 

Try, instead

if test -d $1
then
    echo 'the file exists and is a directory'
else
    echo 'the file doesn't exist or is not a directory'
fi
Steve Emmerson
works for me... thank you Steve :)
Samantha
+4  A: 

Every time you use test on the return code of test, God kills a kitten.

if test -d "$1"

or

if [ -d "$1" ]
Ignacio Vazquez-Abrams
sorry Ignacio... poor kittens :p
Samantha
@nour: In other words: `[` **is** `test` (both are Bash builtins as well as external programs (`/usr/bin/[` and `/usr/bin/test`).
Dennis Williamson
This uses the bash built-in and is therefor probably negligibly faster. Though it goes about the testing in much the same way as @Steve Emmerson's solution. I prefer this method.
Jim