0

I want to have a curl command like below

curl --location --request POST 'https://abcd.com/api/v4/projects/<projectId>/triggers' \
--header 'PRIVATE-TOKEN: <your_access_token>' \
--form 'description="my description"'

Now I wrote a shell script function to generate it dynamically

it need projectId, token, and description as a pramter

callApi(){
while IFS="," read -r -a users; do
for u in "${users[@]}"
do
url="'https://abcd.com/api/v4/projects/$1/triggers'"
echo $url

header="'PRIVATE-TOKEN: $2'" echo $header

desc="'description=$u token'" echo $desc

tk=$(curl --location --request POST $url
--header $header
--form $desc)

echo $tk

done done <<< $(cat $3) }

callApi "<projectId>" "<token>" ./users.csv

It echo perfectly But It thorws error

  • 1
    You have many errors .. Run your script through https://www.shellcheck.net. Basically, remove your single quotes to allow variable expansion and place your options into an array url=("https://abcd.com/api/v4/projects/$1/triggers") – rr0ss0rr Mar 16 '22 at 17:06
  • 1
    @rr0ss0rr: Look again. The single quotes are inside double quotes — I doubt that they’re the problem. – G-Man Says 'Reinstate Monica' Mar 16 '22 at 17:16
  • (1) Please don’t post questions that say “It throws error”.  Include any error messages you get in your question.  For that matter, don’t say “It echo perfectly”.  Show what it echos.  (2) You should always quote variables when you use them; e.g., POST "$url" --header "$header" --form "$desc". – G-Man Says 'Reinstate Monica' Mar 16 '22 at 17:16
  • 1
    But rr0ss0rr may be partly right: try taking out the single quotes. – G-Man Says 'Reinstate Monica' Mar 16 '22 at 17:20
  • on the other hand, tk= doesn't use any quote around variables... but uses variables that now include single quote around their data which is probably bad because these single quotes will be sent on the wire (and if there's a space in a token... even worse). – A.B Mar 16 '22 at 19:14

1 Answers1

2

Check out the accepted answer at How can we run a command stored in a variable?

The reason you face those problems is word splitting and the fact that quotes expanded from variables don't act as quotes, but are just ordinary characters.

I usually follow the below format when building a curl command, assigning each piece into an array

    url_request=("https://abcd.com/api/v4/projects/$1/triggers")
    url_body=(--form "$desac")
    url_header=(--header "PRIVATE-TOKEN: $2")
    url+=("${url_request[@]}" "${url_body[@]}" "${url_header[@]}")
response=$(curl -s &quot;${url[@]}&quot;)

rr0ss0rr
  • 342