在遍历参数时确定是否有下一个参数

Determining if there is a next argument while iterating through the arguments

遍历参数时,如何确定是否有下一个参数?

我尝试解决这个问题的方法是检查下一个参数是否不为空,但我 运行 遇到了一些问题。

在此示例中,我打印了当前参数的值,如果之后有参数,则打印一些消息。

我的做法:

使用 $i+1 其中 $i+1 将为您提供下一个索引的值。

#!/bin/sh

for i in "$@"
do
    echo $i
    if ! [ ${i+1}="" ]; then
        echo "test"
    fi
done

sh test 1 2 3 4 5

但这没有用。我也试过 expr i + 1,但效果不佳。

如果有人能给我提示如何解决这个问题,我将不胜感激。

您可以使用计数器检查 $#:

n=1

for i in "$@"; do
   echo "$i"
   if [ $n -eq $# ]; then
      echo "test"
   fi
   n=$(expr $n + 1)
done
#!/bin/sh

while [ $# -gt 0 ] ; do
  echo 
  if [ -n "${2+x}" ]; then
    echo another arg follows
  fi
  shift
done
$ ./test.sh 1 2 3
1
another arg follows
2
another arg follows
3

这里的技巧是我们使用 shift 来使用参数列表而不是迭代它。下一个参数总是 </code>,我们知道它存在,因为我们只在 <code>$#(位置参数的计数,不包括 [=15=])为正时执行循环。要检查之后的参数 </code> 是否存在,我们可以使用 <code>${PARAM+WORD} 扩展,如果 PARAM 不存在则不生成任何内容,否则生成 WORD.

当然,shift会破坏参数列表。如果你不想那样,把东西移到一个函数中。下面的例子展示了我们如何通过将一个副本传递给一个 shift 在本地吃掉它的函数来处理相同的参数列表两次:

#!/bin/sh

func() {
  while [ $# -gt 0 ] ; do
    echo 
    if [ -n "${2+x}" ]; then
      echo another arg follows
    fi
    shift
  done
}

func "$@"
func "$@"
$ ./test.sh 1 2 3
1
another arg follows
2
another arg follows
3
1
another arg follows
2
another arg follows
3