bash 检查参数是否是路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23310218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if an argument is a path
提问by user1872329
I'm writing a script in bash. It will receive from 2 to 5 arguments. For example:
我正在用 bash 编写脚本。它将接收 2 到 5 个参数。例如:
./foo.sh -n -v SomeString Type Directory
./foo.sh -n -v SomeString Type Directory
-n, -v and Directory are optional. If script doesn't receive argument Directory it will search in current directory for a string. Otherwise it will follow received path and search there. If this directory doesn't exist it will send a message.
-n、-v 和 Directory 是可选的。如果脚本没有收到参数 Directory,它将在当前目录中搜索字符串。否则它将遵循接收到的路径并在那里搜索。如果此目录不存在,它将发送一条消息。
The question is: Is there a way to check if the last arg is a path or not?
问题是:有没有办法检查最后一个 arg 是否是路径?
回答by anubhava
You can get last argument using variable reference:
您可以使用变量引用获取最后一个参数:
numArgs=$#
lastArg="${!numArgs}"
# check if last argument is directory
if [[ -d "$lastArg" ]]; then
echo "it is a directory"
else
echo "it is not a directory"
fi
回答by Baba
you can use this:
你可以使用这个:
#!/bin/bash
if [[ -d ${!#} ]]
then
echo "DIR EXISTS"
else
echo "dosen't exists"
fi
回答by chepner
First, use getopts
to parse the options -n
and -v
(they will have to be used before any non-options, but that's not usually an issue).
首先,用于getopts
解析选项-n
和-v
(它们必须在任何非选项之前使用,但这通常不是问题)。
while getopts nv opt; do
case $opt in
n) nflag=1 ;;
v) vflag=1 ;;
*) printf >&2 "Unrecognized option $opt\n"; exit 1 ;;
esac
done
shift $((OPTIND-1))
Now, you will have only your two required arguments, and possibly your third optional argument, in $@
.
现在,在$@
.
string_arg=
type_arg=
dir_arg=
if [ -d "$dir_arg" ]; then
# Do something with valid directory
fi
Note that this code will work in any POSIX-compliant shell, not just bash
.
请注意,此代码可以在任何符合 POSIX 的 shell 中工作,而不仅仅是bash
.