skip to Main Content

I want to create a script that compares the value of specific get request headers.

So far script content is this:

var=$(curl -I -s http://myhost.local | grep X-Magento-Cache-Debug | awk {'print $2'})

if [ "$var" = "HIT" ]; then
  echo "OK"
else    
  echo "NOK"
  exit 2
fi

So using this script I want to compare the value of X-Magento-Cache-Debug. The problem is that the script always prints NOK regardless the value.

It looks like the string comparison here fails although when i echo the var value i get the desired content.

Any ideas will be helpful thanks.

2

Answers


  1. You are comparing the literal string var to the literal string HIT. The comparision would always be false.

    If you want to compare the content of the variable var for equality it would be

    [ "$var"  =  HIT ]
    

    However, this would be false if the output of your pipe does not consist just of the word HIT, but much more text.

    If you want to know, whether the content of the variable contains the substring HIT somewhere, this would be

    [[ $var == *HIT* ]]
    

    Another possibility would be to let grep do the job:

    if curl -I -s http://myhost.local | grep X-Magento-Cache-Debug | grep -wF HIT 
    then
      ....
    fi
    
    Login or Signup to reply.
  2. Alternative 1:

    Test your condition directly in awk:

    curl -sI http://www.stackoverflow.com 
      | awk '/Connection/ { if ($2 ~ /keep-alive/) { exit 0; } } END { exit 1; }'
    

    Alternative 2:

    Use safer and more flexible pattern matching with [[ =~ ]]

    $ conn=$(curl -sI http://www.stackoverflow.com | awk '/Connection/ { print $2 }')
    $ [[ $conn =~ keep ]] && echo KEEP
    KEEP
    

    or … if [[ $conn =~ keep ]]; then foobar ; fi

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search