Create array in loop from number of arguments

后端 未结 1 559
死守一世寂寞
死守一世寂寞 2020-12-28 15:32
#!/bin/bash
COUNTER=$#
until [ $COUNTER -eq 0 ]; do
args[$COUNTER]=\\$$COUNTER
let COUNTER-=1
done
echo ${args[@]}

When i run this, I get the follo

相关标签:
1条回答
  • 2020-12-28 16:09

    You can use the += operator to append to an array.

    args=()
    for i in "$@"; do
        args+=("$i")
    done
    echo "${args[@]}"
    

    This shows how appending can be done, but the easiest way to get your desired results is:

    echo "$@"
    

    or

    args=("$@")
    echo "${args[@]}"
    

    If you want to keep your existing method, you need to use indirection with !:

    args=()
    for ((i=1; i<=$#; i++)); do
       args[i]=${!i}
    done
    
    echo "${args[@]}"
    

    From the Bash reference:

    If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix } and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

    0 讨论(0)
提交回复
热议问题