Suman Srinivasan Suman Srinivasan - 2 months ago 17
Bash Question

Bash: convert command line arguments into array

How do I convert command-line arguments into a bash script array?

I want to take this:

./something.sh arg1 arg2 arg3


and convert it to

myArray=( arg1 arg2 arg3 )


so that I can use myArray for further use in the script.

This previous SO post comes close, but doesn't go into how to create an array: How do I parse command line arguments in bash?

I need to convert the arguments into a regular bash script array; I realize I could use other languages (Python, for instance) but need to do this in bash. I guess I'm looking for an "append" function or something similar?

UPDATE: I also wanted to ask how to check for zero arguments and assign a default array value, and thanks to the answer below, was able to get this working:

if [ "$#" -eq 0 ]; then
myArray=( defaultarg1 defaultarg2 )
else
myArray=( "$@" )
fi

Answer

Actually your command line arguments are practically like an array already. At least, you can treat the $@ variable much like an array. That said, you can convert it into an actual array like this:

myArray=( "$@" )

If you just want to type some arguments and feed them into the $@ value, use set:

$ set -- apple banana "kiwi fruit"
$ echo "$#"
3
$ echo "$@"
apple banana kiwi fruit

Understanding how to use the argument structure is particularly useful in POSIX sh, which has nothing else like an array.

Comments