如何在sh shell中循环参数

thu*_*ium 2 unix linux shell sh

我知道"for loop"可用于遍历所有参数.但对于我的代码,我更喜欢

i = 1
if [ ${$i} == xx] ; then
 xxx
fi

((iArg++))

if [ ${$i} == xx] ; then
 xxx
fi
Run Code Online (Sandbox Code Playgroud)

很明显,$ {$ i}无效.我该怎么做才对?

我曾经用csh写csh

$argv[$i]
Run Code Online (Sandbox Code Playgroud)

现在必须使用sh shell.感谢帮助

Joh*_*ica 5

由于这个非常困难,参数解析通常通过使用$1和完成shift.典型的循环可能如下所示:

while [ $# -gt 0 ]; do
    case $1 in
        -a) echo "-a";    shift 1;;   # option with no argument
        -b) echo "-b $2"; shift 2;;   # option which takes argument, use $2
        -c) echo "-c";    shift 1;;
    esac
done
Run Code Online (Sandbox Code Playgroud)

也就是说,间接变量名称的方法是!,如:

${!i}
Run Code Online (Sandbox Code Playgroud)