在bash脚本中从grep打印输出会产生损坏的字符串

Ove*_*erv 1 bash shell curl

我有以下简单的bash脚本,它将命令的输出存储在变量中并打印出来:

size=$(curl -sI "http://speedtest.reliableservers.com/1GBtest.bin" | grep -i "length")

echo "--> ${size} <--"
Run Code Online (Sandbox Code Playgroud)

在终端中运行命令时,得到以下输出:

Content-Length: 1073471824
Run Code Online (Sandbox Code Playgroud)

但是,当我运行调用命令的bash脚本时,得到以下输出:

 <--Content-Length: 1073741824
Run Code Online (Sandbox Code Playgroud)

到底是怎么回事?

Ken*_*ney 5

问题是HTTP响应标头以CRLF或结尾\r\n。所述$(..)确实剥离\n,但不是\r,以便输出将是

--> 1073741824\r <--
Run Code Online (Sandbox Code Playgroud)

其中\r回车光标设置到该行的开始,覆盖--><--

您可以剥除\rsed

size=$(curl -sI "http://speedtest.reliableservers.com/1GBtest.bin" | grep -i "length" \
     | sed -e 's/\r//' )

echo "--> ${size} <--"
Run Code Online (Sandbox Code Playgroud)