user1321964
user1321964

Reputation: 35

How to tell if a filename is a directory, not a file

I need to check if a parameter passed to a bash script is a folder or a file. It may or may not end with /

xpath=$(dirname "$1")

strips out the dirname if there was no trailing /

Thanks

Upvotes: 0

Views: 142

Answers (2)

Piotr Wadas
Piotr Wadas

Reputation: 1894

use "test -f" or "test -d" with the path. Though "dirname" always returns name of directory, never a filename, however it may return a directory in which file resides, or a directory in which directory resides, depending if argument is file or directory. "basename" returns filename or directory without preceeding path it resides in.

Upvotes: 1

fedorqui
fedorqui

Reputation: 290305

Given the file a and dir t.

You can use the command file:

$ file t
t: directory
$ file a
a: ASCII text

Or also the -f (file) and -d (dir) flags.

$ [ -f a ] && echo "this is a file"
this is a file
$ [ -f t ] && echo "this is a file"
$
$ [ -d t ] && echo "this is a dir"
this is a dir
$ [ -d a ] && echo "this is a dir"
$

Upvotes: 1

Related Questions