Convert command line arguments into an array in Bash Convert command line arguments into an array in Bash bash bash

Convert command line arguments into an array in Bash


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.


Maybe this can help:

myArray=("$@") 

also you can iterate over arguments by omitting 'in':

for arg; do   echo "$arg"done

will be equivalent

for arg in "${myArray[@]}"; do   echo "$arg"done


Actually the list of parameters could be accessed with $1 $2 ... etc.
Which is exactly equivalent to:

${!i}

So, the list of parameters could be changed with set,
and ${!i} is the correct way to access them:

$ set -- aa bb cc dd 55 ff gg hh ii jjj kkk lll$ for ((i=0;i<=$#;i++)); do echo "$#" "$i" "${!i}"; done
12 1 aa12 2 bb12 3 cc12 4 dd12 5 5512 6 ff12 7 gg12 8 hh12 9 ii12 10 jjj12 11 kkk12 12 lll

For your specific case, this could be used (without the need for arrays), to set the list of arguments when none was given:

if [ "$#" -eq 0 ]; then    set -- defaultarg1 defaultarg2fi

which translates to this even simpler expression:

[ "$#" == "0" ] && set -- defaultarg1 defaultarg2