|
From: adamsalisbury at gmail dot com on 13 Feb 2006 19:33 Hi, I'm using variables at the moment in script with a mathematical purpose, or at least trying. Could anyone explain how to tell bourne that I want a variable to be numerical, rather than string? At the moment my variables which are supposed to hold totals are holding strings like '15+19'. Thanks very much, Adam
From: Chris F.A. Johnson on 14 Feb 2006 03:36 On 2006-02-14, adamsalisbury at gmail dot com wrote: > Hi, > I'm using variables at the moment in script with a mathematical > purpose, or at least trying. > Could anyone explain how to tell bourne that I want a variable to be > numerical, rather than string? > At the moment my variables which are supposed to hold totals are > holding strings like '15+19'. If you want a variable to contain a number, then you have to assign a number to it. If you want to do arithmetic, do the calculation before assigning it to a variable. I showed you how to do arithmetic in my response to your previous post. -- Chris F.A. Johnson, author | <http://cfaj.freeshell.org> Shell Scripting Recipes: | My code in this post, if any, A Problem-Solution Approach | is released under the 2005, Apress | GNU General Public Licence
From: Stephane CHAZELAS on 14 Feb 2006 03:37 2006-02-13, 16:33(-08), adamsalisbury at gmail dot com: > I'm using variables at the moment in script with a mathematical > purpose, or at least trying. > Could anyone explain how to tell bourne that I want a variable to be > numerical, rather than string? > At the moment my variables which are supposed to hold totals are > holding strings like '15+19'. [...] The Bourne shell is a shell, not a programming language. All it does is run commands, so there's no point having variables other than strings, as arguments to commands are strings. For instance, it may call the expr command, which expects as arguments string representations of numbers and arithmetic operators. arg0=expr arg1=15 arg2=+ arg3=19 "$arg0" "$arg1" "$arg2" "$arg3" is the same as expr 15 + 19 Expr will parse its 4 arguments, and find out that it is asked to do the addition of 15 and 19 and output the result as a string on its standard output followed by a newline character. The Bourne shell has a way to store the output of a command in another string variable. That is called command substitution: result=`expr "$arg1" "$arg2" "$arg3"` The `...` will automatically remove the trailing newline character added by expr (actually, it will remove every trailing newline character, which is a bug/feature of every shell). -- St?phane
|
Pages: 1 Prev: script to send automatic email Next: One last command after "exit 1"? |