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

Viewed 9189

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.

2 Answers

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
Related