Home > Blockchain >  Mutiple varaibles in while loop of bash scripting
Mutiple varaibles in while loop of bash scripting

Time:01-08

Suppose i have the below curl where i will be reading two of the varaibles from a file.how can we accomodate both the varaibles in a single while loop

while read p; do
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'HTTP_X_MERCHANT_CODE: STA' --header 'AK-Client-IP: 135.71.173.56' --header 'Authorization: Basic qwrewrereererweer'  -d '{
    "request_details": [
        {
            "id": "$p",  #first dynamic varaible which will be fetched from the file file.txt
            "id_id": "$q",  #second dynamic varaible to be fetched from the file file.txt
            "reason": "Pickup reattempts exhausted"
        }
    ]
}' api.stack.com/ask
done<file.txt

file.tx will have two columns from which the dynamic variables whill be fetched to the above curl. Pls let me know how can we accomodate both the variable in the above while loop

i will need bit of a help regarding the same

CodePudding user response:

read accepts multiple target variable names. The last one receives all the content not yet read from the line. So read p reads the whole line, read p q would read the first token (separated by whitespace) into p and the rest into q, and read p q r would read the first two tokens into p and q and any remaining junk into r (for example if you want to support comments or extra tokens in file.txt).

CodePudding user response:

Since you'll want to use a tool like jq to construct the payload anyway, you should let jq parse the file instead of using the shell.

filter='split(" ") |
  { request_details: [
       {
          id: .[0],
          id_id: .[1],
          reason: "Pickup reattempts exhausted"
       }
    ]
  }'

jq -cR "$filter" file.txt | 
  while IFS= read -r payload; do
    curl -X POST --header 'Content-Type: application/json' \
                 --header 'Accept: application/json' \
                 --header 'HTTP_X_MERCHANT_CODE: STA' \
                 --header 'AK-Client-IP: 135.71.173.56' \
                 --header 'Authorization: Basic qwrewrereererweer' \
         -d "$payload"
  done

The -c option to jq ensures the entire output appears on one line: curl doesn't need a pretty-printed JSON value.

  •  Tags:  
  • bash
  • Related