Reputation: 167
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.
Upvotes: 12
Views: 12399
Reputation: 2162
Description of bash components used in script below.
"$@"
set -- "$@" "$1"
shift
$#
One way to use all of this, is where we want to loop through all the command line parameters, filtering some of changing them is some way. Here is an example that filters a specific parameter (e.g --values=xyz). It loops through all of them adding the ones we want to keep to the end and shifting left dropping the first one every-time.
#!/bin/bash
argc=$#
j=0
while [ $j -lt $argc ]; do
case "$1" in
--values=?*)
# do nothing remove this
;;
*)
set -- "$@" "$1"
;;
esac
shift
j=$((j + 1))
done
Upvotes: 1
Reputation: 532238
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
Upvotes: 21