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:

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

7 Answers
7

Leave a Comment