views:

22

answers:

2

Hi, I'm trying to test whether a directory path exists when a file is passed to my script. I use dirname to strip and save the path. I want my script to run only if the path exists. This is my attempt below.

FILE=$1 DIRNAME=dirname $FILE

if [ -z $DIRNAME ] ; then echo "Error no file path" exit 1 fi

But this doesn't work. Actual when there is no file path dirname $FILE still returns "." to DIRNAME, i.e. this directory. So how do i distinguish between "." and "/bla/bla/bla".

Thanks.

A: 

why not use

 
if [ -a $1] ; then echo "found file"; fi

?

atk
This is true whether a file path exists or not. How can I test if DIRNAME is populated or holds "."
Paul
It was as simple as if [ $DIRNAME == "." ] ; thenI don't know why this did not work earlier. Must've made a mistake else-where.Thanks very much for you quick response.
Paul
Paul, I'm glad you figured it out - and sorry that my response wasn't what you were looking for. Typos preventing the code you posted from working can be easy to make and tough to spot :)
atk
A: 

Are you sure dirname is checking the filesystem for existence? What OS are you on? Most dirnames just do string manipulation, I believe. So this:

dirname /one/two/three

Returns /one/two even if /one doesn't exist.

Maybe this is what you're looking for:

FILE=$1
DIRNAME=`dirname "$FILE"`
if [ ! -d "$DIRNAME" ]; then
    echo "$DIRNAME doesn't exist" >&2
    exit 1
fi
Rob Davis
Ok, thanks for this. I check this later. I'm got into something that need finished soon.
Paul