1

I am writing a bash script and I would like to be able to store each command line argument as it's own variable. So if there was a command line like so:

./myscript.sh word anotherWord yetAnotherWord

The result should be:

variable1 = word
variable2 = anotherWord
variable3 = yetAnotherWord

I have tried using a for loop and $@ like so:

declare -A myarray
counter=0
for arg in "$@"
do
  myarray[$counter]=arg
done

but when i try to echo say variable1 i get arg[1] instead of the expected word any help would be appreciated.

2
  • Also, there's little reason to use an associative array if all the keys are going to be integers anyway. An indexed array doesn't have to be contiguous: foo=([0]=a [5]=b [13]=c) is legal. Commented Feb 7, 2020 at 17:48
  • Your current loop just has a typo: arg is a regular string; $arg is the value of the parameter named arg. You also appear to be writing $myarray[1] rather than ${myarry[1]}. Commented Feb 7, 2020 at 18:22

2 Answers 2

4

They already are stored in a variable: $@. You can access the individual indices as $1, $2, etc. You don't need to store them in new variables if those are sufficient.

# Loop over arguments.
for arg in "$@"; do
    echo "$arg"
done

# Access arguments by index.
echo "First  = $1"
echo "Second = $2"
echo "Third  = $3"

If you do want a new array, args=("$@") will assign them all to a new array in one shot. No need for the explicit for loop. You can then access the individual elements with ${args[0]} and the like.

args=("$@")

# Loop over arguments.
for arg in "${args[@]}"; do
    echo "$arg"
done

# Access arguments by index.
echo "First  = ${args[0]}"
echo "Second = ${args[1]}"
echo "Third  = ${args[2]}"

(Note that using an explicit array the indices start at 0 instead of 1.)

Sign up to request clarification or add additional context in comments.

Comments

-1

I would use a while loop like this:

#!/bin/bash

array=()
counter=0
while [ $# -gt 0 ]; do 
    array[$counter]="$1"
    shift
    ((counter++))

done

#output test
echo ${array[0]}
echo ${array[1]}
echo ${array[2]}

Output is:

root@system:/# ./test.sh one two tree 
one two tree

I use the counter for passed arguments $# and shift which makes the first argument $1 get deleted and $2 gets $1.

Hope i could help you.

2 Comments

There's no reason to drop into a POSIX-style loop (that uses a bash extension to increment counter anyway) just to populate an array that can be populated identically without any loop.
Aside from a couple of non-loop-related typos, the OP's loop works, too. This answer doesn't add anything of value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.