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

问题描述:

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

#!/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"` 

更新:删除返回刻度 - 现在看不到任何错误,但没有输出。

+0

也许你应该在'curl'命令周围丢掉'反引号' –

+1

反引号不仅仅用于运行命令;它们用于捕获命令的输出以用作另一个表达式中的值。 – chepner

+0

删除反卷绕反卷 - 我现在没有得到一个错误,但仍然没有输出。注意:它在命令行上工作。 – Koshur

主要的变化使是运行curl命令subsitution之外:

# 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" 
+0

我现在没有看到任何错误,但没有输出。 – Koshur

+1

@Koshur add a' v'标记到curl命令以查看发生了什么。如果服务器使用重定向进行回复,并且您没有要求'curl'来跟踪它们,那么可能会出现空的响应,但这只是一种可能性。 – Aaron