4

我有一个这样的 bash 脚本

#!/bin/bash

while read fqdn hostname; do
curl -H "Content-Type:application/json" -XPUT "https://server/api/hosts/${fqdn}" -d '{"host":{"name": "'${hostname}'"}}' --cacert bundle.pem --cert pnet-pem.cer --key privkey.pem
done <curl1.txt

文件 curl1.txt 包含

fqdn(选项卡)主机名

…………

我必须使用 Foreman API 更新一些数据。我有很多 fqdns 和主机名,所以我编写了上面的脚本。问题出在 JSON 上,因为我收到如下错误:

{"status":400,"error":"There was a problem in the JSON you submitted: 795: unexpected token at '{\"host\":{\"name\": \"ptesrv02-lub\r\"}}'"}

当我'{"host":{"name": "${hostname}"}}'代替时'{"host":{"name": "'${hostname}'"}}',我得到

{
  "error": {"id":130,"errors":{"interfaces.name":["is invalid"],"name":["is invalid"]},"full_messages":["Name is invalid","Name is invalid"]}
}

那么问题出在哪里?你能帮我吗?

4

2 回答 2

1

As threadp pointed, you have a trailing \r character. You can try this to remove it.

${hostname%?}

This usage just remove last character, in this scenario, it was trailing \r. But, it is better to use

${hostname/$'\r'/}

Thanks 123

于 2016-07-20T09:30:51.453 回答
1

要从从 Windows(CR-LF结尾)复制的文件中删除琐碎的特殊字符,“tr”命令可以用作

hostname=$(echo $hostname|tr -d '\r')

在你上面的例子中。这些特殊字符的存在破坏了bash对待字符的方式。

归功于threadp指出hostname变量中存在特殊字符。

如果您怀疑文件有这样的CR-LF结尾,您可以通过使用搜索它们来确认grep,将文件视为二进制文件

grep -U $'\015' curl1.txt
于 2016-07-20T09:20:15.320 回答