Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does set -- “$@” "$i" mean in Bash?

Tags:

bash

The set command in the following loop is confusing to me.

for i in "$@"
do 
  set -- "$@" "$i" # what does it mean?
done

I can understand $@ is all the positional parameters, and $i is one of the positional parameters. However, I can't figure out what

set -- "$@" "$i" 

means.

like image 348
Teddy Avatar asked Mar 24 '16 18:03

Teddy


People also ask

What does $@ In bash mean?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What is $@ and $* in shell script?

• $* - It stores complete set of positional parameter in a single string. • $@ - Quoted string treated as separate arguments. • $? - exit status of command.

What's the difference between $@ and $* in bash?

There is no difference if you do not put $* or $@ in quotes. But if you put them inside quotes (which you should, as a general good practice), then $@ will pass your parameters as separate parameters, whereas $* will just pass all params as a single parameter.

What does set mean in bash?

set allows you to change the values of shell options and set the positional parameters, or to display the names and values of shell variables.


1 Answers

It's appending the value of $i onto the end of the positional parameters. Not sure why one would want to do it, but it's basically a verbose way of doubling the parameters. It has the same affect as

$ set -- a b c
$ echo "$@"
a b c
$ set -- "$@" "$@"
echo "$@"
a b c a b c
like image 129
chepner Avatar answered Sep 18 '22 00:09

chepner