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
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
Side-by-side view of how the array and $@ are practically the same.
Code:
#!/bin/bash
echo "Dollar-1 : $1"
echo "Dollar-2 : $2"
echo "Dollar-3 : $3"
echo "Dollar-AT: $@"
echo ""
myArray=( "$@" )
echo "A Val 0: ${myArray[0]}"
echo "A Val 1: ${myArray[1]}"
echo "A Val 2: ${myArray[2]}"
echo "A All Values: ${myArray[@]}"
Input:
./bash-array-practice.sh 1 2 3 4
Output:
Dollar-1 : 1
Dollar-2 : 2
Dollar-3 : 3
Dollar-AT: 1 2 3 4
A Val 0: 1
A Val 1: 2
A Val 2: 3
A All Values: 1 2 3 4
Easier Yet, you can operate directly on $@
;)
Here is how to do pass a a list of args directly from the prompt:
function echoarg { for stuff in "$@" ; do echo $stuff ; done ; }
echoarg Hey Ho Lets Go
Hey
Ho
Lets
Go
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 aa
12 2 bb
12 3 cc
12 4 dd
12 5 55
12 6 ff
12 7 gg
12 8 hh
12 9 ii
12 10 jjj
12 11 kkk
12 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 defaultarg2
fi
which translates to this even simpler expression:
[ "$#" == "0" ] && set -- defaultarg1 defaultarg2
Here is another usage :
#!/bin/bash
array=( "$@" )
arraylength=${#array[@]}
for (( i=0; i<${arraylength}; i++ ));
do
echo "${array[$i]}"
done
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.