Bash Floating point math with bc

Hello Everyone,

I am currently working on a script to calculate optimal tcp window size

the formula that I am following is

2 x (bandwith speed /8 * Round Trip Time ) = x

This is what I have so far

#!/bin/bash
echo "Enter connection speed" << Get the speed of the Connection from user
read SPEED
echo "enter ip for far end device" << Enter a ip to ping to get Round trip time
read IP
echo "determine RTT"
RTT=$(ping -c 1 $IP  |grep rtt | cut -d"/" -f5 ) |bc

echo ((2 * $SPEED / 8 * $RTT ))

This is what I get

Enter connection speed
10
enter ip for far end device
192.168.1.1
determine RTT
./opt-tcpwin.sh: line 12: syntax error near unexpected token `('
./opt-tcpwin.sh: line 12: `echo ((2 * $SPEED / 8 * $RTT ))'|bc

Any help or guidance would be great

thank you all

First off, you should use code tags

Never comment lines like this
echo "Enter connection speed" << Get the speed of the Connection from user
Use hash # like this
echo "Enter connection speed" # Get the speed of the Connection from user

RTT=$(ping -c 1 $IP |grep rtt | cut -d"/" -f5 ) |bc
What are you trying to do with bc here? This does not give any output to bc to work with, remove it.
RTT=$(ping -c 1 $IP |grep rtt | cut -d"/" -f5 )

echo ((2 * $SPEED / 8 * $RTT ))
Here you miss the $ to do the math
echo $((2 * $SPEED / 8 * $RTT ))
Not sure why it still does not work so I have change it to awk

Do also use parantheses to make sure you have the math correctly

echo $(( (3*8)/(2*4) ))
3

compare to

echo $(( 3*8/2*4 ))
48
#!/bin/bash
echo "Enter connection speed" # Get the speed of the Connection from user
read SPEED
echo "enter ip for far end device" # Enter a ip to ping to get Round trip time
read IP
echo "determine RTT"
RTT=$(ping -c 1 $IP | awk -F/ 'END {print $5}')
awk -v s=$SPEED -v r=$RTT 'BEGIN {print (2*s)/(8*r)}'

Hi.

This is script s1:

#!/usr/bin/env bash

set -x
SPEED=50000
IP=8.8.8.8
s1="scale=0"
s2=$(ping -c 1 $IP  |grep rtt | cut -d'/' -f5 )
printf -v RTT "%.0f\n" $(ping -c 1 $IP  |grep rtt | cut -d'/' -f5  )

# echo ((2 * $SPEED / 8 * $RTT ))
echo $(( (2 * $SPEED) / (8 * $RTT) ))

echo or:

echo "$s1;(2*$SPEED)/(8*$s2)" | bc

when run, produces:

% ./s1
+ SPEED=50000
+ IP=8.8.8.8
+ s1=scale=0
++ ping -c 1 8.8.8.8
++ grep rtt
++ cut -d/ -f5
+ s2=48.061
++ ping -c 1 8.8.8.8
++ grep rtt
++ cut -d/ -f5
+ printf -v RTT '%.0f\n' 47.815
+ echo 260
260
+ echo or:
or:
+ echo 'scale=0;(2*50000)/(8*48.061)'
+ bc
260

Adjust parentheses as necessary. See man pages for details.

Best wshes ... cheers, drl

Thank you both for your input

I will let you know how it goes

BMF