bash getopts 多个参数或默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22058316/
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
bash getopts multiple arguments or default value
提问by Greg
So I have a question about get opts in bash. I want to get the value of the arguments if they are present but if they are not present to use a default value. So the script should take a directory and an integer but if they aren't specified then $PWD and 3 should be default values. Here is what
所以我有一个关于 get opts in bash 的问题。如果它们存在,我想获取参数的值,但如果它们不存在,则使用默认值。所以脚本应该采用一个目录和一个整数,但如果没有指定它们,那么 $PWD 和 3 应该是默认值。这是什么
while getopts "hd:l:" opt; do
case $opt in
d ) directory=$OPTARG;;
l ) depth=$OPTARG;;
h ) usage
exit 0;;
\? ) usage
exit 1;;
esac
回答by anubhava
You can just provide default value before while
loop:
您可以在while
循环前提供默认值:
directory=mydir
depth=123
while getopts "hd:l:" opt; do
case $opt in
d ) directory=$OPTARG;;
l ) depth=$OPTARG;;
h ) usage
exit 0;;
*) usage
exit 1;;
esac
done
echo "<$directory> <$depth>"