在 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
