Updates

Math in the Shell

I recently had to update a script that ran in bash that was failing. It was due to the lack of “bc” on the system (the script runs in recovery mode on the Mac). I was using bc to do some math to calculate a percentage of a number like this:

new_percent=`echo "scale=0;$partition_size * $convert_percent "|bc -l`

While this might be clever, it is dependent on “bc”. It turns out there is a much easier way to do this right in the Bash or the Bourne shell:

new_percent=$(( convert_percent*partition_size /100 ))

Much more straight forward and doesn’t have any external dependencies. It does integer operations so this gives a different result:

new_percent=$(( (convert_percent /100) * partition_size ))

It is also interesting on the syntax. To run an operation in the shell and return a result, you can do this:

result=$( pwd )

The result will contain the output of the current working directory. Very similar syntax and I’m sure somehow related.