Sunday, April 17, 2016

Recursive Factorial in bc!

alias factorial='_() { var=${1}; echo -en "scale=25;\ndefine f (x) {if (x <= 1) return (1);\nreturn (f(x-1) * x);}\nf(${var})\nquit" | bc;};_' 
Logic found on the bc man page. Note the newlines, bc is a bit finicky about newlines when dealing with functions on one-liners otherwise.

Tuesday, April 5, 2016

Printing key-value pairs from Bash Associative array

#!/bin/bash 

 ## Printing key-value pairs from a Bash associative array 
unset myarr && declare -A myarr 
let myarr["eightytwo"]+=8
let myarr["eightytwo"]+=74
myarr["thirteen"]+=1
myarr["thirteen"]+=3
let myarr["fiftythree"]+=48
let myarr["fiftythree"]+=5
for a in "${!myarr[@]}"; do echo "${a}: ${myarr["$a"]}"; done