Location parameters can be used
shift
Command left shift. For example
shift 3
Indicates the original
$4
Change
$1
, The original
$5
Change
$2
And so on.
$1
,
$2
,
$3
Discard,
$0
Do not move. Without Parameters
shift
The command is equivalent
shift 1
. Very useful Unix Command: shift. We know that the number of location variables or command line parameters must be fixed, or when the shell program does not know the number, all parameters can be assigned to the variable $ * together *. If you want shell to process parameters one by one without knowing the number of location variables, that is, after $1, after $2, it is $3. The value of $1 before the shift command is executed is not available after the shift command is executed.
Example:
# Test shift command (x_shift.sh)
Until [$ #-EQ 0]
Do
Echo "the first parameter is $1. The number of parameters is $ #"
Shift
Done
Run the preceding program x_shift.sh:
$./X_shift.sh 1 2 3 4
The result is as follows:
The first parameter is: 1. The number of parameters is: 4.
The first parameter is: 2. The number of parameters is: 3.
The first parameter is 3. The number of parameters is 2.
The first parameter is: 4. The number of parameters is: 1.
We can see that the number of variables ($ #) is reduced by one every time the shift command is executed, and the variable value is one bit in advance. The following code uses the until and shift commands to calculate the sum of all command line parameters.
# Shift application of the previous command (x_shift2.sh)
If [$ #-EQ 0]
Then
Echo "Usage: x_shift2.sh Parameters"
Exit 1
Fi
Sum = 0
Until [$ #-EQ 0]
Do
Sum = 'expr $ sum + $1'
Shift
Done
Echo "sum is: $ sum"
Execute the above program:
$ X_shift2.sh 10 20 15
The result is as follows:
45
The shift command has another important purpose. bsh defines nine location variables from $1 to $9, which does not mean that you can only use nine parameters in the command line, the shift command can be used to access more than 9 parameters.
The number of moving parameters at a time is specified by the parameter included in the shift command. For example, after the shell program processes the first nine command line parameters, you can use the shift 9 command to move $10 to $1.