[英]Access second argument in getopts option using bash
几天前在这里已经提出的相关问题
但是这次条件不同,使用getopts
跟随bash脚本
#!/bin/bash
ipaddr=""
sysip=""
msgType=""
sshTimeout=""
bulbIndex=""
bulbstate=""
while getopts ":ht:d:A:r:s:m:" OPTION
do
case $OPTION in
h)
usage $LINENO
;;
t)
let "t_count += 1"
ipaddr="${OPTARG}"
echo -e $ipaddr
;;
d)
let "d_count += 1"
echo "Not supported"
exit 0
;;
A)
let "A_count += 1"
bulbIndex="${OPTARG}" # After -A option firsr argument is bulb index and second is state off/on
bulbstate=$3
printf "Set %s state on %s bulb\n" $bulbstate $bulbIndex
;;
r)
let "r_count += 1"
sysip="${OPTARG}"
echo -e $sysip
;;
m)
let "m_count += 1" #message type 1:text 2:number 3:Text&number
msgType="${OPTARG}"
echo -e $msgType
;;
s)
let "s_count += 1"
sshTimeout="${OPTARG}"
echo -e $sshTimeout
;;
?)
echo -e "wrong command sysntax"
exit 0
;;
esac
done
上面的脚本对于-A
选项以外的所有选项都可以正常工作。它有什么问题让您从下面的脚本执行步骤中知道
$ ./sample.bash -A 3 OFF
Set OFF state on 3 bulb
这是预期的输出,但是当我给出多个选项时,它的行为就像
$ ./sample.bash -t 192.168.0.1 -r 192.169.0.33 -A 3 OFF
192.168.0.1
192.169.0.33
Set -r state on 3 bulb
在这里我期望OFF
而不是-r
并且显然它会给出此输出,因为这一次它不是$3
而是$7
但是我的问题是我如何告知脚本现在是$7
而不是$3
。
和
$ ./sample.bash -t 192.168.0.1 -A 3 OFF -r 192.169.0.33 -m 1
192.168.0.1
Set -A state on 3 bulb
这次-A
之后,所有选项都被丢弃,再次-A
改为OFF
我怎样才能正确访问后两个参数-A
选项中的任何序列-A
的选择吗?
也有人对问题的询问让我知道,坦白地说,解决方案的意思是非常简单或困难,但目前我不知道。
getopts每个选项仅接受一个参数。 如何将两个参数都传递给引号内的-A,然后在case语句内将它们分开?
A)
let "A_count += 1"
bulbIndex=${OPTARG% O*}
bulbstate=${OPTARG#* }
printf "Set %s state on %s bulb\n" $bulbstate $bulbIndex
;;
然后使用以下命令调用:
$ ./sample.bash -t 192.168.0.1 -r 192.169.0.33 -A "3 OFF"
给出:
192.168.0.1
192.169.0.33
Set OFF state on 3 bulb
如果您不能使用引号,则可以确保-A是最后使用的选项,那么您可以使用OPTARG来获取数字,然后单独获取最终参数。
A)
let "A_count += 1"
bulbIndex="${OPTARG}"
bulbstate=${@: -1}
printf "Set %s state on %s bulb\n" $bulbstate $bulbIndex
;;
与上场后最后OPTIND
发现得到it.Modified的方式-A
选项,如以下getopts
A)
let "A_count += 1"
let "index += $OPTIND" # where initial value of index is 2
bulbstate=${!index}
bulbIndex="${OPTARG}"
printf "Set %s state on %s bulb\n" $bulbstate $bulbIndex
((OPTIND++))
;;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.