Difference between $@ and $ * scripts in bash

I am new to bash and I am learning it and I have doubts about the real difference between using $@ and S* .

I'm here red bash Special options

I understand that both expand to positional parameters, but the difference occurs in double quotes. By the way, " $@ " = "$1" "$2"..."$n" may be different from "S*" = "$1$2...$n".

I am trying to figure this out with a simple script:

 if [ $# -gt 0 ]; then echo "Your command line contains $# arguments" else echo "Your command line contains no arguments" exit fi echo "Params are: " echo $@ echo $* echo " $@ " echo "$*" 

if I execute my script in a terminal like this ~./my_script par1 par2 par3

the result is always the same:

 Params are: par1 par2 par3 par1 par2 par3 par1 par2 par3 par1 par2 par3 

Perhaps I do not understand the real use of both special variables and if my example is true or not. I would also like to find this example with a good example.

+4
source share
2 answers

From http://tldp.org/LDP/abs/html/refcards.html :

"$ *" All positional parameters (as one word) *

"$ @" All positional parameters (as separate lines)

This code shows this: if a string with elements separated by spaces is specified, $@ treats each word as a new element, and $* considers them all together as one and the same parameter.

 echo "Params for: \ $@ " for item in "${@}" do echo $item -- done echo "Params for : \$*" for item in "${*}" do echo $item -- done 

Test:

 $ ./a par1 par2 par3 Your command line contains 3 arguments Params for: $@ par1 -- par2 -- par3 -- Params for : $* par1 par2 par3 -- 
+3
source

They may look the same if you use echo , but this is because they are treated the same way with echo and are not equivalent.

If you pass the three command line arguments specified in the bash script to C, using ./my_c $@ ,

you will get the result ARGV[1] == "par1" ARGV[2] == "par2" ARGV[3] == "par3" .

If you pass the three command line arguments specified in the bash script to the C program using ./my_c $* ,

you will get the result ARGV[1] == "par1 par2 par3" .

( ARGV is an array of arguments provided in C, the first element is always the name of the command with which the program was called)

This will increase the flexibility with what you do with these parameters later in the script.

+4
source

Source: https://habr.com/ru/post/1208924/


All Articles