Reputation: 35
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
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
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