簡體   English   中英

在循環中運行curl會導致意外輸出

[英]Running curl in a loop results in unexpected output

在curl中,我做了類似的事情來檢查URL是否可用:

$ curl -u admin:secret -s http://test.app.com/doSomething -o /dev/null -w "%{http_code} %{url_effective}\\n"
200 http://test.app.com/doSomething

我有一個主機和路徑列表,我想要使用GET請求定期檢查,輸出應該顯示響應狀態和被調用的URL。 因此,對於一組主機tests.app.com,a1.app.com,p.app.com和路徑“/ doSomething”和“doSomethingElse”,我將運行該腳本並期望以下輸出

200 http://test.app.com/doSomething
200 http://test.app.com/doSomethingElse
200 http://a1.app.com/doSomething
404 http://a1.app.com/doSomethingElse
200 http://p.app.com/doSomething
500 http://p.app.com/doSomethingElse

這樣我可以看到路徑doSomethingElse不起作用。

現在我的腳本看起來像這樣:

#!/bin/bash

HOSTS=(
        'test.app.com'
        'a1.app.com'
        'p.app.com'
)
PATHS=(
        'doSomething'
        'doSomethingElse'
)

USER=admin
PASS=secret

# fixed parameters
auth_header="-u ${USER}:${PASS}"
out_parms="-w \"%{http_code} %{url_effective}\\\n\""

for h in "${HOSTS[@]}"; do
        for p in "${PATHS[@]}"; do
                curl ${auth_header} -s http://${h}/${p} -o /dev/null ${out_parms}
        done
done

它產生幾個curl調用(類似於頂部的示例),但是當我運行此腳本時,輸出如下所示

"200"000"200"000"200"000"200"000"200"000"200"000

注意:“200”似乎是狀態代碼,我的設置中有6個請求。

如果我在curl命令( echo curl ${auth_header} ... )之前添加一個echo ,我會得到一個命令列表,我可以從命令行執行這些命令並導致預期的結果。

我究竟做錯了什么?

讓bash 打印出你的curl命令正在執行的內容

(set -x; curl ${auth_header} -s http://${h}/${p} -o /dev/null ${out_parms})

生成以下輸出:

++ curl -u admin:secret -s http://test.app.com/doSomething -o /dev/null -w '"%{http_code}' '%{url_effective}\\n"'
"301"000++ curl -u admin:secret -s http://test.app.com/doSomethingElse -o /dev/null -w '"%{http_code}' '%{url_effective}\\n"'
"301"000++ curl -u admin:secret -s http://a1.app.com/doSomething -o /dev/null -w '"%{http_code}' '%{url_effective}\\n"'
"301"000++ curl -u admin:secret -s http://a1.app.com/doSomethingElse -o /dev/null -w '"%{http_code}' '%{url_effective}\\n"'
"301"000++ curl -u admin:secret -s http://p.app.com/doSomething -o /dev/null -w '"%{http_code}' '%{url_effective}\\n"'
"301"000++ curl -u admin:secret -s http://p.app.com/doSomethingElse -o /dev/null -w '"%{http_code}' '%{url_effective}\\n"'
"301"000

看着

-w '"%{http_code}' '%{url_effective}\\n"'

我們可以看到curl命令沒有按照你想要的方式進行格式化

正如這里所回答的,你應該總是在變量替換周圍加上雙引號 ; 但是,沒有理由參數化out_parms。 將該定義內聯如下:

curl ${auth_header} -s http://${h}/${p} -o /dev/null -w "%{http_code} %{url_effective}\n"

以你期望的格式給我這個輸出。

301 http://test.app.com/doSomething
301 http://test.app.com/doSomethingElse
301 http://a1.app.com/doSomething
301 http://a1.app.com/doSomethingElse
301 http://p.app.com/doSomething
301 http://p.app.com/doSomethingElse

或者,如果要保留out_parms,如果將out_parms更改為,則會生成相同的輸出

out_parms="-w %{http_code} %{url_effective}\n"

並在curl命令中將雙引號括起來

curl ${auth_header} -s http://${h}/${p} -o /dev/null "${out_parms}"

暫無
暫無

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

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