问题
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