在bash脚本中从grep打印输出会产生损坏的字符串 [英] Printing output from grep in bash script yields broken string
本文介绍了在bash脚本中从grep打印输出会产生损坏的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下简单的bash脚本,将命令的输出存储在变量中并打印出来:
I have the following simple bash script that stores the output of a command in a variable and prints it:
size=$(curl -sI "http://speedtest.reliableservers.com/1GBtest.bin" | grep -i "length")
echo "--> ${size} <--"
在终端中运行命令时,得到以下输出:
When running the command in the terminal, I get the following output:
Content-Length: 1073471824
但是当我运行调用命令的bash脚本时,会得到以下输出:
But when I run this bash script that invokes the command, I get the following output:
<--Content-Length: 1073741824
这是怎么回事?
推荐答案
问题是HTTP响应标头以CRLF
或\r\n
结尾. $(..)
确实去除了\n
,但没有去除\r
,因此输出将是
The problem is that the HTTP response header ends with CRLF
or \r\n
. The $(..)
does strip the \n
but not the \r
, so that the output will be
--> 1073741824\r <--
其中\r
回车将光标设置到行的开头,并用<--
覆盖-->
.
where the \r
carriage return sets the cursor to the start of the line, overwriting -->
with <--
.
您可以使用sed
剥离\r
:
size=$(curl -sI "http://speedtest.reliableservers.com/1GBtest.bin" | grep -i "length" \
| sed -e 's/\r//' )
echo "--> ${size} <--"
这篇关于在bash脚本中从grep打印输出会产生损坏的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文