Skip to content

Instantly share code, notes, and snippets.

@noureddin
Created January 29, 2017 06:26
Show Gist options
  • Save noureddin/51de9a1c949a4481d954914182294f78 to your computer and use it in GitHub Desktop.
Save noureddin/51de9a1c949a4481d954914182294f78 to your computer and use it in GitHub Desktop.
Edit GIST
#!/bin/bash
# edit a gist file contents: https://developer.github.com/v3/gists/#edit-a-gist
# based on https://gist.github.com/noureddin/93d6182acdd1dcdf880daee1b97af05f
GITHUB_USERNAME=noureddin # change this to your github username
if [ $# -lt 2 ]; then
printf "Usage: %s id filename [gistname]\n" $(basename "$0") >&2
exit 1 # exit with error
fi
# Parse the arguments
id="$1"
filename="$2"
[ -z "$3" ] && gistname="$filename" || gistname="$3"
# Check the file
if ! [ -e "$filename" ]; then
printf 'File "%s" not found!\n' "$filename" >&2
exit 1
fi
# Somehow sanitize the file content
# Remove \r (from Windows end-of-lines),
# Replace \ by \\
# Replace tabs by \t
# Replace " by \"
# Replace % by %%
# Replace EOL by \n
filecontent=$(sed -e 's/\r//' -e 's/\\/\\\\/g' -e 's/\t/\\t/g' -e 's/"/\\&/g' -e 's/%/%%/g' "${filename}" | awk '{ printf($0 "\\n") }')
# Build the JSON request
read -r -d '' JSON <<EOF
{
"files": {
"${gistname}": {
"content": "${filecontent}"
}
}
}
EOF
# Use curl to send a POST request
curl -u "${GITHUB_USERNAME}" -X PATCH -d "${JSON}" "https://api.github.com/gists/${id}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment