0

I have the below shell script which reads a file, copies the content of the file to a variable and passes the variable as argument to another command.

declare -a arr=()
while IFS= read -r var
do
  arr+=( $var )
done < "accounts.json"
args=''
for j in "${arr[@]}"
 do
   args="$args $j"
 done
 peer chaincode invoke -n cc -C channel1 -c '{"Args":["InitLedgerAdvanced",'"\"$args\""']}'

This works very well when the accounts.json file is small. But I get an error that says "Argument list too long" when the size of accounts.json is too large. I have tried xargs but to no success.

edit 1:

below is example json file with only two rows

[{"accountID":"C682227132","accountStatus":"1"},
{"accountID":"C800427392","accountStatus":"1"}]

Below is what a peer command would look like with actual data

peer chaincode invoke -n cc -C channel1 -c '{"Args":["InitLedgerAdvanced","[{"accountID":"C682227132","accountStatus":"1"},
{"accountID":"C800427392","accountStatus":"1"}]"]}'
  • 1
    You would not be able to use xargs here as you (I assume) you need to give the complete JSON document in one go. Is that correct? Can that peer command be made to read the document from a file instead from the command line? (Note: I'm unsure what peer is). – Kusalananda Mar 28 at 20:23
  • Yes, I need the complete json document in one go. I cannot use the peer command to read document from a file. peer is not a native unix/linux command. It comes from Hyperledger fabric (a blockchain service). – user344247 Mar 28 at 20:25
  • 1
    Please show a sample of the input file and show what the -c argument is supposed to look like. I bet a simple jq script is all that's required. That would mean you don't need to break up the file into lines and then combine the lines into a string: jq would do that for you. – glenn jackman Mar 28 at 20:26
  • @glennjackman That wouldn't make the actual argument to peer shorter in the end, would it? – Kusalananda Mar 28 at 20:29
  • @glennjackman. I have edited my question and added a few examples. Please don't worry about use of double quotes inside single quotes. I have made sure to have escape characters – user344247 Mar 28 at 20:32
1

This might work

# slurp the accounts file into a variable
accounts=$(< accounts.json)

# create the json, escaping the accounts quotes along the way
printf -v json '{"Args":["InitLedgerAdvanced","%s"]}' "${accounts//\"/\\\"}"

# and invoke the command
peer chaincode invoke -n cc -C channel1 -c "$json"

If that still gives you trouble, you'll have to find a way to pass the -c argument to "peer" via stdin or a file, not as a command line argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.