Home > database >  shell script: cat file content then use it in curl post
shell script: cat file content then use it in curl post

Time:07-27

im trying to hit gitlab release api to update my release note description field from CHANGELOG.md file
these are what ive tried:

#!/bin/sh

releaseNote=$(cat CHANGELOG.md)
curl --header 'Content-Type: application/json' --request PUT --data '{"description": "'"${releaseNote}"'"}' --header "PRIVATE-TOKEN: mytokenhere" "https://gitlab.com/api/v4/projects/1234/releases/0.1"
#!/bin/sh

releaseNote=$(cat CHANGELOG.md)
curl --header 'Content-Type: application/json' --request PUT --data '{\"description\": \"${releaseNote}\" }' --header "PRIVATE-TOKEN: mytokenhere" "https://gitlab.com/api/v4/projects/1234/releases/0.1"

when i try to hard-code description field like this, it works

#!/bin/sh

curl --header 'Content-Type: application/json' --request PUT --data '{"description": "foo"}' --header "PRIVATE-TOKEN: mytokenhere" "https://gitlab.com/api/v4/projects/1234/releases/0.1"

and here is whats inside my CHANGELOG.md file

# Changelog

All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

## 1.0.0 (2022-07-22)


### Features

* abc
* def

any suggestion guys?

CodePudding user response:

Here is a way you can solve this issue

# content of a file we need
FILE_MD=$(<file.md);


# variable for curl using single quote => ' not double "
CURL_DATA='{
    "repository": "tmp",
    "command": "git",
    "args": [
        "pull",
        "origin",
        "'"$FILE_MD"'"
    ],
    "options": {
        "cwd": "/home/git/tmp"
    }
}';

# test it
echo "$CURL_DATA";

# or run it
curl -s -X POST ... -H 'Content-Type: application/json' --data "$CURL_DATA" 

first

Read content of that file into a variable i.e. FILE_MD

second

Wrap other data you have in single quote ' not double one "

third

Wrap your variable for a file content i.e. FILE_MD in "'" ... "'"

fourth

Pass the variable CURL_DATA to curl

curl -s -X POST ... -H 'Content-Type: application/json' --data "$CURL_DATA" 

CodePudding user response:

as per @LéaGris suggestion above, finally it works.. here is my code snippet

#!/bin/sh


# format CHANGELOG.md to proper JSON format first
releaseNote=$( jq -sR '{"description": .}' CHANGELOG.md )

# hit the API
curl --header 'Content-Type: application/json' --request PUT --data "$releaseNote" --header "PRIVATE-TOKEN: mytokenhere" "https://gitlab.com/api/v4/projects/1234/releases/0.1"

  • Related