Difference between $ @ and $ * in Shell

Source: Internet
Author: User

$ @ Refers to all command line parameters. Each parameter is enclosed ""

$ * Indicates all command line parameters

 

The following procedure:

Test1.sh

-------------------

Sum = 0
For VaR
In "$ @"
Do
Let sum = sum + $ VaR
Done
Echo "sum = $ sum"

 

./Test1.sh 1 2 3

The result is sum = 6.

 

Test2.sh

--------------------

Sum = 0
For VaR
In "$ *"
Do
Let sum = sum + $ VaR
Done
Echo "sum = $ sum"

./Test2.sh 1 2 3

The result is sum = 1.

 

Analysis 1:

Bash-x test1.sh

The result is as follows:

+ Sum = 0
+ For VAR in '"$ @"'
+ Let sum = sum + 1
+ For VAR in '"$ @"'
+ Let sum = sum + 2
+ For VAR in '"$ @"'
+ Let sum = sum + 3
+ Echo sum = 6
Sum = 6

It can be seen that for is executed three times, indicating that for is bounded by "", because each parameter is surrounded ""

 

 

Analysis 2:

Bash-x test2.sh

The result is as follows:

+ Sum = 0
+ For VAR in '"$ *"'
+ Let sum = sum + 1 2 3
+ Echo sum = 1
Sum = 1

It can be seen that the loop is executed only once, indicating that $ * is surrounded by "" as a whole, not every parameter is surrounded by "", so it is only executed once

 

 

A more direct example is:

For VaR
In "a B C"
Do
Echo "$ {var }@"
Done

Print:

A B C @

 

For VaR
In "A" "B" "C"
Do
Echo "$ {var }@"
Done

Print:

A @

B @

C @

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.