2013-03-28 51 views
0

在測試腳本中,我使用了很多次「curl」命令。爲了優化代碼,我想要在一個全局變量中執行「捲曲」選項。如何在一個變量中指定命令參數?

我讀了「捲曲」的使用條款,它說傳遞一個包含空格的參數必須是用單引號將其框起來。

但它不工作。

$ curl_options="-i -L -k -S --connect-timeout 30 --user-agent 'Opera/9.80 (Windows NT 6.1; WOW64) Presto/2.12.388 Version/12.14'" 
$ curl $curl_options "http://google.com" 

輸出結果:

curl: (6) Couldn't resolve host'' Opera ' 
curl: (6) Couldn't resolve host '(Windows' 
curl: (6) Couldn't resolve host 'NT' 
curl: (6) Couldn't resolve host '6 .1; ' 
curl: (6) Couldn't resolve host 'WOW64)' 
curl: (6) Couldn't resolve host 'Presto' 
curl: (6) Couldn't resolve host 'Version' 

回答

3

bash,你應該使用數組。這樣一來,你就不必擔心在字符串中的空間是兩個選項一個選項的一部分,或分離:

curl_options=(...) 
curl_options+=("--user-agent" "Opera/9.80 (Windows NT 6.1; WOW64) Presto/2.12.388 Version/12.14") 

curl "${curl_options[@]}" "http://google.com" 

如果您不能使用陣列(例如,他們AREN」噸您正在使用)外殼可用,你就必須退回到使用eval

$ curl_options="-i -L -k -S --connect-timeout 30 --user-agent 'Opera/9.80 (Windows NT 6.1; WOW64) Presto/2.12.388 Version/12.14'" 
$ eval "curl $curl_options http://google.com" 

這不是理想的,因爲你需要非常小心你如何設置的curl_options值,因爲eval已不知道什麼該值表示。 shell僅將該值插入傳遞給eval的字符串中,並且eval執行該值。錯別字可能會產生意想不到的後果。

+0

我早就意識到這個代碼。但teamlead並未批准此代碼。 – user2219963

+0

我已經使用'eval'與POSIX兼容的解決方案進行了更新。希望有人能夠提出一個更安全的方案,但我認爲這個用例是添加陣列支持的基本原理之一。 – chepner

+0

我有另一個變量 \t html_content ='$捲曲curl_options 「http://google.com」' \t html_content ='EVAL 「捲曲$ curl_options http://google.com」' 這個變種會廢話。它的工作原理是 – user2219963

相關問題