之前可能有其他参数,请不要硬编码参数编号($ 2)。
的getopts的帮助表示
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"
我尝试过这一点。当我不带参数地调用它时仍然不起作用:./sc.sh -r ///错误:./sc.sh:选项需要参数 - r – Smugli
@Smugli:请参阅我的编辑 – chaos
谢谢。现在它工作得很好! – Smugli