2017-07-14 23 views
0

下面的問題就是我的問題的變化:如何將給定的包含字符串參數的bash腳本的所有命令行參數傳遞給子進程?

Bash: Reading quoted/escaped arguments correctly from a string

我想寫以下類型的bash腳本(說 'something.sh')......

#!/bin/bash 

python $* 

...它將所有命令行參數直接傳遞給子進程。上述基於$ *作品的命令,如...

./something.sh --version 

...就好。然而,悲慘的失敗了的字符串參數例如像在這種情況下...

./something.sh -c "import os; print(os.name)" 

...這結果(在我的例子)在...

python -c import 

...切割字符串參數在第一空間(自然產生Python語法錯誤)。

我在尋找一個通用的解決方案,它可以處理由bash腳本調用的任意程序的多個參數和字符串參數。

+0

工作正常,當我測試它? –

+1

給[shellcheck](http://shellcheck.net)一個嘗試。它會自動指出這個問題。 –

回答

2

使用此:

python "[email protected]" 

[email protected]$*既擴大到腳本所有收到的參數,但是當你用[email protected],並把它用雙引號,它會自動重新報價一切都那麼它工作正常。

bash manual

展開爲位置參數,從1開始。當擴展出現在雙引號內時,每個參數都會擴展爲單獨的單詞。也就是說,"[email protected]"相當於"$1" "$2" …

參見Why does [email protected] work different from most other variables in bash?

相關問題