Suman Suman -4 years ago 100
Bash Question

Convert command line arguments into an array in Bash

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

I want to take this:

./ 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 )
myArray=( "$@" )

Answer Source

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 "$#"
$ 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download