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.

3
  • There might be newline after http version? Commented May 31, 2015 at 18:28
  • test uses single = for string comparision, not double == Commented May 31, 2015 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.) Commented May 31, 2015 at 19:39

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

5 Comments

Ok, tried both of your options above, but still only get the 'else' version.
Can I just match the 'Method Not Allowed' portion of the text somehow?
@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.)
@bmcgonag: Added a regex option, although it is also dependent on using bash.
I used your answer along with umlauts combined. if [ "$line" = "Method Not Allowed" ]; then . thanks to you both.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.