Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array argument to the Bash script

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 
like image 305
zhihong Avatar asked Jun 21 '13 10:06

zhihong


People also ask

What does [- Z $1 mean in bash?

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


1 Answers

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 
like image 142
glenn jackman Avatar answered Sep 28 '22 02:09

glenn jackman