Skip to content

Instantly share code, notes, and snippets.

@herd-the-cats
Last active September 7, 2020 23:06
Show Gist options
  • Select an option

  • Save herd-the-cats/6db11a190f694f94f4533d2ce8efe481 to your computer and use it in GitHub Desktop.

Select an option

Save herd-the-cats/6db11a190f694f94f4533d2ce8efe481 to your computer and use it in GitHub Desktop.
Bash function creates a persistent subshell of bc to stream multiple arithmetic operations
# credit to https://github.com/F-Hauri/Connector-bash for the idea
function bcpipe() {
command -v bc 1>/dev/null 2>&1 || { printf "No bc binary.\n" 1>&2 ; return 1 ;}
[[ $# -lt 1 ]] && { printf "Usage: %s [BCSTART|BCSTOP] || \033[3mbc-compatible arithmetic arguments\033[0m\n" "${FUNCNAME[0]}" ; return 1 ;}
if [[ $1 == "BCSTART" ]] ; then
local tmpd
local tmpfifo
tmpd="$(mktemp -d)"
tmpfifo="$(mktemp -u -p "$tmpd")"
mkfifo -m 0600 "$tmpfifo"
exec {BC_W}> >(exec bc -l >"$tmpfifo")
exec {BC_R}< "$tmpfifo"
rm "$tmpfifo"
rmdir "$tmpd" 1>/dev/null 2>&1 || true
export BC_W
export BC_R
return 0
fi
if [[ $1 == "BCSTOP" ]] ; then
exec {BC_R}<&-
exec {BC_W}<&-
unset BC_W
unset BC_R
return 0
fi
local result
if [[ -v BC_R && -v BC_W ]] ; then
printf "%s\n" "$@" 1>&${BC_W}
read -u ${BC_R} result
printf "%s" "$result"
return 0
else
result="$(printf "%s\n" "$@" | bc -l)"
printf "%s" "$result"
return 0
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment