我有点新的bash,我有一个问题,我无法在互联网上找到解决方案。
在我做一些尝试自己编程之类的事情之前,我想看看处理这种情况的标准方式是什么。
基本上,我想捕获getopts到array ...
我不确定我是否足够清楚,所以让我们尝试一下这个PHP示例:
http://www.test.com/index.php?a=1&b=2
<?php
function getParams() {
return $_GET[];
}
?>
这就是我想要的样子: myScript -a 1 -b 2
到目前为止,我发现的每一份getopts都暗示着我需要确切知道我想获得的样子:
while getopts a:b: option
do
case "${option}"
in
a) a=${OPTARG};;
b) b=${OPTARG};;
esac
done
无论这些选项如何
OPTS = get_params
echo $OPTS[@]
然后我可以对自己的验证等...
再次对不起,如果我错过了明显的东西,我真的很陌生,我真的很感谢您从哪里开始的任何帮助或指导。
非常感谢您。
简单:
declare -A myopts
while getopts cqz:b:a: OPTNAM ;do
myopts[$OPTNAM]=$OPTARG
done
测试:
set -- -a 4 -b 23 -c -q -- file test
declare -A myopts
while getopts cqz:b:a: OPTNAM ;do
myopts[$OPTNAM]=$OPTARG
done
set | grep ^myopts=
myopts=([a]="3" [b]="3" [c]="" [q]="" )
echo ${@:$OPTIND}
file test
[ ${myopts[c]+.} ] && echo switch c present
switch c present
for sw in c q z;do
echo switch $sw $(
[ ${myopts[$sw]+.} ] && echo present || echo absent )
done
switch c present
switch q present
switch z absent
echo ${myopts[a]}
3
您可以沿着这些行:
#!/bin/bash
declare -A my_opts
while (($#)); do
case $1 in
-- )
shift
break
;;
-* )
my_opts[${1#-}]=$2
shift 2
;;
* )
break
;;
esac
done
for k in "${!my_opts[@]}"; do
echo "$k => ${my_opts[$k]}"
done
# At this point, you still have the remaining arguments in $@
echo "Arguments left: ${@:-(none)}"
# End of script #
调用此脚本test_args
和chmod +x test_args
。然后(说明这种过度简化的方法的副作用):
$ ./test_args -a 1 -b 2
a => 1
b => 2
Arguments left: (none)
$ ./test_args -a 1 -- -b 2
a => 1
Arguments left: -b 2
$ ./test_args -a 1 foo -b 2
a => 1
Arguments left: foo -b 2
$ ./test_args --a 1 -b 2
-a => 1
b => 2
Arguments left: (none)
$ # And a bad one (with this simplified version):
$ ./test_args -a -- foo
-a => --
Arguments left: foo