Upload a file to a Gist with bash
Here is a solution that works for me on Bash/Dash to create anonymous gist (very probably not bullet-proof):
# 0. Your file nameFNAME=some.file# 1. Somehow sanitize the file content# Remove \r (from Windows end-of-lines),# Replace tabs by \t# Replace " by \"# Replace EOL by \nCONTENT=$(sed -e 's/\r//' -e's/\t/\\t/g' -e 's/"/\\"/g' "${FNAME}" | awk '{ printf($0 "\\n") }')# 2. Build the JSON requestread -r -d '' DESC <<EOF{ "description": "some description", "public": true, "files": { "${FNAME}": { "content": "${CONTENT}" } }}EOF# 3. Use curl to send a POST requestcurl -X POST -d "${DESC}" "https://api.github.com/gists"
If you need to create a gist associated with your github account, (for basic authentication) replace the last line by:
curl -u "${GITHUB_USERNAME}" -X POST -d "${DESC}" "https://api.github.com/gists"
For more advanced authentification schemes, please see https://developer.github.com/v3/#authentication
A command line tool implemented in Python:
pip install python-gistgist create "example description" foo.txt bar.txt
See https://github.com/jdowner/gist
If you prefer a Ruby gem, see https://github.com/defunkt/gist
Building on the answer of Sylvain Leroux, we can replace the sanitization and json building steps by making use of the jq command line tool:
$ jq -Rs '{"description": "some description", "public": true, "files": {"'$FNAME'": {"content": .}}}' $FNAME | curl -X POST -d @- "https://api.github.com/gists"
Or, with authentication:
$ jq -Rs '{"description": "some description", "public": true, "files": {"'$FNAME'": {"content": .}}}' $FNAME | curl -u "${GITHUB_USERNAME}" -X POST -d @- "https://api.github.com/gists"