LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to display remainder in Bash script (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-display-remainder-in-bash-script-603629/)

packets 11-30-2007 07:41 PM

How to display remainder in Bash script
 
I'm trying to create a script that will convert b/s to kb/s. To convert to kb/s, I must divide it to 1000 b/s. However, the answer does not contain the remainder. When I do "expr 5 / 3", it shows only 1 (suppose to be 1.6). Doesn't show the remainder .6.

I search in Google and it says the "%" is remainder of a division. But when I do expr 5 % 3, it shows "2". It suppose to be 6, am I right?


Any inputs,

jschiwal 11-30-2007 07:51 PM

Bash variables are integers only. You could use bc to display it.

meters=14034
echo "scale=2; $meters / 1000" | bc

However, a script that needs to handle floating point numbers probably should be written using another language.

The expression "5 % 3" will give you 1 Remainder 3. The "%" operator is the mod operator.

packets 11-30-2007 08:47 PM

When I'm doing this, it has an error

meters=14034
date=`date +%F\ %k:%M`
echo "scale=2; $date $meters / 1000" | bc

Can I put a command before $metes?

jschiwal 11-30-2007 09:14 PM

The date command doesn't belong there. You want to echo "bc" expressions into the command.

You could separate the two if you wanted the date displayed as well.

Code:

meters=14034
date
echo "scale=2; $meters / 1000" | bc


packets 11-30-2007 10:36 PM

Is there a way I can put a variable next to the echo with bc?

Quote:

echo "scale=2; $meters / 1000" | bc

I need to attached a numbers to the output. When I do 'echo -n "scale=2; $meters / 1000" | bc'
it says: (standard_in) 1: parse error

jschiwal 12-01-2007 01:03 AM

The echo is not do display something to the screen. It is to send a line to "bc" that the bc shell understands. You could do something similar as you did before but use the -n option to suppress a newline at the end of the echo:
meters=14034
date=`date +%F\ %k:%M`
echo -n "$date "
echo "scale=2; $meters / 1000" | bc

4c00h 12-01-2007 01:30 AM

Should be 1024 instead of 1000 if you want exact results


All times are GMT -5. The time now is 06:46 AM.