shell study-14day--shift (parameter shift left)

. 1 , the Shift parameter shift instructions

The shift command is used to move the parameters (left shift). It is usually used to traverse each parameter in turn without knowing the number of incoming parameters and then perform the corresponding processing (common in the startup scripts of various programs in Linux) .

When the scanning process parameters of the script, often use the shift command, if your script needs 5 or 5 more than one parameter, you will need to use to access the first shift command 5 parameters a and back .

Function: Each time it is executed, the parameter sequence moves one position to the left, and the value of $# (the number of parameters passed to the script) is reduced by 1, which is used to process each parameter separately, and the removed parameters are no longer available .

Example 1: Addition calculation

[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]#

Personal public number:

image.png

Guess you like

Origin blog.51cto.com/13440764/2575390