Home > Software design >  Populate bash array with any amount of arguments
Populate bash array with any amount of arguments

Time:02-02

I'm trying to fill an array in my script by passing the content directly to the script:

bash ./script.sh arg1 arg2 arg3

I know that I can address these arguments with $1, $2 and so on but the array doesn't always have the same amount of items in it which is why I can't really do:

databases=($1 $2 $3)

I'd imagine that I could use a loop but I don't know how to loop through all passed arguments.

CodePudding user response:

You want

databases=("$@")

to capture all the parameters into the array.

You have to use quotes there, or else

bash ./script.sh "arg one" "arg two" "arg three"

won't capture the 3 parameters correctly.


As @Gordon says,

for db in "${databases[@]}"; do
    echo "$db"
done

As you've discovered: $databases acts like ${databases[0]} -- a bash quirk.

And quote your variables: not echo $i but echo "$i" -- make this a habit, it will save your hide.

  •  Tags:  
  • Related