0

My temp file.

{"label": "Allowed","value": "20863962"} ,
{"label": "Denied","value": "5"} ,

Read into an array.

#Read into array
IFS=$'\r\n' items=($(cat < ./tmp))
# print all items
echo "${items[@]}"

The output shows this:

{"label": "Allowed","value": "20863962"} , {"label": "Denied","value": "5"} ,

And my final curl command is failing.

When I run the script with -x, it is showing extra characters in the output which I suspect may be causing my final curl command to fail.

+ echo '{"label": "Allowed","value": "20863962"} ,' '{"label": "Denied","value": "5"} ,'

Note the extra ' ' in the echo output.

My final curl command should like this:

curl -d '{ "auth_token":"pass", "items": [{"label": "Allowed","value": "20863962"} , {"label": "Denied","value": "5"}] }' http://lab:3030/widgets/test
1
  • But the extra ' ' in the output only represents the space between the two arguments to echo. What exactly is the output you needed? Commented Aug 8, 2013 at 7:27

2 Answers 2

1

To strip that extra "," you can do something like:

JSON='{"label": "Allowed","value": "20863962"} , {"label": "Denied","value": "5"} ,'
echo ${JSON%?}
# {"label": "Allowed","value": "20863962"} , {"label": "Denied","value": "5"}
Sign up to request clarification or add additional context in comments.

Comments

1
IFS=$'\r\n' items=($(cat < ./tmp))

When using the format var=($var2) or var=($(command)), if a string on it contains a pattern it would be subject to pathname expansion which could lead to representing existing filenames instead, so sometimes use read is preferable. Anyway this is how I would probably do it with bash. You might find it helpful as well.

#!/bin/bash

shopt -s extglob  ## enable extended patterns
IFS=$'\n' read -rd ''-a items  < file  ## read input to array
items=("${items[@]##+([^\{])}")  ## removing extra leading characters
items=("${items[@]%%+([^\}])?($'\r')}")  ## removing extra trailing characters

IFS=,  ## set IFS to , to separate values by commas in "${var[*]}"
echo curl -d "{ \"auth_token\":\"pass\", \"items\": [${items[*]}] }" "http://lab:3030/widgets/test"

You could also just completely disable pathname expansion with noglob. This also would only be valid on the shell that runs the script.

shopt -u -o noglob  ## or set +o noglob, or set +f
IFS=$'\r\n' items=($(cat < ./tmp))  ## simply the same as IFS=$'\r\n' items=($(<./tmp))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.