簡體   English   中英

如何將一個 bash 腳本中的 arguments 數組傳遞給另一個 arguments 有空格的腳本

[英]How to pass array of arguments in one bash script to another where some arguments have spaces

我正在編寫一個 bash 腳本,該腳本生成一個 arguments 列表以傳遞給另一個外部腳本。 此 arguments 列表可以包含帶有空格的字符串。 請注意,此 arguments 列表的長度將根據腳本的運行方式而有所不同。

bash 腳本如下所示:

#!/bin/bash
# script1.sh

... some code that populates the array ARGS_TO_PASS ...

# NOTE! ARGS_TO_PASS can be of varying length depending on what the above code does.
#
# Here is example of what ARGS_TO_PASS might be:
# ARGS_TO_PASS=(a b c 'the quick brown fox')

# Now, call script2.sh on ARGS_TO_PASS.
script2.sh ${ARGS_TO_PASS[*]}

這是第二個腳本:

#!/bin/bash
# script2.sh
while [[ $# -gt 0 ]]; do
    echo "parsing arg: $1"
    shift
done

如果script1.sh的最后一行是script2.sh ${ARGS_TO_PASS[*]} ,則 output 如下所示:

parsing arg: a
parsing arg: b
parsing arg: c
parsing arg: the
parsing arg: quick
parsing arg: brown
parsing arg: fox

如果script1.sh的最后一行是script2.sh "${ARGS_TO_PASS[*]}" output 看起來像這樣:

parsing arg: a b c 'the quick brown fox'

這些都不是我想要的。 想要的是 output 看起來像這樣:

parsing arg: a
parsing arg: b
parsing arg: c
parsing arg: the quick brown fox

有沒有辦法做到這一點?

您可以使用

script2.sh "${ARGS_TO_PASS[@]}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM