【问题标题】:Output of cURL is corrupted when stored to a bash variable [duplicate]存储到 bash 变量时,cURL 的输出已损坏 [重复]
【发布时间】:2018-06-23 06:35:41
【问题描述】:

这是我直接从终端执行 cURL 时控制台输出的内容:

/# curl -ksi http://localhost/ 
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.6.2
Date: Sun, 14 Jan 2018 11:49:38 GMT
Content-Type: text/html
Content-Length: 160
Connection: keep-alive
Location: http://localhost/welcome/default
Cache-Control: private, max-age=0

<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx/1.6.2</center>
</body>
</html>

但如果我尝试将 cURL 的输出保存到一个变量中,它的内容最终看起来已损坏:

/# VAR=`curl -ksi http://localhost/`
/# echo $VAR
 </html>nter>nginx/1.6.2</center>er>d>fault

在这种情况下我做错了什么?

【问题讨论】:

  • 您没有引用变量,这就是问题所在。总是说"$VAR",除非你有特定的理由不这样做。
  • 引用变量应该可以解决它!
  • 值中可能也有回车。
  • @Cyrus \r 不是问题。 \r 后面没有 \n 是一个问题。没有引号意味着所有的 \n 都变成了空格。只需使用引号就不会让它发生。
  • @Cyrus 为什么不呢?为我工作。

标签: bash curl newline carriage-return quoting


【解决方案1】:

使用数组

var=( "$(curl -ksi http://localhost/)" )
echo "${var[@]}"

旁注:不要将VAR之类的所有大写变量用作用户变量,因为它们是为shell环境保留的

【讨论】:

  • 数组将只包含一个元素。它对简单的字符串变量没有任何价值。
  • 我同意.. 我在考虑一个特定的用例,实际上我在 SO. 的一些答案中看到了它。但我无法链接它。
  • 感谢旁注!答案并不完全正确,不引用变量是问题
  • 确实,但你明白了吗? :-) 所以,很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 2020-07-04
  • 1970-01-01
相关资源
最近更新 更多