1

I'm using cURL to check links for uptime in a bash script like this:

curl -Lo /dev/null --silent --head --write-out '%{http_code}' $link

Where link="http://deadlink/" for example.

It returns 000 cos it's a dead link which is fine, but whenever I get a 000 response from cURL (since it could be for many reasons), I'd like to apply some logic to find out what's happening there. For instance, is it because connection refused, timeout, ssl failure, etc?

I assume the best way would some way to isolate the error code directly from cURL and apply tests to it using IF statements. That would be fine, so the closest I've got to extracting the error code from cURL by itself is this:

failState=$(curl -Ss $link; echo "error code is $?" )
echo $failState

Which nicely returns:

curl: (6) Could not resolve host: brokenlink
error code is 6

How do I get the "6" into a variable?

nooblag
  • 678
  • 3
  • 23
  • BTW, this is discussed in [BashFAQ #2](http://mywiki.wooledge.org/BashFAQ/002). – Charles Duffy Apr 19 '19 at 15:57
  • As another aside, if you only want *one* piece of output and don't need to distinguish specific non-successful HTTP status values, consider using `--fail` so curl will set `$?` to 22 should there be a HTTP status of 400 or above. – Charles Duffy Apr 19 '19 at 16:01

1 Answers1

1

you can assign $? to another variable right after assigning curl's output to failState.

failState=$(curl -Ss "$link") exitCode=$?
oguz ismail
  • 1
  • 16
  • 47
  • 69
  • 1
    (1) Consider quoting `"$link"`; (2) Consider putting the exit-status collection on the same line as the command setting it so logging or other code changes are less likely to unintentionally modify the status before it's collected. – Charles Duffy Apr 19 '19 at 15:54