Jay Wehrman
Jay Wehrman

Reputation: 193

BASH store command line arguments as separate variables

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.

Upvotes: 1

Views: 3748

Answers (2)

John Kugelman
John Kugelman

Reputation: 361605

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.)

Upvotes: 4

tzuxi
tzuxi

Reputation: 117

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.

Upvotes: -1

Related Questions