简体   繁体   中英

Comparing variable to string in Bash

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM