How can I do division with variables in a Linux shell? How can I do division with variables in a Linux shell? bash bash

How can I do division with variables in a Linux shell?


Those variables are shell variables. To expand them as parameters to another program (ie expr), you need to use the $ prefix:

expr $x / $y

The reason it complained is because it thought you were trying to operate on alphabetic characters (ie non-integer)

If you are using the Bash shell, you can achieve the same result using expression syntax:

echo $((x / y))

Or:

z=$((x / y))echo $z


I believe it was already mentioned in other threads:

calc(){ awk "BEGIN { print "$*" }"; }

then you can simply type :

calc 7.5/3.2  2.34375

In your case it will be:

x=20; y=3;calc $x/$y

or if you prefer, add this as a separate script and make it available in $PATH so you will always have it in your local shell:

#!/bin/bashcalc(){ awk "BEGIN { print $* }"; }


Why not use let; I find it much easier.Here's an example you may find useful:

start=`date +%s`# ... do something that takes a while ...sleep 71end=`date +%s`let deltatime=end-startlet hours=deltatime/3600let minutes=(deltatime/60)%60let seconds=deltatime%60printf "Time spent: %d:%02d:%02d\n" $hours $minutes $seconds

Another simple example - calculate number of days since 1970:

let days=$(date +%s)/86400