2015-11-19 31 views
2

假設我有一個文件params.txt包含內容多字參數

--option "option 1" --option "option 2" 

我想能夠使用的params.txt內容作爲命令行參數的一些程序, myProg

./myProg $(cat params.txt) 

./myProg `cat params.txt` 

但這似乎不起作用:它將多字參數視爲多個參數,而不是單引號參數。有沒有辦法使用命令替換(或其他慶典的功能,我不知道)從params.txt拉參數,並得到

./myProg --option "option 1" --option "option 2" 

爲執行命令的方法嗎?

+0

'params.txt'是由一個人或一個軟件寫的嗎? –

+0

...如果它來自軟件,最好的選擇是使它成爲NUL分隔符,而不是shell引用。 –

+0

謝謝。它是由人類寫的。如果它是NUL分隔的,會不會在bash中使用它?編輯:只看到你的答案的更新。謝謝! –

回答

3

如果params.txt是由你信任的人寫的,你可以用eval做到這一點:

eval "./myProg $(<params.txt)" 

要安全地從寫劇本的eval -safe流看起來不是這樣的:

printf '%q ' --option "option 1" --option "option 2" >params.txt 

更明確地存儲參數並在沒有the serious security risks caused by eval的情況下使用它們的方法是以NUL定界的流:

# write params file 
printf '%s\0' --option "option 1" --option "option 2" >params 

...然後,燒到那......

# read params file into array 
params=() 
while IFS= read -r -d '' param; do 
    params+=("$param") 
done <params 

# use that array to call your program 
./myProg "${params[@]}" 

注意,這後一種形式是不是命令替換兼容,但可以與進程替換,使用,如果你從命令讀取輸出比cat更有趣(最好用簡單的重定向代替)。因此:

# this does not work: depends on NULs being stored in a shell variable 
while IFS= read -r -d '' param; do params+=("$param"); done <<<"$(...command here...)" 

# this works 
while IFS= read -r -d '' param; do params+=("$param"); done < <(...command here...) 

請注意,過程替換是POSIX sh中不存在的功能;請確保您的shebang使用此支持指定了一個shell(例如#!/bin/bash)。