Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Simplify if and else to a single line

I want to know if it is possible to reduce this line to a single one

if [[ $(curl --silent --output /dev/null --write-out "%{http_code}" "https://httpbin.org/status/200") -ne 200 ]]; then
  exit 1
else
  exit 0
fi

If the status code of the request was different from 200, exit with error, if it was successfully, exit with 0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

curl already has defined exit codes for many situations if you use -f.

A lot of effort has gone into the project to make curl return a usable exit code when something goes wrong and it will always return 0 (zero) when the operation went as planned.

$ curl -f -s http://google.com >/dev/null ; echo $?
0
$ curl -f -s hoop://google.com >/dev/null; echo $?
1
$ curl -f -s http://test.invalid >/dev/null ; echo $?
6
$ curl -f -s http://google.com/invalid >/dev/null ; echo $?
22

To return modified codes (eg. 0 on a 404 as you suggest in a comment), you could do simple boolean manipulation:

$ echo $((
    $(curl -f -s -o /dev/null \
        -w '!(%{http_code}==404)' \
        https://httpbin.org/status/200)
  ))
1
$ echo $((
    $(curl -f -s -o /dev/null \
        -w '!(%{http_code}==404)' \
        https://httpbin.org/status/404)
  ))
0
$

(substitute exit for echo)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading