bash 脚本上的回车 \r
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22140338/
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
Carriage return \r on bash script
提问by James Wise
I have this bash script on my CentOS 5.3.
我的 CentOS 5.3 上有这个 bash 脚本。
#!/bin/bash RESULT=$(cat /tmp/logfile.log | grep -i "Backlog File Count" | awk '{print }') if [ "${RESULT}" -lt "5" ]; then echo "${RESULT} is less than 5" else echo "${RESULT} is greater than 5" fi
/tmp/logfile.log:
/tmp/logfile.log:
Backlog File Names (first 1 files)
This bash script should supposedly to get the value "1" on the log file and print the output. However, when I run the script, this is the error message:
这个 bash 脚本应该应该在日志文件中获取值“1”并打印输出。但是,当我运行脚本时,这是错误消息:
: integer expression expected
So when I set the debug mode, I found the "RESULT" variable output:
所以当我设置调试模式时,我发现了“RESULT”变量输出:
+ RESULT=$'1\r' ..... + '[' $'1\r' -lt 5 ']'
I've noticed that "\r" output is attached on the value.
我注意到 "\r" 输出附加在值上。
I would appreciate if any one could lead me why there is "\r" on that output and how to get rid of that error. I tried on CentOS 6.3 and there is no issue.
如果有人能引导我为什么该输出上有“\ r”以及如何摆脱该错误,我将不胜感激。我在 CentOS 6.3 上试过,没有问题。
# rpm -qa bash bash-3.2-32.el5_9.1
Thank you. James
谢谢你。詹姆士
回答by devnull
Your input file contains CR+LF line endings. Strip the CR before reading the variable. Say:
您的输入文件包含 CR+LF 行尾。在读取变量之前剥离 CR。说:
RESULT=$(tr -d '\r' < /tmp/logfile.log | grep -i "Backlog File Count" | awk '{print }')
Alternatively, you could remove the carriage returns from the input file by using dos2unix
or any other utility.
或者,您可以使用dos2unix
或任何其他实用程序从输入文件中删除回车符。
Moreover, saying:
此外,说:
cat file | grep foobar
is equivalent to saying:
相当于说:
grep foobar file
and avoids the Useless Use of Cat.