I'm looking for a way to pass command line arguments to a bc script.
For example, take this simple bc script that outputs 10 digits of pi (rounded):
#!/bin/bc -lq
n_digits = 10;
scale = n_digits + 1;
/* calculation, replace later with a better algorithm */
result = 4 * a(1); /* arctan(1) = pi/4 */
/* rounding to n_digits */
t = 10^scale;
result *= t;
if (result < 0) result -= 50; /* unnecessary, but generally useful */
if (result > 0) result += 50; /* always true in this specific case */
scale -= 2;
result /= t;
print result, "\n";
quit;
In the script the variable n_digits
is hard coded to 10. I'd like to pass it a value from the command line. I could use the read()
function (n_digits = read();
) to pass it a number from the standard input like this:
$ ./pi <<< 20
3.1415926535897932385
But this requires trickery with redirection or piping and is not very user friendly. A command line argument would be much better.
The workaround I can think of is embedding the bc script into a bash script, like this, for example:
#!/bin/bash
bc -lq << EOF
n_digits = $1;
scale = n_digits + 1;
/* calculation, replace later with a better algorithm */
result = 4 * a(1); /* arctan(1) = pi/4 */
/* rounding to n_digits */
t = 10^scale;
result *= t;
if (result < 0) result -= 50; /* unnecessary, but generally useful */
if (result > 0) result += 50; /* always true in this specific case */
scale -= 2;
result /= t;
print result, "\n";
quit;
EOF
This works, but is bad aesthetic, and it feels unnecessary. Also, it looks like it could be used to inject arbitrary code, so it might be a good idea to implement checks in the bash script. Messy...
My question is: Is it possible to do it directly with a bc script? Is there some kind of an argv variable that I just can't find in documentation?
I'm using GNU bc, btw.