Teddy
Teddy

Reputation: 167

What does set -- “$@” "$i" mean in 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.

Upvotes: 12

Views: 12399

Answers (2)

Pieter
Pieter

Reputation: 2162

Description of bash components used in script below.

"$@"

  • is all the commandline parameters as a list

set -- "$@" "$1"

  • adds the first command line parameter to end of list, making it one longer

shift

  • shift's the command line parameters to the left, reducing them by one

$#

  • Is the length or number of command lime parameters.

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

chepner
chepner

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

Related Questions