bashshellif-statementcurlecho

Match output of a CURL in an IF-ELSE condition in BASH


  1. I want to evaluate the output of a curl in an if-else.
  2. If the first condition matches, then shell return 0 and hence I equate to zero.
  3. Similarly for the second condition
  4. If Nothing matches go to else block

I have the following

if [[ curl https://www.example.com | grep -q "Match 1 Found" = 0 ]]
then
    echo "Match 1 Found"
elif [[ curl https://www.example.com | grep -q "Match 2 Found" = 0 ]]
then
    echo "Match 2 Found"
else
    echo "No Match Found"

PS : I am equating to zero since shell returns 0 if it is True


Solution

  • [[ ]] is used to evaluate conditional expressions, but you don't need that when testing a command. The exit status of a command is tested directly by if.

    So just write:

    if curl https://www.example.com | grep -q "Match 1 Found"
    

    If you're doing the same curl in both if and elif, you probably should save the output in a variable rather than going to the website twice.

    results=$(curl https://www.example.com)
    case "$result" in
        *"Match 1 Found"*) echo "Match 1 Found" ;;
        *"Match 2 Found"*) echo "Match 2 Found" ;;
        *) echo "No Match Found" ;;
    esac