curl在命令行上工作,但不在shell脚本中

时间:2017-02-28 15:04:30

标签: bash curl cookies sed

当我在命令行的curl命令中直接使用变量cookie的值时 - 它可以工作;但它在脚本中不起作用。以下错误:

#!/bin/bash

cookie=`tail -1000 cat.txt | grep -v "wm-ueug" | grep -v "JRECookie" | grep "JSESSIONID.*_ga=GA" | tail -1 | sed -r 's/.{26}//' | sed 's/.$//'`

`curl "http://example.com/monitor?method=monitor&refresh=true&count=4&start=1&dateFrom=2017-02-21&dateTo=2017-02-28&runId=&hidden_status=&dojo.preventCache=1488290723103" -H "Host: example.com" -H "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20400202 Firefox/50.0" -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" -H "Accept-Language: en-US,en;q=0.5" --compressed -H "Content-Type: application/x-www-form-urlencoded" -H "X-Requested-With: XMLHttpRequest" -H "Referer: http://example.com/monitor" -H "Cookie: $cookie" -H "Connection: keep-alive"`

更新:删除后退标记 - 现在看不到任何错误但没有输出。

1 个答案:

答案 0 :(得分:1)

要做的主要更改是在命令格式之外运行curl

# Not `curl ...`
curl ...

但是,您可能希望分解curl命令,使其更具可读性和可理解性。

#!/bin/bash

cookie=$(tail -1000 cat.txt |
         grep -v "wm-ueug" |
         grep -v "JRECookie" |
         grep "JSESSIONID.*_ga=GA" |
         tail -1 | sed -r 's/.{26}//' | sed 's/.$//')

# Parameters can be passed to curl via the -d option, rather
# than as a query string in the URL.
url="http://example.com/monitor"
parameters=(
   -d method=monitor
   -d refresh=true
   -d count=4
   -d start=1
   -d dateFrom=2017-02-21
   -d dateTo=2017-02-28
   -d runId=hidden_status
   -d dojo.preventCache=1488290723103
)

headers=(
   -H "Host: example.com"
   -H "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20400202 Firefox/50.0"
   -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
   -H "Accept-Language: en-US,en;q=0.5"
   -H "Content-Type: application/x-www-form-urlencoded"
   -H "X-Requested-With: XMLHttpRequest"
   -H "Referer: http://example.com/monitor"
   -H "Cookie: $cookie"
   -H "Connection: keep-alive"
)
curl --compressed "${parameters[@]}" "${headers[@]}" "$url"