1

I've tried the suggestion at How do I compare two string variables in an 'if' statement in Bash?

but it's not working for me.

I have

if [ "$line" == "HTTP/1.1 405 Method Not Allowed" ]
then
    <do whatever I need here>
else
    <do something else>
fi

No matter what, it always goes to else statement. I am even echoing $line ahead of this, and then copied and pasted the result, just to be sure the string was right.

Any help on why this is happening would be greatly appreciated.

Community
  • 1
  • 1
bmcgonag
  • 109
  • 2
  • 17
  • There might be newline after http version? – SMA May 31 '15 at 18:28
  • `test` uses single `=` for string comparision, not double `==` – umläute May 31 '15 at 19:01
  • By the way, instead of echoing the line (which won't let you see invisible characters), try using the bash printf %q format to show the line as a bash string: `printf %q\\n "$line"` (The quotes are important.) – rici May 31 '15 at 19:39

1 Answers1

2

If you read that line from a compliant HTTP network connection, it almost certainly has a carriage return character at the end (\x0D, often represented as \r), since the HTTP protocol uses CR-LF terminated lines.

So you'll need to remove or ignore the CR.

Here are a couple of options, if you are using bash:

  1. Remove the CR (if present) from the line, using bash find-and-replace syntax:

    if [ "${line//$'\r'/}" = "HTTP/1.1 405 Method Not Allowed" ]; then
    
  2. Use a glob comparison to do a prefix match (requires [[ instead of [, but that is better anyway):

    if [[ "$line" = "HTTP/1.1 405 Method Not Allowed"* ]]; then
    
  3. You could use regex comparison in [[ to do a substring match, possibly with a regular expression:

    if [[ $line =~ "Method Not Allowed" ]]; then
    

    (If you use a regular expression, make sure that the regular expression operators are not quoted.)

rici
  • 234,347
  • 28
  • 237
  • 341
  • Ok, tried both of your options above, but still only get the 'else' version. – bmcgonag May 31 '15 at 19:15
  • Can I just match the 'Method Not Allowed' portion of the text somehow? – bmcgonag May 31 '15 at 19:15
  • @bmcgonag: Sure. (If you're using bash.) `if [[ "$line" == *"Method Not Allowed"* ]]; then ...` (But if my solutions didn't work, you might not be using bash. Please check.) – rici May 31 '15 at 19:27
  • @bmcgonag: Added a regex option, although it is also dependent on using bash. – rici May 31 '15 at 19:33
  • I used your answer along with umlauts combined. if [ "$line" = *"Method Not Allowed"* ]; then . thanks to you both. – bmcgonag May 31 '15 at 20:22