我有这个代码,并希望确保当有人跑步时#34; myscript.sh -h -h"或" myscript.sh -hh"它没有回应WOW 2次。
while getopts ":h-:" option; do
case $option in
h )
echo "WOW"
;;
esac
done
答案 0 :(得分:0)
使用变量检查是否已处理h=
while getopts "h" option; do
case $option in
h )
[ "$h" ] || echo "WOW"
h=1
;;
esac
done
:
[ "$h" ] || echo "WOW"
如果条件[ "$h" ]
为false,则行 weighted_choices = [('Red', 3), ('Blue', 2), ('Yellow', 1), ('Green', 4)]
population = [val for val, cnt in weighted_choices for i in range(cnt)]
random.choice(population)
将仅运行echo语句,并且仅当变量h为空时该条件为false。
答案 1 :(得分:0)
通常,在解析命令行参数时,您不会采取任何操作。相反,使用它们来设置一旦你解析了它们就可以检查的状态。
do_wow=0 # By default, don't echo "wow"
while getopts ":h-:" option; do
case $option in
h ) # do_wow will equal 1 whether you use -h
# once, twice, or 100 times.
do_wow=1
;;
esac
done
if [[ $do_wow -eq 1 ]]; then
echo "wow"
fi