This is part of The Pile, a partial archive of some open source mailing lists and newsgroups.
Subject: Bash script From: Jeff Smelser <tradergt@smelser.org> Date: Thu, 27 Jan 2000 21:06:03 -0600 Just trying to write a bash script and can't seem to figure out how to do addition with variables. If someone could give me a quick example, I would appreciate it. Thanks === Subject: Re: Bash script From: Bret Hughes <bhughes@elevating.com> Date: Thu, 27 Jan 2000 22:13:20 -0600 Try some thing like this #! /bin/sh # addnums - adds two numbers input as args and outputs the result newval=`expr $1 + $2` echo 'the sum of ' $1 ' and ' $2 ' is ' $newval === Subject: Re: Bash script From: "Rick L. Mantooth" <ricklman@swbell.net> Date: Fri, 28 Jan 2000 00:42:09 -0600 (CST) You can also use bc #!/bin/sh var1=5 var2=6 echo "$var1 + $var2" | bc # end === Subject: Re: Bash script From: rpjday <rpjday@mindspring.com> Date: Fri, 28 Jan 2000 04:45:41 -0500 (EST) On Thu, 27 Jan 2000, Jeff Smelser wrote: > this worked great, thanks a lot! > > > On Thu, 27 Jan 2000, Bret Hughes wrote: > > > Try some thing like this > > #! /bin/sh > > # addnums - adds two numbers input as args and outputs the result > > newval=`expr $1 + $2` > > echo 'the sum of ' $1 ' and ' $2 ' is ' $newval the more efficient way with bash is with the $((...)) operator, which represents arithmetic built into the shell. $ echo $((1+2)) 3 the advantage to this approach is that you can be sloppy with spacing, and you have not just simple arithmetic, but bit shift operators. same feature with the korn shell. === Subject: Re: Bash script From: Steven W Orr <steveo@world.std.com> Date: Fri, 28 Jan 2000 09:00:39 -0500 =>On Thu, 27 Jan 2000, Bret Hughes wrote: => =>> Try some thing like this =>> =>> =>> #! /bin/sh =>> # addnums - adds two numbers input as args and outputs the result =>> newval=`expr $1 + $2` =>> echo 'the sum of ' $1 ' and ' $2 ' is ' $newval If no one minds, I'd just like to amplify on this a little. The solution below uses the primitive Bourne shell method which uses an external program (expr) to do the arithmetic. Bash has internal functionality to perform stuff like this. The hashpling at the beginning specifies which interpreter is to process the script. By specifying your script to use /bin/sh, you are explicitly *not* writing a bash script. The script below can be re-written using internal arithmetic functions: #! /bin/bash # addnums - adds two numbers input as args and outputs the result newval=$(($1+$2)) echo "the sum of $1 and $2 is $newval" ===