How can I get an HTTP status code with an AWK one-liner?

爱⌒轻易说出口 提交于 2019-12-25 05:03:38

问题


I want to print just the HTTP status code for a web page retrieved using cURL. Is it possible to do this with an AWK one-liner?


回答1:


You can get it with just curl, without even using awk:

curl -I http://example.com/ -w '%{response_code}' -so /dev/null

curl's -I option makes a HEAD request, which is usually what you want for this.




回答2:


Solution

The following one-liner will read the HTTP header from a pipe, and print out the status code.

awk 'BEGIN {"curl -sI http://example.com" | getline; print "Status Code: " $2}'

Interesting Aspects

There are a few nice things about this approach that may not be obvious at first glance. For example:

  • This solution is pure AWK; no shell script or wrapper required.
  • Since we only care about the first line of the header, we don't need to track or compare NR to skip undesirable lines.
  • $0 is populated in a BEGIN block, so AWK doesn't need a file argument.


来源:https://stackoverflow.com/questions/11137310/how-can-i-get-an-http-status-code-with-an-awk-one-liner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!