这是我正在尝试做的
while getopts "h?rd" opt; do
case "$opt" in
h|\?)
echo "invalid"
exit 0
;;
r) report=1
;;
d) delete=1
;;
esac
done
-r & -d 起作用,作为参数传递的任何其他字符也会发出错误。 但如果我不使用参数,代码也会运行。我也想提示错误。我怎样才能做到这一点?
最佳答案
您可以使用 bash 的 $#
变量来查找任何参数。也可以通过在 getopts
case *)
获取其他无效参数
#!/bin/bash
if [ $# -lt 1 ]; then
echo "no arguments"
exit 1
fi
while getopts ":h\?rd" opt; do
case "$opt" in
h|"\?")
echo "valid"
exit 0
;;
r) report=1
;;
d) delete=1
;;
*) echo "not valid"
;;
esac
done
关于linux - 当没有输入参数时,如何使用 getopts 来避免运行脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38309991/