Skip to content

Instantly share code, notes, and snippets.

@david50407
Last active March 9, 2020 06:24
Show Gist options
  • Save david50407/3a7e4239a8b409857ead8a6d9c0e036d to your computer and use it in GitHub Desktop.
Save david50407/3a7e4239a8b409857ead8a6d9c0e036d to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -euo pipefail
PATH=/bin:/sbin
http-request() {
local domain=$1; shift
local path=${1:-/}; shift
local verb=GET
(
exec 5<>/dev/tcp/$domain/80
cat <<-EOF >&5
$verb $path HTTP/1.1
User-Agent: bash
Host: $domain
Accept: text/html
Connection: close
EOF
cat <&5
)
}
query-fib() {
local nth=${1:-0}; shift
# <li><h4>Binary Base 2:</h4><div>0</div></li>
# <li><h4>Hexadecimal Radix 16:</h4><div>0</div></li>
http-request "www.protocol5.com" "/Fibonacci/$nth.htm" \
| egrep '<li><h4>[^<]+(Base|Radix) ([[:digit:]]+):</h4><div>([^<]+)</div></li>' \
| sed -e 's,<[^>]\+>,,g' -e 's,[^[:digit:]]\+\([[:digit:]]\+\):\(.\+\),\1 \2,g'
}
usage() {
cat <<-EOF
Usage: $0 [-b base] n-th
Print n-th fibonacci number in specific base
-b base : Specific base number, supportted 2,3,5,6,8,10,16,36 (default: 10)
EOF
}
main() {
local base=10
while getopts "b:h" opt; do
case $opt in
b)
case $OPTARG in
2|3|5|6|8|10|16|36)
base=$OPTARG
;;
*)
echo "$0: illegal base number -- $OPTARG"
usage
exit 1
;;
esac
;;
h)
usage
exit 0
;;
*)
usage
exit 1
;;
esac
done
shift $(($OPTIND - 1))
if [[ $# -ne 1 ]]; then
usage
exit 1
fi
local nth=$1; shift
local table=$(query-fib $nth)
if [[ -z "$table" ]]; then
echo "Cannot pull fibonacci result from internet"
exit 2
fi
while read -r tbase tval; do
[[ $tbase = $base ]] && echo $tval
done < <(echo -n "$table")
}
main $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment