carriage-return 和 if 语句中的通配符

carriage-return and wildcards in if statement

谁能告诉我为什么这不起作用:

#!/bin/bash
# 

foo="hello

world"

if [[ "$foo" == *"\r\r"* ]]
then 
  echo "two carriage-returns found"
fi  

编辑: Freddy 和 WjAndrea,非常感谢!哎呀,我花了几个小时试图让语法正确!

您需要检查两个换行符(换行符)\n\n 并使用 ANSI-C quoting:

#!/bin/bash

foo="hello

world"

if [[ $foo == *$'\n\n'* ]]; then
  echo "two newlines found"
fi

两个原因:

  1. 你有回车符 returns \r 与换行符 \n
  2. 那些 \r 字面上是反斜杠后跟小写 R,而不是回车符 returns

因此,您可以使用 C-style strings 让它们变得特别:

if [[ "$foo" == *$'\n\n'* ]]

或者放两个实际的换行符,但这很难看:

if [[ "$foo" == *"

"* ]]