bash 在bash中使用回车执行字符串比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20378726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:52:18  来源:igfitidea点击:

Performing string comparison with carriage return in bash

stringbashshellsh

提问by Zhro

Why does the following code fail in bash? Note, I am trying to perform a more complex comparison such as "somestring\r"; this is just a simplified example.

为什么以下代码在 bash 中失败?请注意,我正在尝试执行更复杂的比较,例如 "somestring\r"; 这只是一个简化的例子。

I can confirm that the carriage return "ascii 13" is getting into the script. But I cannot compare against it with a regular string comparison.

我可以确认回车符“ascii 13”正在进入脚本。但是我无法将它与常规字符串比较进行比较。

The expected result is "1" for a positive match.

正匹配的预期结果是“1”。

Command line:

命令行:

echo -e "\r" | ./test.sh

Script:

脚本:

ord() {
   printf '%d' "'"
}

read a
echo "1st char: $(ord ${a:0:1})"

left="${a:0:1}"

if [ "$left" = "\r" ]; then
   echo 1
fi

exit 0

采纳答案by devnull

The following would illustrate how you can determine if the string contains a carriage return:

下面将说明如何确定字符串是否包含回车:

read a
if [[ $a =~ $'\r' ]]; then
  echo 1;
fi

Executing it by saying:

执行它说:

echo -e "something\r" | bash foo

would return

会回来

1


EDIT: If you want to figure whether the last character of a string contains a carriage return, you could say:

编辑:如果您想确定字符串的最后一个字符是否包含回车,您可以说:

if [[ ${a: -1} = $'\r' ]]; then
  echo 1;
fi