日期:2014-05-16  浏览次数:20613 次

急:请指教如何使用变量替换$ 参数,谢谢!
现在想实现一个动态解析传入参数,如一个函数输入4个参数
两两参数对应一个子函数,现在需要循环获取参数,实现如下
if [ "$#" == 0 ];then
echo set default env
elif [ `expr $# % 2` == 0 ];then
for ((i=1; i<$#; i=i+2))
{
j=`expr $i + 1`
parse_param_list $1 $2  #####这里如何使用i j 变量替换,类似实现$1..$n的功能?
}
echo i=$i j=$j
else
echo "incorrect input format"
fi

请知道的指教一下,在线等待,谢谢!
------解决方案--------------------
#!/bin/bash
if [ "$#" == 0 ]; then
    echo set default env
elif [ `expr $# % 2` == 0 ]; then
    for ((i=1; i<$#; i=i+2)); do
        j=`expr $i + 1`
        parse_param_list $1 $2
        shift 2
    done
    echo i=$i j=$j
else
    echo "incorrect input format"
fi

------解决方案--------------------
引用:
Quote: 引用:

parse_param_list $i $j

$i $j只是变量1 2,类似于传入两个参数parse_param_list 1 1 
而不是实际的第1个 第2个参数哦

# !/bin/sh

if [ "$#" == 0 ]; then
    echo "set default env"
elif [ `expr $# % 2` == 0 ]; then
    array=($*)
    for((i=0; i<$#; i=i+2))
    do
        #parse_param_list $1 $2  #####这里如何使用i j 变量替换,类似实现$1..$n的功能?
        echo ${array[@]:i:2}
    done
else
    echo "incorrect input format"
fi