0

After iterating thru the shell arguments and filtering out unwanted arguments into an array, I want to assign the array back to $*.

For example, in the below script, I want to remove the arguments -f java, which are in sequence, and store the rest of the arguments in the args array. Is there a way to assign the filtered arguments back to $*?

I am trying to do set --${*} $args, but it is taking only the first argument and not the whole array.

If I pass

$ .test.sh arg1 arg2 -f java7 arg3 
arg1 arg2 agr3 
while (( $# )); do
    if [[ $1 = "-f" ]] && [[ $2 = "java7" ]]; then
        unset USE_JAVA8
        JAR=signals.jar
        echo "USE_JAVA8 Flag is OFF running Signal on java7"
        shift 2
        continue
    fi
args+=( "$1" )
shift

done

set --${*} $args

echo $*

Kusalananda
  • 333,661
  • In bash, $arrayname only gets the first element of the array; you want "${arrayname[@]}" (or in this case, set -- "${args[@]}"). You should almost never use $* or leave off the quotes, because either way it causes confusion between gaps between arguments and whitespace within arguments. See my explanation here (about $@, not an array, but it works the same). – Gordon Davisson Jul 18 '22 at 03:59
  • 1
    See: http://mywiki.wooledge.org/BashGuide/Arrays and https://www.gnu.org/software/bash/manual/html_node/Arrays.html – ilkkachu Jul 18 '22 at 09:28

1 Answers1

2

Assuming you are using the bash shell, $args would be the equivalent of ${args[0]}, i.e., the first element of the array args.

To set the list of positional parameters to the values of the array args, you would use

set -- "${args[@]}"

Note that "${args[@]}" must be quoted exactly like this, or the individual elements of the array would potentially be split into multiple words by the shell and undergo filename globbing. If you use "$*" (a single quoted string) or "$@" (a list of individually quoted strings), these should be used quoted for the same reason.

Also related:


In the zsh shell, set -- $args would correctly have set the list of positional parameters to the list of elements from the args array.

Kusalananda
  • 333,661