rossoreed
Posts: 35
Joined: Mon Dec 30, 2013 9:48 am

Rounding in a bash script

Sun Jan 24, 2016 4:59 pm

I'm writing a bash script which provides data about the SD card, and I've run into this issue. (sorry if it's a basic mistake)

If I run;

Code: Select all

$sudo blockdev --getsz /dev/mmcblk0
I get the correct answer - 15130624

But if I combine it with some calculations;

Code: Select all

DISK_SIZE="$(($(sudo blockdev --getsz /dev/mmcblk0)/2048/925))"
I get 7, instead of 7.987027027027

User avatar
allfox
Posts: 452
Joined: Sat Jun 22, 2013 1:36 pm
Location: Guang Dong, China

Re: Rounding in a bash script

Sun Jan 24, 2016 5:04 pm

I think you need a calculator program to help.

Get "calc" command from the apcalc package: sudo apt install apcalc

Code: Select all

#! /bin/bash

CALC="/usr/bin/calc -p"

echo `$CALC "1 / 4"`

exit 0

User avatar
Paeryn
Posts: 2966
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Rounding in a bash script

Sun Jan 24, 2016 9:59 pm

Bash only deals with integer numbers. As allfox said, you need to use other programs if you want floating point numbers.
She who travels light — forgot something.

User avatar
PeterO
Posts: 5880
Joined: Sun Jul 22, 2012 4:14 pm

Re: Rounding in a bash script

Sun Jan 24, 2016 10:17 pm

This should be in your book marks list http://www.tldp.org/LDP/abs/html/index.html
abs = Advanced Bash-Scripting Guide

For maths see http://www.tldp.org/LDP/abs/html/arithexp.html

PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

rossoreed
Posts: 35
Joined: Mon Dec 30, 2013 9:48 am

Re: Rounding in a bash script

Sun Jan 24, 2016 10:26 pm

OK thanks, I'll look at plan B!

Paul

Return to “General discussion”