The use of shift in shell programming under Linux

Source: Internet
Author: User


Positional parameters can be moved left with the shift command. For example, shift 3 means that the original $ $ is now $ $, the original $ $ $ $ $ $ $ $ The shift command with no parameters is equal to shift 1.

Very useful UNIX command: shift. We know that for positional variables or command parameters, the number must be certain, or when the shell program does not know its number, you can assign all the arguments to the variable $*. Left-side users require the shell in the case of not knowing the number of position variables, but also one by one the parameters-processing, that is, after the $ $ $, in the back of $ $. The value of the variable before the Shfit command executes is not available after the shift command executes.

Example one:

#!/bin/bash
Until [$#-eq 0]
Todo
echo "The parameter:$1 number is:$#"
Shift
Done

Example two:

#!/bin/bash
If [$#-eq 0]
Then
echo "Usage:a2.sh parameter"
Exit 1
Fi
Sum=0
Until [$#-eq 0]
Todo
sum= ' expr $sum + $
Shift
Done
echo "sum is: $sum"

Example three:


Here's a simple script that reads:

#!/bin/sh

Until [$#-eq 0]
Todo
echo "The first parameter is: $# number of arguments:"
Shift
Perform the above procedure x_shift.sh:

[root@ay1404171530212980a0z test]#./test 11 22 33 44 55 66 77

The results appear as follows:

The first parameter is: 11 The number of parameters is: 7
The first parameter is: 22 The number of parameters is: 6
The first parameter is: 33 The number of parameters is: 5
The first parameter is: 44 The number of parameters is: 4
The first parameter is: 55 The number of parameters is: 3
The first parameter is: 66 The number of parameters is: 2
The first parameter is: 77 The number of parameters is: 1

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.