Last active
June 5, 2022 21:44
-
-
Save neechbear/c4c4069ad09a405376eea513095595c5 to your computer and use it in GitHub Desktop.
Playing around with a pure-ish bash IMDB-ish client for fun
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 -Eeuo pipefail | |
trap 'declare rc=$?; | |
>&2 echo "Unexpected error executing $BASH_COMMAND at ${BASH_SOURCE[0]} line $LINENO"; | |
exit $rc' ERR | |
join () { | |
local IFS="$1"; shift | |
echo "$*" | |
} | |
omdbapi () { | |
declare host="$1"; shift | |
declare query="$(join "&" "$@")" | |
declare data="" body="" | |
data="$(get_url "$host" "$query")" | |
while read -r out ; do | |
out="${out%%$'\r'}" | |
if [[ ! $body && -z "$out" ]] ; then | |
body=true | |
elif [[ $body ]] ; then | |
echo "$out" | |
fi | |
done < <(echo "$data") | { | |
declare rc=${PIPESTATUS[0]} | |
if type -P jq >/dev/null ; then | |
jq . | |
else | |
cat | |
fi | |
return $rc | |
} | |
} | |
get_url () { | |
declare host="$1" query="$2" | |
exec 3<>"/dev/tcp/$host/80" | |
printf "GET /?%s HTTP/1.1\r\nhost: %s\r\nConnection: close\r\n\r\n" \ | |
"$query" "$host" >&3 | |
cat <&3 | |
} | |
main () { | |
declare -r api_host="www.omdbapi.com" | |
declare api_key="${OMDB_APIKEY:-$(cat ~/.omdb.apikey 2>/dev/null||:)}" | |
if [[ -z "$api_key" ]] ; then | |
>&2 echo "Missing OMDB_APIKEY environment variable or ~/.omdb.apikey file; exiting!" | |
exit 1 | |
fi | |
if [[ $# -lt 1 ]] ; then | |
>&2 echo "Syntax: ${BASH_SOURCE[0]##*/} <movie title>" | |
exit 64 | |
fi | |
omdbapi "$api_host" "apikey=$api_key" "plot=full" "t=$*" | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment