2

How can I return 0 when the response status is 200?

Right now I'm able to get the status, e.g. 200 with the following command:

curl -LI http://google.com -o /dev/null -w '%{http_code}\n' -s

But what I need to do is turn this 200 in a return 0.

How can I achieve this?

I tried the following command but it doesn't return:

if [$(curl -LI http://google.com -o /dev/null -w '%{http_code}\n' -s) == "200"]; then echo 0
1Z10
  • 2,801
  • 7
  • 33
  • 82
  • Isn't the return code 0 if the command is successfult? Why not just use `$?` – msg Sep 14 '18 at 00:58
  • 2
    The code you showed should not run due to syntax errors. Also see [How to use Shellcheck](https://github.com/koalaman/shellcheck), [How to debug a bash script?](https://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](https://stackoverflow.com/q/951336/608639) (SO), [How to debug bash script?](https://askubuntu.com/q/21136) (AskU), [Debugging Bash scripts](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html), etc. – jww Sep 14 '18 at 01:40
  • 1
    cross-posted: https://superuser.com/q/1358026/4714 – glenn jackman Sep 14 '18 at 03:21

4 Answers4

20

You can also use the -f parameter:

(HTTP) Fail silently (no output at all) on server errors. This is mostly done to better enable scripts etc to better deal with failed attempts.

So:

curl -f -LI http://google.com

Will return status 0 if the call was sucessful.

Dherik
  • 17,757
  • 11
  • 115
  • 164
12

Looks like you need some spaces and a fi. This works for me:

if [ $(curl -LI http://google.com -o /dev/null -w '%{http_code}\n' -s) == "200" ]; then echo 0; fi
Jack
  • 5,801
  • 1
  • 15
  • 20
4

The most simple way is to check for curl's exit code.

$ curl --fail -LI http://google.com -o /dev/null -w '%{http_code}\n' -s > /dev/null
$ echo $?
0
$ curl --fail -LI http://g234234oogle.com -o /dev/null -w '%{http_code}\n' -s > /dev/null
$ echo $?
6

Please note that --fail is neccessary here (details in this answer). Also note as pointed out by Bob in the comments (see footnote) that in case of a non-200 success code this will still return 0.

If you don't want to use that for whatever reason, here's the other approach:

http_code=$(curl -LI http://google.com -o /dev/null -w '%{http_code}\n' -s)
if [ ${http_code} -eq 200 ]; then
    echo 0
fi

The reason your code isn't working is because you have to add spaces within the brackets.

(Copied from my answer on SuperUser where OP cross-posted the by now deleted question)

confetti
  • 1,062
  • 2
  • 12
  • 27
0

Another way is to use the boolean operator && :

[ $(curl -LI http://google.com -o /dev/null -w '%{http_code}\n' -s) == "200" ] && echo 0

The second command will be executed only if the first part is True.

Gianluca Mereu
  • 300
  • 1
  • 4