Created
August 25, 2020 16:41
-
-
Save 0x6362/099575d0a92d542bea2bfc65de953930 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -e | |
usage() { | |
echo "giphy-grab [-f|--force] [-s|--skip-title] [-o|--output] <url>" | |
echo " --force: overwrite output file if it exists" | |
echo " --skip-title: don't fetch GIF name from GIPHY" | |
echo " --output: filename or destination folder for GIF" | |
exit 1 | |
} | |
POSITIONAL=() | |
while [[ $# -gt 0 ]] | |
do | |
key="$1" | |
case $key in | |
-h|--help) | |
usage | |
shift | |
shift | |
;; | |
-f|--force) | |
OVERWRITE="true" | |
shift | |
;; | |
-s|--skip-title) | |
SKIP_TITLE="true" | |
shift | |
;; | |
-o|--output) | |
OUTPUT="$2" | |
shift | |
shift | |
;; | |
*) # unknown, save for later unpacking | |
POSITIONAL+=("$1") | |
shift | |
;; | |
esac | |
done | |
set -- "${POSITIONAL[@]}" # restore unflagged params | |
if (( ${#POSITIONAL[@]} < 1 )); then | |
usage | |
fi | |
extract_id() { | |
echo "$1" | grep -E -o "\b[a-zA-Z0-9]{10,20}\b" | |
} | |
fetch_title() { | |
curl -L -s "https://giphy.com/gifs/$1" \ | |
| grep -E -o "<title>.+</title>" \ | |
| sed -E 's/\<[^>]+\>//g' \ | |
| sed -E 's/ GIF.* - Find & Share on GIPHY//' | |
} | |
URL="$1" | |
ID=$(extract_id "$URL") | |
GIF_URL="http://i.giphy.com/media/${ID}/giphy.gif" | |
if [[ "$SKIP_TITLE" ]] && [[ -z "$OUTPUT" ]]; then | |
echo "-o|--output must be used when -s|--skip-title flag is set" >&2 | |
exit 1 | |
fi | |
if [[ -z "$SKIP_TITLE" ]]; then | |
COMPUTED_NAME=$(fetch_title "$ID") | |
COMPUTED_NAME="${COMPUTED_NAME}.gif" | |
fi | |
if [[ "$OUTPUT" ]]; then | |
# must be passed as last argument | |
if [[ -d "$OUTPUT" ]] && [[ "$COMPUTED_NAME" ]]; then | |
OUTPUT="${OUTPUT}/${COMPUTED_NAME}" | |
fi | |
else | |
OUTPUT="$COMPUTED_NAME" | |
fi | |
cmd=(curl -L --output "$OUTPUT" "$GIF_URL") | |
if [[ -e "$OUTPUT" ]] && [[ -z "$OVERWRITE" ]]; then | |
echo "$OUTPUT exists and -f|--force not set. Exiting" | |
exit 1 | |
fi | |
echo "Destination URL: $URL | Output: ${OUTPUT}" | |
#echo "${cmd[@]}" | |
"${cmd[@]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment