Skip to content

Instantly share code, notes, and snippets.

@noureddin
Forked from rubo77/create-gist.sh
Last active March 12, 2019 17:40
Show Gist options
  • Save noureddin/93d6182acdd1dcdf880daee1b97af05f to your computer and use it in GitHub Desktop.
Save noureddin/93d6182acdd1dcdf880daee1b97af05f to your computer and use it in GitHub Desktop.
Post GIST
#!/bin/bash
GITHUB_USERNAME=noureddin # change this to your github username
# or see https://gist.github.com/s-leroux/7cb7424d33ba3753e907cc2553bcd1ba
if [ "$1" == "" ]; then
printf "Usage: %s [--public] filename [gistname]\n" $(basename "$0") >&2
exit 1 # exit with error
fi
# Parse the arguments
if [ "$1" == '--public' ]; then
public='true'
filename="$2"
[ -z "$3" ] && gistname="$filename" || gistname="$3"
else
public='false'
filename="$1"
[ -z "$2" ] && gistname="$filename" || gistname="$2"
fi
# Check the file
if ! [ -e "$filename" ]; then
printf 'File "%s" not found!\n' "$filename" >&2
exit 1
fi
# Enter the description
echo -n 'Description: '
read description
# 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
{
"description": "${description}",
"public": ${public},
"files": {
"${gistname}": {
"content": "${filecontent}"
}
}
}
EOF
#printf '%s\n' "$JSON";exit
# Use curl to send a POST request
# ANONYMOUS GIST:
# curl -X POST -d "${JSON}" "https://api.github.com/gists"
# REGISTERED USER:
curl -u "${GITHUB_USERNAME}" -X POST -d "${JSON}" "https://api.github.com/gists"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment