[HPADM] RE: Getting an absolute value

From: Jeff Lightner (jlightner@water.com)
Date: Thu Oct 12 2006 - 11:25:41 EDT


Found a link that gave a function for this. It had some other lines
that didn't make any sense and didn't actually call the function. I've
deleted the lines and added a final to call the function:

#!/bin/ksh
#
# Function to evaluate the absolute value of a number
abs () {
# Check for numeric input
if expr $1 + 0 2>/dev/null 1>&2 ; then
# Is the number negative?
if [ $1 -lt 0 ] ; then
echo `expr 0 - $1`
else
echo $1
fi
return 0 # OK
else
return 1 # Not a number
fi
}

abs $1

You could just insert the function within a script then call the "abs"
line with whatever input you wanted at the point you were ready which is
presumably why he posted it as a function rather than a wholly contained
script. The above however is stand alone because it calls the function
after it defines it. You wouldn't really need it to be a function for
this.

The link is
http://forums.devshed.com/unix-help-35/absolute-value-fuction-in-unix-26
7780.html

It mentions other ways to do it with awk or bc.

-----Original Message-----
From: hpux-admin-owner@DutchWorks.nl
[mailto:hpux-admin-owner@DutchWorks.nl] On Behalf Of Shaw, Marco
Sent: Thursday, October 12, 2006 10:38 AM
To: hpux-admin@DutchWorks.nl
Subject: [HPADM] Getting an absolute value

Can't believe google doesn't provide an answer, searched these archives
also!

#a=`expr 2 - 1`
#echo $a
1
#a=`expr 2 - 3`
#echo $a
-1

I want to get the absolute value of the difference. I don't have to use
expr, but
also would prefer something available directly with the Borne shell.

Marco

--
             ---> Please post QUESTIONS and SUMMARIES only!! <---
        To subscribe/unsubscribe to this list, contact
majordomo@dutchworks.nl
       Name: hpux-admin@dutchworks.nl     Owner:
owner-hpux-admin@dutchworks.nl
 
 Archives:  ftp.dutchworks.nl:/pub/digests/hpux-admin       (FTP, browse
only)
            http://www.dutchworks.nl/htbin/hpsysadmin   (Web, browse &
search)
--
             ---> Please post QUESTIONS and SUMMARIES only!! <---
        To subscribe/unsubscribe to this list, contact majordomo@dutchworks.nl
       Name: hpux-admin@dutchworks.nl     Owner: owner-hpux-admin@dutchworks.nl
 
 Archives:  ftp.dutchworks.nl:/pub/digests/hpux-admin       (FTP, browse only)
            http://www.dutchworks.nl/htbin/hpsysadmin   (Web, browse & search)


This archive was generated by hypermail 2.1.7 : Sat Apr 12 2008 - 11:02:54 EDT