Looping a python command from bash, cannot use floats as parameter for command
I am trying to loop a python command in my bash terminal to take many float values for a certain parameter.
This is what I have so far:
for ((t=0; t <= 165; t=t+5)); do python3 filename 1 [echo $t/100] 0; done
I want to loop over values between 0 and 1.65, on .05 increments. Only bash doesn’t seem to accept float values like that, and the echo command is not being recognized by python. I have gotten errors like "cannot convert [echo to a float", or that ( is not correct syntax if I replace the square brackets.
What can I do to fix this? the ideal situation would be for my script to run:
python3 filename 1 0.00 0 python3 filename 1 0.05 0 . . . python3 filename 1 1.65 0
each after the other without them running simultaneously.
Thanks!
With bash version 4.0+, you can use a brace expansion and string manipulation to formulate that float number:
for n in {000..165..5}; do echo python3 filename 1 "${n%??}.${n#?}" 0 done
${n%??}
removes 2 chars from the end of the string,
${n#?}
removes 1 char from the start of the string.
The easiest without a lot of fuzz is to make use of the sequence command seq
. This command allows you to make a sequence of numbers with any increment:
seq FIRST INCREMENT LAST
In the case of the OP, there is a request to generate the numbers 0.00 0.05 0.10 … 1.65, so all that needs to be done is
for x in $(seq 0 0.05 1.65); do python3 filename 1 "$x" 0 done
Performing the loop within bc
, Formatting number with bash, Calling the script with xargs
:
LC_NUMERIC=C printf '%0.2f\n' \ $(<<<'scale=2;i=0;while(i<=1.65){i;i+=.05}' bc) | xargs -l -I{} python3 filename 1 {} 0
bash
doesn’t do floating-point arithmetic. Use an external command like bc
.
for ((t=0; t <= 165; t=t+5)); do python3 filename 1 "$(echo "scale=2; $t / 100" | bc)" 0 done
Do the division in the python script and just pass whole numbers instead.