How to pass an argument with space from bash script to bash script?

旧巷老猫 提交于 2019-12-06 09:13:37

问题


I have a script the manipulates data, creates arguments and sends them to a second script. One of the arguments contains a space.

script1.sh:

args=()
args+=("A")
args+=("1 2")
args+=("B")
. script2.sh ${args[@]}

script2.sh:

for f in "$@"
do
  echo f=$f
done

I'd like to get "1 2" as single argument, but receive them separately:

f=A
f=1
f=2
f=B

I tried also converting the input in script2 to list in=($@) and iterating over it using for f in ${in[@]} but got the same result.

So, the problem might be in one of the following: building the list of arguments ; passing the built list ; parsing the input ; or iterating over the input.

How to pass an argument with space from bash script to bash script? Thanks.

* I'm using git-bash on Windows.


回答1:


You just need to add quotes when passing the array as an argument:

args=()
args+=("A")
args+=("1 2")
args+=("B")
. script2.sh "${args[@]}"


来源:https://stackoverflow.com/questions/31726705/how-to-pass-an-argument-with-space-from-bash-script-to-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!