-1

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

Rajarshi Das
  • 11,778
  • 6
  • 46
  • 74
  • [Shellcheck](https://www.shellcheck.net/) finds many issues with the code. If you fix them there's a much better chance that it will work. – pjh Mar 16 '22 at 14:44

1 Answers1

1

Don't use both double and single quotes like that. You are adding literal single quotes to the url (and other variables) which, as you have discovered, breaks.

Use double quotes if you need to allow command or parameter substitution, single quotes otherwise. Double quote your variables everywhere you dereference them.

Use indentation for readability.

Useless use of cat.

I've captured the function parameters at the start of the function for visibility: I did not even notice the $1 buried in the URL.

callApi() {
  local project=$1 token=$2 userfile=$3

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

      header="PRIVATE-TOKEN: ${token}"
      echo "$header"

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

      tk=$(
        curl --location \
             --request POST \
             --header "$header" \
             --form "$desc" \
             "$url"
      )
      echo "$tk"
    done
  done < "$userfile"
}
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • its comming output url : `https://abcd.com/api/v4/projects/$1/triggers` It not able to detect $1 when I call the function `apiCall "2222" "token1" ./users.csv` – Rajarshi Das Mar 16 '22 at 16:32
  • Oh, I didn't notice the variable in there. That requires double quotes. I'll update – glenn jackman Mar 16 '22 at 16:47
  • What's the purpose of `tk` here? One could just let curl write its output straight to stdout, and except for not leaving that variable left over after the function is done, behavior would be identical. – Charles Duffy Mar 16 '22 at 18:20