Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array in loop from number of arguments

#!/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.

like image 544
parsecpython Avatar asked Mar 14 '13 21:03

parsecpython


People also ask

Can you declare an array in a for loop?

You can declare (define) an array inside a loop, but you won't be able to use it anywhere outside the loop. You could also declare the array outside the loop and create it (eg. by calling new ...) inside the loop, in which case you would be able to use it anywhere as far as the scope the declaration is in goes.

How do you turn an argument into an array?

from() Method in JavaScript. Another way of converting the arguments object into an array is to use the method Array. from() . Here, we have to pass the arguments object inside the from() method, giving us an array.


1 Answers

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.

like image 58
jordanm Avatar answered Sep 19 '22 08:09

jordanm