Shell scripting and test expressions
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.
why not use
if [ -a $1] ; then echo "found file"; fi
?
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
精彩评论