Create array in loop from number of arguments

parsecpython picture parsecpython · Mar 14, 2013 · Viewed 55.6k times · Source
#!/bin/bash
COUNTER=$#
until [ $COUNTER -eq 0 ]; do
args[$COUNTER]=\$$COUNTER
let COUNTER-=1
done
echo ${args[@]}

When i run this, I get the following results

user@host:~/sandbox# ./script.sh first second third
$1 $2 $3

and i'm expecting it to echo out what $1, $2, and $3 are not a text value of "$1"

I'm trying to write a script in bash that will create an array that is the size of the number of arguments I give it.
I'm expecting

user@host:~/sandbox# ./script.sh alpha bravo charlie
alpha bravo charlie

or

user@host:~/sandbox# ./script.sh 23425 jasson orange green verb noun coffee
23425 jasson orange green verb noun coffee

So, the goal is to make

args[0]=$1
args[1]=$2
args[2]=$3
args[3]=$4

The way that I have it, the $1,$2,$3 aren't being interpolated but just being read as a text string.

Answer

jordanm picture jordanm · Mar 14, 2013

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.