Printing output from grep in bash script yields br

2019-03-03 17:12发布

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

But when I run this bash script that invokes the command, I get the following output:

 <--Content-Length: 1073741824

What is going on?

标签: bash shell curl
1条回答
你好瞎i
2楼-- · 2019-03-03 17:57

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 <--

where the \r carriage return sets the cursor to the start of the line, overwriting --> with <--.

You can strip the \r with sed:

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

echo "--> ${size} <--"
查看更多
登录 后发表回答