0

I am attempting to check if a connection can be made with the url in the script, not sure if that is the best approach. The curl command's output is all going to stdout. I only want my echo to go to stdout after running the script below. I tried adding -s, but that did not help. I would appreciate some help.

check=$(curl -s -vv -I https://github.com | grep "HTTP/2 200")
if [[ -z "$check" ]]; then
  echo "Cnxn failed"
else
  echo "Cnxn successful"
fi

I would like to see something like this only:

Cnxn failed

or

Cnxn successful
Diego-S
  • 67
  • 4
  • `curl` by itself returns an exit code which indicates whether it was successful, so you can probably do this without the `-vv` and the `grep`. Bonus: it keeps working even if GitHub decides to switch to a different HTTP version :) – Thomas Oct 11 '22 at 18:38
  • add `2>&1` before the pipe, separated by a space of course, but yeah, what @Thomas said. – Jetchisel Oct 11 '22 at 18:40
  • Plus `grep -q` if you also want to hide the matching line from the grep output. – Thomas Oct 11 '22 at 18:42
  • what you're seeing on your terminal isn't `curl/stdout` but rather `curl/stderr`; you can redirect stderr to stdout (`2>&1` - Jetchisel's comment): `check=$(curl ... github.com 2>&1 | grep ...)`; keep in mind this is going to send all of that `stderr` output into the `check` variable; if you're 100% sure you won't need the stderr output you could replace the recommended `2>&1` with `2>/dev/null` (ie, discard all stderr output) – markp-fuso Oct 11 '22 at 18:48
  • How do I check for the exit code if I don't use grep? Thanks in advance @Thomas – Diego-S Oct 11 '22 at 19:35
  • https://stackoverflow.com/questions/2220301/how-to-evaluate-http-response-codes-from-bash-shell-script provides a lot of options/information that might be useful for you. – j_b Oct 11 '22 at 20:34

2 Answers2

1

Please try this code

check=$(curl -s -vv -I https://github.com 2>/dev/null | grep "HTTP/2 200")
#echo $check
if [[ -z $check ]] ; then
      echo "Cnxn failed"
    else
      echo "Cnxn successful"
fi
1

you get the return code by $?

curl -s -vv -I https://github.com/ardmy 2>/dev/null | grep -q "HTTP/2 200"
if [[ $? == 0 ]]; then
echo "Cnxn successful $?"
else
echo "Cnxn failed $?"
fi
Vincent Stans
  • 543
  • 4
  • 7
  • This works well. Thanks, I had to mark @AleksandrPakhomov 's response with the solution since his was earlier. – Diego-S Oct 12 '22 at 18:03