Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using decimals in shell scripts

Status
Not open for further replies.

boebox

MIS
Oct 30, 2000
70
CA
Does anyone know how to use decimal numbers in a shell script?

expr only accepts integers!

Thanks
Tony
 

Hi, boebox!

You can use decimal numbers in a awk and perl scripts, as I know. Sorry, maybe you also know this.

You can post your programming problem.

KP.
 
In what context are you using them? ... shell scripts don't really have any concept of data types, but you could use awk/nawk along with the printf function which handles this sort of thing easily.

Could you post an example of what you're trying to do?

Greg.
 
#!/bin/sh

var1=0
i=0

for ;;
do
var2=`mycommand | awk '{ print $4 }' => decimal number (6.7)
var1=$var2 + $var1
i=$i+1
done

var3=var2 / $i
 
I just ran into this problem myself
and was able to solve it using bc.
Below, look for the text scale=2.
That sets the results to 2 decimal postions.

Robert

#/usr/local/bin
# disk_space
# usage: disk_space [/path]
# works much like the command du
# but oputs in k,kb,mb and gb

################################################################################
# Variables
################################################################################
TMP_LIST=/tmp/TMP_LIST.disk_space.$$ # generic tmp file for data

################################################################################
# Functions
################################################################################
Disk_Usage ()
{
KB_TOTAL=`du -sk $DIR|awk '{print $1}'`
}

################################################################################
# Main
################################################################################

DIR=$1
Disk_Usage

echo "scale=2" >> $TMP_LIST.kb
echo "${KB_TOTAL}*1000" >> $TMP_LIST.kb
echo "quit" >> $TMP_LIST.kb
K_TOTAL=`bc $TMP_LIST.kb`

echo "scale=2" >> $TMP_LIST.mb
echo "${KB_TOTAL}/1000" >> $TMP_LIST.mb
echo "quit" >> $TMP_LIST.mb
MB_TOTAL=`bc $TMP_LIST.mb`

echo "scale=2" >> $TMP_LIST.gb
echo "${KB_TOTAL}/1000000" >> $TMP_LIST.gb
echo "quit" >> $TMP_LIST.gb
GB_TOTAL=`bc $TMP_LIST.gb`

echo
echo " K TOTAL: $K_TOTAL"
echo "KB TOTAL: $KB_TOTAL"
echo "MB TOTAL: $MB_TOTAL"
echo "GB TOTAL: $GB_TOTAL"
echo

################################################################################
# End
################################################################################

test run...
# ./disk_space /var

K TOTAL: 769390000
KB TOTAL: 769390
MB TOTAL: 769.39
GB TOTAL: .76

Robert G. Jordan

Robert@JORDAN2000.com
Unix Admin, United Airlines
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top