通过Shell Scripting中的参数循环跳过第一个参数

时间:2018-02-24 17:13:59

标签: shell

#!/bin/sh
BACKUPDIR=$1
for argnum in {2..$#};do
    echo ${"$argnum"}
done

我试过这个,但它给了我这个错误: ./backup.sh:10:./ backup.sh:错误替换

1 个答案:

答案 0 :(得分:2)

使用shift命令在阅读后从参数列表中删除$1(从而将旧的$2重新编号为$1,即旧$3 1}}到$2等):

#!/bin/sh
backupdir=$1; shift
for arg; do
  echo "$arg"
done

为了提供与问题中的代码等效的文字(但不是特别好的做法),间接扩展(缺少此类security-impacting practices as eval)如下所示:

#!/bin/bash
#      ^^^^-- This IS NOT GUARANTEED TO WORK in /bin/sh

# not idiomatic, not portable to baseline POSIX shells; this is best avoided
backupdir=$1
for ((argnum=2; argnum<=$#; ++argnum)); do
  echo "${!argnum}"
done