开发者

Distinguish directory name or path to the directory

开发者 https://www.devze.com 2023-03-04 20:17 出处:网络
I have a shell script which takes a directory-name or path to the directory command-line, and cre开发者_如何学Pythonate that directory. If I want to identify the argument is a valid path or only a dir

I have a shell script which takes a directory-name or path to the directory command-line, and cre开发者_如何学Pythonate that directory. If I want to identify the argument is a valid path or only a directory-name, how can I achieve this? As if a directory-name is passed then that directory will be created in the location from where the script is being executed, and if it is a path then the directory will be created on that path. So this distinction is necessary for my script.

Thanks and regards.


Some programs treat arguments with a trailing '/' differently. Consider:

./foo x

./foo x/

However, I would encourage the use of a "tag"/"option" if applicable as the above is a very subtle detail to overlook. (Think of the users!).

./foo -p x

./foo --path=x

./foo x

Happy coding.


I'm not sure what you mean, nor convinced you need to make this distinction: mkdir -- "$1" creates a directory no matter how you present the name to it.

To test whether the first argument is a simple directory name with no path component (e.g. foo but not foo/bar or /abso/lute), test whether it contains a /:

case "$1" in
  */*) echo "contains multiple path components";;
  *) echo "no slash, just a base name";;
esac

To test whether the first argument is a relative path or an absolute path, test whether it starts with /:

case "$1" in
  /*) echo "absolute";;
  *) echo "relative";;
esac

By the way that this applies whether you're considering a file or a directory.


dir=$(dirname -- "$1")

if test "$dir" != '.'; then
    echo 'Path'
else
    echo 'Directory'
fi
0

精彩评论

暂无评论...
验证码 换一张
取 消