[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] something about bc
From: |
lina |
Subject: |
Re: [Help-bash] something about bc |
Date: |
Thu, 29 Dec 2011 01:44:07 +0800 |
On 29 Dec, 2011, at 0:18, Greg Wooledge <address@hidden> wrote:
> On Wed, Dec 28, 2011 at 09:56:00AM -0600, address@hidden wrote:
>> On Wed, 28 Dec 2011, lina wrote:
>>> some wrong try:
>>>
>>> $ a=1.5 ; a+=1 ; echo $a
>>> 1.51
>
> You are doing string concatenation here. The two strings "1.5" and "1"
> are concatenated to make "1.51".
>
>>> $ a=1.5 ; a+=1 | bc; echo $a
>>> 1.5
>
> Here, you ran three separate commands:
>
> a=1.5 # variable assignment
> a+=1 | bc # variable assignment piped to bc
> echo $a # expand a variable, perform word splitting and globbing, write
>
> Since the second variable assignment does not write anything to standard
> output, the pipe to bc has no input, and therefore bc does nothing.
>
> Since the second variable assignment was performed inside a pipeline, it
> takes place in a subshell (child process), and no change to the variable
> takes place in the main shell.
>
>>> $ a=1.5 ; let "a+=1" | bc; echo $a
>>> bash: let: 1.5: syntax error: invalid arithmetic operator (error token is
>>> ".5")
>>> 1.5
>
> Bash cannot perform floating-point arithmetic. It only has integer
> arithmetic.
>
> imadev:~$ let a=1.5+1
> bash: let: a=1.5+1: syntax error: invalid arithmetic operator (error token is
> ".5+1")
>
> If you want to perform floating-point math, you have to use bc *instead of*
> let, not *in addition to* let.
>
>> echo "a=1.5; a+=1; print a;" | bc
>
> This must be GNU bc. It doesn't work with standard bc:
>
> imadev:~$ echo "a=1.5; a+=1; print a;" | bc
> syntax error on line 1,
>
> Here is how it works with standard bc:
>
> imadev:~$ echo "a=1.5; a=a+1; a" | bc
> 2.5
>
> Or more simply:
>
> imadev:~$ echo "1.5+1" | bc
> 2.5
>
> And, taking a wild-ass guess, here is what I think lina wanted to do:
>
> imadev:~$ a=1.5
> imadev:~$ a=$(echo "$a + 1" | bc)
> imadev:~$ echo "$a"
> 2.5
>
Cool. Thanks for both of you. I should try more times.
Best wishes,