shell study-14day--shift(參數左移)

1Shift 參數左移指令

shift 命令用於對參數的移動(左移),一般用於在不知道傳入參數個數的狀況下依次遍歷每一個參數而後進行相應處理(常見於 Linux 中各類程序的啓動腳本)shell

在掃描處理腳本程序的參數時,常常要用到的shift命令,若是你的腳本須要5個或5個以上的參數,你就須要用shift命令來訪問第5個及其後面的參數bash

做用:每執行一次,參數序列順次左移一個位置,$#(傳遞到腳本的參數個數)的值減 1,用於分別處理每一個參數,移出去的參數,再也不可用.ide

實例1:加法計算

[root@test shell]# cat shift.sh 
#!/bin/bash
if [ $# -le 0 ];then 
        echo "無可用參數"
        exit
fi
 
sum=0
while [ $# -gt 0 ] ;do
        sum=$[$sum+$1]
        shift
done
 echo "total is $sum"
[root@test shell]# sh shift.sh 1 2 3 
total is 6
[root@test shell]#

我的公衆號:
spa

image.png

相關文章
相關標籤/搜索