在 Bash 脚本中使用 shift 命令
    
    Fumbani Banda
    2024年2月15日
    
    Bash
    Bash Command
    Bash Shift
    
 
在类 Unix 操作系统中,shift 命令是 Bash shell 中的内置命令,它使参数的索引从移位位置 N 开始。该命令删除列表中的第一个参数。
shift 命令只接受一个参数,一个 integer。
在 Bash 脚本中使用 shift 命令
下面的 bash 脚本演示了如何使用 shift 命令。bash 脚本有一个 add 函数,在函数内部,我们有三个部分。
每个部分添加两个数字并打印总和。bash 脚本的最后一行调用函数并将 5 参数传递给函数。
例子:
#!/bin/bash
add(){
  echo "Using default shift value"
  sum=`expr $1 + $2`
  echo \$1=$1
  echo \$2=$1
  echo "sum="$sum
  echo "------------"
  echo "Passing the integer,1, to the shift command"
  shift 1
  sum1=`expr $1 + $2`
  echo \$1=$1
  echo \$2=$2
  echo "sum="$sum1
  echo "------------"
  echo "Passing the integer,2, to the shift command"
  shift 2
  sum3=`expr $1 + $2`
  echo \$1=$1
  echo \$2=$2
  echo "sum="$sum3
}
add 1 2 3 4 5
输出:

add 函数的第一部分不使用 shift 命令。
从上面的 bash 脚本中,变量 $1 将采用 1 而 $2 将采用 2。数字的总和将是 3。
第二部分将整数 1 传递给 shift 命令。我们忽略传递给函数的第一个参数,因为第一个参数将是第二个参数,下一个参数将是第三个参数,依此类推。
变量 $1 将采用值 2,而变量 $2 将采用 3。变量值的总和为 5。
最后一部分将整数 2 传递给 shift 命令。我们在第二个和第三个参数中忽略了 2 和 3。
我们将开始计算第一个参数为 4,第二个参数为 5。两个参数的和是 9。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Fumbani Banda
    
