Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
" "${array[@]}"

And invoke it like

test.sh argument1 "${array[@]}" argument2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...