Home > OS >  Simplify if and else to a single line
Simplify if and else to a single line

Time:08-17

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

CodePudding user response:

Just put ; in proper places.

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

You can also do this:

exit $(( $(curl --silent --output /dev/null --write-out "%{http_code}" "https://httpbin.org/status/200") != 200 ))

Walter, here you go :p

exit $(( $(curl --silent --output /dev/null --write-out "%{http_code}" "https://httpbin.org/status/200") == 200 ? 0 : 1 ))

CodePudding user response:

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)

CodePudding user response:

You can do something like this :

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

CodePudding user response:

Since you are exiting in both branches, you might as well just do:

status=$( curl ... )
test "$status" -eq 200

These must be the last lines of the script. If for some reason you have more code in the script that you want to ignore but not delete, just add an exit. If you want, you can be explicit and write exit $? but it's not necessary, since exit with no argument is equivalent.

The script will exit with the status of the last executed command, so if "$status" is 200, the script exits 0. If it is not 200, it will exit 1. Note that this also generates a comprehensible error message if the curl is somehow munged and status is set to a non-integer value, while that error message is not visible if you use [[.

  •  Tags:  
  • bash
  • Related