It is surprising me that I do not find the answer after 1 hour search for this. I would like to pass an array to my script like this:
test.sh argument1 array argument2
I DO NOT want to put this in another bash script like following:
array=(a b c) for i in "${array[@]}" do test.sh argument1 $i argument2 done
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
Bash arrays are not "first class values" -- you can't pass them around like one "thing".
Assuming test.sh
is a bash script, I would do
#!/bin/bash arg1=$1; shift array=( "$@" ) last_idx=$(( ${#array[@]} - 1 )) arg2=${array[$last_idx]} unset array[$last_idx] echo "arg1=$arg1" echo "arg2=$arg2" echo "array contains:" printf "%s\n" "${array[@]}"
And invoke it like
test.sh argument1 "${array[@]}" argument2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With