Interview Prep/Shell Scripting/Text processing: grep, sed, awk, cut, sort, uniq

How do you do floating-point math in shell scripts?

IntermediateConceptText processing: grep, sed, awk, cut, sort, uniq
Answer

Bash only does integers. Use awk (always available) or bc.

ratio=$(awk -v e="$errors" -v t="$total" 'BEGIN {printf "%.2f", (t ? 100*e/t : 0)}')
echo "scale=3; 10/3" | bc               # 3.333
if awk -v r="$ratio" 'BEGIN {exit !(r > 5.0)}'; then alert "error rate ${ratio}%"; fi

The last line shows the trick for float comparisons: awk exits 0 when the condition is true.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Text processing: grep, sed, awk, cut, sort, uniq