BASH:具有默认参数值的getopts [英] BASH: getopts with default parameters value
问题描述
我还有另一个bash脚本问题,我根本无法解决.这是我显示问题的简化脚本:
I've got another bash-script problem I simply couldn't solve. It's my simplified script showing the problem:
while getopts "r:" opt; do
case $opt in
r)
fold=/dev
dir=${2:-fold}
a=`find $dir -type b | wc -l`
echo "$a"
;;
esac
done
我通过以下方式致电
./sc.sh -r /bin
这是可行的,但是当我不提供参数时,它是无效的:
and it's work, but when I don't give a parameter it doesn't work:
./sc.sh -r
在此脚本中,我希望/dev为我的默认参数$ 2.
I want /dev to be my default parameter $2 in this script.
推荐答案
之前可能还有其他参数,请不要对参数号($ 2)进行硬编码.
There may be other parameters before, don't hard-code the parameter number ($2).
getopts帮助说
The getopts help says
当一个选项需要一个参数,getopts的地方这样的说法到壳体变量OPTARG.结果 ...
[在静默错误报告模式下,如果 找不到必需的参数,getopts在名称中放置一个:",然后 将OPTARG设置为找到的选项字符.
When an option requires an argument, getopts places that argument into the shell variable OPTARG.
...
[In silent error reporting mode,] if a required argument is not found, getopts places a ':' into NAME and sets OPTARG to the option character found.
所以你想要
dir=/dev # the default value
while getopts ":r:" opt; do # note the leading colon
case $opt in
r) dir=${OPTARG} ;;
:) if [[ $OPTARG == "r" ]]; then
# -r with required argument missing.
# we already have a default "dir" value, so ignore this error
:
fi
;;
esac
done
shift $((OPTIND-1))
a=$(find "$dir" -type b | wc -l)
echo "$a"
这篇关于BASH:具有默认参数值的getopts的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!