Date Modified Tags bash / python / shell

Bash hates floats

So I was writing some code the other day and wanted to wait for a small fraction of a second in a bash script. I also happened to be listening to Magic Sword at the time. That's not important to this story but I am trying to paint a picture here!

One thing I always forget about bash and shell scripts is that they do not support floating point numbers!

On many systems the sleep command actually supports floats. For example...

sleep .1

...will work on most linux distros.

And you can use $RANDOM combined with modular division to get a random integer value between a certain range:

sleep $[ ( $RANDOM % 10 )  + 1 ]s

What though if you want to wait a random fraction of a second?

You can't do something like this in bash because it doesn't support floats.

For example you can't simply scale your random integer to a fractional by multiplying it by a float because bash will interpret the .01 as string:

# INVALID
sleep $[ (( $RANDOM % 10 )  + 1) * .01 ]s
> syntax error: operand expected (error token is ".01 ")

Python to the rescue

What we can do though is use Python in our bash script to generate our random number for us, return it as a string, and then we can pass it into the sleep function!

sleep $(python -c "import random;print random.uniform(.01, .8)")

This works because the Python executable has a -c flag which allows you to pass in a string for python to interpret.

If the semicolon in the above python snippet confuses you, note that Python does allow you to insert multiple statements on one line by breaking them up by semicolons. It's one of those features that people really don't like to talk about though. One of the dirty secrets of Python, really.


Comments

comments powered by Disqus