4

I have a bash script like this

#!/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

The file curl1.txt contains of

fqdn (tab)hostname

..........

I have to update some data using theForeman API. I have a lot fqdns and hostnames so I've wrote the script above. The problem is with JSON, because I get an error like this:

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

When I put '{"host":{"name": "${hostname}"}}' instead '{"host":{"name": "'${hostname}'"}}' I get

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

So where is the problem? Can You help me with that?

10
  • You've a trailing \r character in your ${hostname} value: ptesrv02-lub\r . This is very likely to be the issue. Commented Jul 20, 2016 at 8:34
  • Ok, so what means \r ? In text file I have no sign like this and the file is generated by ruby script. Commented Jul 20, 2016 at 8:36
  • 1
    @Inian since you were the first one to present a working solution, please put your comment as an answer so OP can accept it. Commented Jul 20, 2016 at 9:15
  • 1
    @salih You should also provide your answer as it is an alternate and helpful method. Commented Jul 20, 2016 at 9:16
  • 1
    @alaSmith: You can click on the small tick-mark on the left of the answer below for accepting the post, thereby marking the post as solved. Commented Jul 20, 2016 at 9:22

2 Answers 2

1

To remove trivial special characters from files copied from Windows(CR-LF endings) 'tr' command can be used as

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

in your example above. Presence of these special characters mangles how bash treats characters.

Credits to threadp for pointing out the presence of special characters in the hostname variable.

If you ever suspect the file to have such CR-LF endings, you can confirm by searching for them by using grep, treating the file as binary

grep -U $'\015' curl1.txt
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

That will just remove the last character, better to use something like "${hostname/$'\r'/}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.