'curl command can not be formed dynamically due to single quote [duplicate]

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



Solution 1:[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"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1