** Injection-safe floating point math in bash/shell **
Note: The focus of this answer is provide ideas for injection-safe solution to performing math in bash (or other shells). Of course, same can be used, with minor adjustment to perform advanced string processing, etc.
Most of the solution that were by presented, construct small scriptlet on the fly, using external data (variables, files, command line, environment variables). The external input can be used to inject malicious code into the engine, many of them
Below is a comparison on using the various language to perform basic math calculation, where the result in floating point. It calculates A + B * 0.1 (as floating point).
All solution attempt avoid creating dynamic scriptlets, which are extremely hard to maintain, Instead they use static program, and pass parameters into designated variable. They will safely handle parameters with special characters - reducing the possibility of code injection. The exception is 'BC' which does not provide input/output facility
The exception is 'bc', which does not provide any input/output, all the data comes via programs in stdin, and all output goes to stdout. All calculation are executing in a sandbox, which does not allow side effect (opening files, etc.). In theory, injection safe by design!
A=5.2
B=4.3
# Awk: Map variable into awk
# Exit 0 (or just exit) for success, non-zero for error.
#
awk -v A="$A" -v B="$B" 'BEGIN { print A + B * 0.1 ; exit 0}'
# Perl
perl -e '($A,$B) = @ARGV ; print $A + $B * 0.1' "$A" "$B"
# Python 2
python -c 'import sys ; a = float(sys.argv[1]) ; b = float(sys.argv[2]) ; print a+b*0.1' "$A" "$B"
# Python 3
python3 -c 'import sys ; a = float(sys.argv[1]) ; b = float(sys.argv[2]) ; print(a+b*0.1)' "$A" "$B"
# BC
bc <<< "scale=1 ; $A + $B * 0.1"