我想要指定是使用
Normal Error Reporting
还是Silent Error Reporting
随getopts
一起提供的能力。
然后我就可以像这样调用我的 bash 函数
mari -s -n VAL -z VAL
-s
将设置静默错误报告(即设置opstring=":n:z:"
),否则将使用正常错误报告(opstring="n:z:"
)。
目前我在函数内部硬接线
opstring
。
mari()
{
impl=""
if [[ "$impl" == "SILENT" ]]; then
opstring=":n:z:" # Short options string
else
opstring="n:z:"
fi
while getopts "$opstring" opname; do
case ${opname} in
("n")
if [ -n "$OPTARG" ]; then
echo "The string is not empty"
else
echo "The string is empty"
fi
;;
("z")
if [ -z "$OPTARG" ]; then
echo "The string is empty"
else
echo "The string is not empty"
fi
;;
(?)
## Invalid Option Found, OPNAME set to '?'
echo "Invalid option: -$OPTARG" 1>&2
exit 1
;;
(:)
## Required option argument not found, OPNAME set to ':'
echo "Option -$OPTARG requires an argument" 1>&2
exit 1
;;
esac
done
}
一旦遇到
s
就修改opstring。
?
是一个 glob,它匹配任何东西。你必须引用它。
mari() {
local opstring
opstring="sn:z:"
while getopts "$opstring" opname; do
case ${opname} in
"s")
opstring=":${opstring%%:}"
;;
"n")
if [ -n "$OPTARG" ]; then
echo "The string is not empty"
else
echo "The string is empty"
fi
;;
"z")
if [ -z "$OPTARG" ]; then
echo "The string is empty"
else
echo "The string is not empty"
fi
;;
'?')
## Invalid Option Found, OPNAME set to '?'
echo "Invalid option: -$OPTARG" 1>&2
exit 1
;;
':')
## Required option argument not found, OPNAME set to ':'
echo "Option -$OPTARG requires an argument" 1>&2
exit 1
;;
esac
done
}
echo "no invalid option:"
mari -s -bla
echo "invalid option:"
mari -bla