0

I have a simple bash script that uses an api to add itself into a database. But the script keeps adding ' ' to my variables and its breaking curl.

hostname=`hostname`
ip_address=`ip add show eth0 | grep 'inet ' | awk '{ print $2 }' | cut -d '/' -f1`
env=`hostname | cut -d '-' -f1`
os=`cat /etc/issue.net | head -1`
date=`date`
curl -H 'Content-Type: application/json' -PUT "https://10.10.10.10/database" -k -d '{"Environment":"'$env'","Hostname":"'$hostname'","IP_Address":"'$ip_address'","OS":"'$os'","State":"OK","Updated_Time":"'$date'"}'
exit $?

The output is this:

curl -H 'Content-Type: application/json' -PUT https://10.10.10.10/database -k -d '{"Environment":"ops","Hostname":"ex-example-host","IP_Address":"10.10.10.10","OS":"Ubuntu' 14.04 'LTS","State":"OK","Updated_Time":"Thu' Aug 14 15:27:55 PDT '2014"}'

Both the $date and $hostname put ' ' on the inside the format breaking the curl. Is there a way to fix this?

Thanks,

2
  • When you say "the output", I think you mean what you see when you enable set -x. That's not what the application sees. set -x shows you what you could type directly to achieve the same effect. So the quotes that it shows are (in this case) not passed to curl. @chepner's answer is correct, although you could also achieve the same effect by double-quoting the variable interpolations: ..."'"$date"'"... or by double-quoting the whole -d argument and backslash-escaping the double-quotes which you want to pass through. Commented Aug 14, 2014 at 16:20
  • @rici I tried the "'" and that did not work. Still did the same thing. Commented Aug 14, 2014 at 21:39

1 Answer 1

1

The problem is that you are leaving the parameter expansions unquoted in bash, so spaces in those values break up the word being passed to curl. It would be simpler to swap your use of double and single quotes, if JSON allowed you to use single quotes. That not being the case, I'd store the JSON in a variable using read and a here document first to simplify the quoting.

read -r data <<EOF
{"Environment":"$env","Hostname":"$hostname","IP_Address":"$ip_address","OS":"$os","State":"OK","Updated_Time":"$date"}
EOF

curl ... -d "$data"
Sign up to request clarification or add additional context in comments.

Comments

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.