[英]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? 我已经尝试过如何在Bash的'if'语句中比较两个字符串变量的建议?
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.
我什至在此之前回显$ line,然后复制并粘贴结果,以确保字符串正确。
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. 如果您从兼容的HTTP网络连接中读取该行,则几乎可以肯定它的末尾有一个回车符(
\\x0D
,通常表示为\\r
),因为HTTP协议使用CR-LF终止的行。
So you'll need to remove or ignore the CR. 因此,您需要删除或忽略CR。
Here are a couple of options, if you are using bash: 如果您使用的是bash,则有两个选项:
Remove the CR (if present) from the line, using bash find-and-replace syntax: 使用bash查找和替换语法从该行中删除CR(如果存在):
if [ "${line//$'\\r'/}" = "HTTP/1.1 405 Method Not Allowed" ]; then
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
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.) (如果使用正则表达式,请确保不使用正则表达式运算符。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.