Skip to content

Instantly share code, notes, and snippets.

@s-leroux
Created June 24, 2016 09:46
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save s-leroux/7cb7424d33ba3753e907cc2553bcd1ba to your computer and use it in GitHub Desktop.
Save s-leroux/7cb7424d33ba3753e907cc2553bcd1ba to your computer and use it in GitHub Desktop.
Post GIST
# 0. Your file name
FNAME=some.file
# 1. Somehow sanitize the file content
# Remove \r (from Windows end-of-lines),
# Replace tabs by \t
# Replace " by \"
# Replace EOL by \n
CONTENT=$(sed -e 's/\r//' -e's/\t/\\t/g' -e 's/"/\\"/g' "${FNAME}" | awk '{ printf($0 "\\n") }')
# 2. Build the JSON request
read -r -d '' DESC <<EOF
{
"description": "some description",
"public": true,
"files": {
"${FNAME}": {
"content": "${CONTENT}"
}
}
}
EOF
# 3. Use curl to send a POST request
# ANONYMOUS GIST :
# curl -X POST -d "${DESC}" "https://api.github.com/gists"
# REGISTERED USER
curl -u "${GITHUB_USERNAME}" -X POST -d "${DESC}" "https://api.github.com/gists"
@rubo77
Copy link

rubo77 commented Nov 18, 2016

If you need to create an anonymous gist comment the last line and uncomment:

curl -X POST -d "${DESC}" "https://api.github.com/gists"

posted on http://stackoverflow.com/a/33354920/1069083

@jaimet
Copy link

jaimet commented Jun 24, 2017

I don't have enough stackoverflow reputation to add a comment to the main conversation thread, but the reason why this breaks if the file contains a percent symbol (%) is because awk then attempts to treat it as a "Format-Control Letter" - please see https://www.gnu.org/software/gawk/manual/html_node/Control-Letters.html HTH, Jaime

@jaimet
Copy link

jaimet commented Jun 24, 2017

And it turns out that the solution is just to "double-escape" the percent symbols in the input, so line 9:
CONTENT=$(sed -e 's/\r//' -e's/\t/\t/g' -e 's/"/\"/g' "${FNAME}" | awk '{ printf($0 "\n") }')
becomes:
CONTENT=$(sed -e 's/\r//' -e's/\t/\t/g' -e 's/"/\"/g' "${FNAME}" | awk '{gsub("%","%%",$0);print $0}' | awk '{ printf($0 "\n") }')
:-)

@ceremcem
Copy link

ceremcem commented Sep 12, 2017

This code deserves a repo: https://github.com/ceremcem/create-gist (I'll hand it over to @s-leroux on request)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment