What's the difference between $* and $@ in Shell scripts?
What's the difference between $* and $@ in Shell scripts? In order to solve this problem, today the editor summarizes this article about $* and $@, which can be used as a reference for interested friends. I hope it will be helpful to you.
When $* and $@ are not surrounded by double quotation marks, there is no difference between them, each parameter received is treated as a piece of data, separated by spaces.
But when they are enclosed in double quotes, there is a difference:
"$*" treats all parameters as a data as a whole, rather than each parameter as a data.
"$@" still treats each parameter as a piece of data, independent of each other.
For example, if five parameters are passed, for "$*", the five parameters will be merged together to form a piece of data, which can not be separated; for "$@", the five parameters are independent of each other. They are five pieces of data.
If you use echo to output "$" and "$@" directly, you can't see the difference, but if you use the for loop to output data one by one, you can immediately see the difference.
For the use of for loops, please click: Shell for loops and for int loops
Write the following code and save it as test.sh:
#! / bin/bash
Echo "print each param from\"\ $\ ""
For var in "$"
Do
Echo "$var"
Done
Echo "print each param from\"\ $@\ ""
For var in "$@"
Do
Echo "$var"
Done
Run test.sh with parameters:
[mozhiyan@localhost demo] $. . / test.sh a b c d
Print each param from "$"
A b c d
Print each param from "$@"
A
B
C
D
From the running results, you can see that for "$*", it only loops once because it has only 1 point of data; for "$@", it loops five times because it has five pieces of data.
After reading the above, do you have a general idea of the difference between $* and $@ in Shell scripts? If you want to know more about the content of the article, welcome to follow the industry information channel, thank you for reading!