Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > linux.debian.user > #178441 > unrolled thread

Recomended tutoial(s) on doing arithmetic in Bash scripts

Started byRichard Owlett <rowlett@cloud85.net>
First post2017-03-05 16:50 +0100
Last post2017-03-05 23:10 +0100
Articles 20 on this page of 21 — 8 participants

Back to article view | Back to linux.debian.user


Contents

  Recomended tutoial(s) on doing arithmetic in Bash scripts Richard Owlett <rowlett@cloud85.net> - 2017-03-05 16:50 +0100
    Re: Recomended tutoial(s) on doing arithmetic in Bash scripts Reco <recoverym4n@gmail.com> - 2017-03-05 17:30 +0100
    Re: Recomended tutoial(s) on doing arithmetic in Bash scripts <tomas@tuxteam.de> - 2017-03-05 17:30 +0100
      Re: Recomended tutoial(s) on doing arithmetic in Bash scripts GiaThnYgeia <GiaThnYgeia@openmailbox.org> - 2017-03-05 19:20 +0100
        Re: Recomended tutoial(s) on doing arithmetic in Bash scripts <tomas@tuxteam.de> - 2017-03-05 21:40 +0100
        Re: Recomended tutoial(s) on doing arithmetic in Bash scripts Greg Wooledge <wooledg@eeg.ccf.org> - 2017-03-06 14:40 +0100
          Re: Recomended tutoial(s) on doing arithmetic in Bash scripts <tomas@tuxteam.de> - 2017-03-06 15:00 +0100
          Re: Recomended tutoial(s) on doing arithmetic in Bash scripts Jörg-Volker Peetz <jvpeetz@web.de> - 2017-03-06 16:00 +0100
            Re: Recomended tutoial(s) on doing arithmetic in Bash scripts <tomas@tuxteam.de> - 2017-03-06 16:40 +0100
      Re: Recomended tutoial(s) on doing arithmetic in Bash scripts Richard Owlett <rowlett@cloud85.net> - 2017-03-05 19:20 +0100
        Re: Recomended tutoial(s) on doing arithmetic in Bash scripts Richard Owlett <rowlett@cloud85.net> - 2017-03-05 19:50 +0100
        Re: Recomended tutoial(s) on doing arithmetic in Bash scripts <tomas@tuxteam.de> - 2017-03-05 21:30 +0100
          Re: Recomended tutoial(s) on doing arithmetic in Bash scripts Richard Owlett <rowlett@cloud85.net> - 2017-03-05 22:00 +0100
      Re: Recomended tutoial(s) on doing arithmetic in Bash scripts Jude DaShiell <jdashiel@panix.com> - 2017-03-05 23:20 +0100
        Re: Recomended tutoial(s) on doing arithmetic in Bash scripts Richard Owlett <rowlett@cloud85.net> - 2017-03-06 12:20 +0100
          Re: Recomended tutoial(s) on doing arithmetic in Bash scripts <tomas@tuxteam.de> - 2017-03-06 12:40 +0100
    Re: Recomended tutoial(s) on doing arithmetic in Bash scripts David Christensen <dpchrist@holgerdanske.com> - 2017-03-05 20:50 +0100
      Re: Recomended tutoial(s) on doing arithmetic in Bash scripts Richard Owlett <rowlett@cloud85.net> - 2017-03-05 21:50 +0100
        Re: Recomended tutoial(s) on doing arithmetic in Bash scripts David Christensen <dpchrist@holgerdanske.com> - 2017-03-06 04:40 +0100
      Re: Recomended tutoial(s) on doing arithmetic in Bash scripts <tomas@tuxteam.de> - 2017-03-05 22:30 +0100
    Re: Recomended tutoial(s) on doing arithmetic in Bash scripts Jude DaShiell <jdashiel@panix.com> - 2017-03-05 23:10 +0100

Page 1 of 2  [1] 2  Next page →


#178441 — Recomended tutoial(s) on doing arithmetic in Bash scripts

FromRichard Owlett <rowlett@cloud85.net>
Date2017-03-05 16:50 +0100
SubjectRecomended tutoial(s) on doing arithmetic in Bash scripts
Message-ID<thGA1-2jU-5@gated-at.bofh.it>
I'm interested in "expr" and "bc".
The man pages lack reasonable examples.
The tutorial/HOWTO pages confuse the issue with fancy page layouts 
and/or code samples showing how impressive the author can make the 
script's output.

Suggestions please.
TIA

[toc] | [next] | [standalone]


#178442

FromReco <recoverym4n@gmail.com>
Date2017-03-05 17:30 +0100
Message-ID<thHcJ-2Sl-1@gated-at.bofh.it>
In reply to#178441
	Hi.

On Sun, 5 Mar 2017 09:42:16 -0600
Richard Owlett <rowlett@cloud85.net> wrote:

> I'm interested in "expr" and "bc".
> The man pages lack reasonable examples.
> The tutorial/HOWTO pages confuse the issue with fancy page layouts 
> and/or code samples showing how impressive the author can make the 
> script's output.

expr 2 + 2

echo 2 + 2 | bc

and, since you mentioned bash - you don't need anything but bash to do
basic operations:

echo $((2 + 2))

Reco

[toc] | [prev] | [next] | [standalone]


#178443

From<tomas@tuxteam.de>
Date2017-03-05 17:30 +0100
Message-ID<thHcJ-2Sl-3@gated-at.bofh.it>
In reply to#178441
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Sun, Mar 05, 2017 at 09:42:16AM -0600, Richard Owlett wrote:
> I'm interested in "expr" and "bc".
> The man pages lack reasonable examples.
> The tutorial/HOWTO pages confuse the issue with fancy page layouts
> and/or code samples showing how impressive the author can make the
> script's output.

Hm. Neither expr nor bc are bash, they are "external" binaries. If you
want to do arithmetic in bash, there's $((...)):

  tomas@rasputin:~$ echo $(( (3+4)/3 ))
  2

As you see, this does integer arithmetic. There's not much to it, the
usuall stuff (more or less known from C, like pre/post increment, negation,
bitwise and/or/xor... see the section "ARITHMETIC EVALUATION" in the
bash manual.

Expr and bc can do more -- but you've to take into account that they
are external programs and thus give their response on stdout: you
have to "catch" it somehow to make use of it. The `...` or the more
modern and highly recommended $(...) come in:

  tomas@rasputin:~$ foo=$(expr 3 + 4)
  tomas@rasputin:~$ echo $foo
  7

Note that expr can also only do integers. I don't know whether expr
brings anything to the table beyond portability. If you stick to bash
(or dash, or...) it seems better to keep to the builtin $((...))

If you need floating point numbers, bc (or dc) are your next stops.

Perhaps you start with a couple of small examples on what you want
to achieve, post them here and we take them as riddles :-)

Here's a little example with dc, to get your appetite going. As you
might know, I'm a Luddite and have no desktop environment. As a laptop
user, I'm still interested on my battery's status: my laptop just
quits pretty abruptly when empty, putting the excellent ext4 file
system to test. For that, I've a small xterm which displays the
battery fill status (which I want as a fraction of 1, to five
significant digits, so I can see it's moving). The repeating is
done outside the program, with "watch" -- invoked from my WM.

Here's the shell snippet. The dc magic (dividing the battery's
current status, called NOW, by the FULL status) is done at
the last line:

  #!/bin/bash
  # Notes:
  # for colors:
  # tput setaf 1 ; tput bold ; echo -n 123 ; tput setaf 7 ; tput sgr0 ; echo 456
  # cf tput(1) terminfo(5)
  # do continuous mode with watch -c, possibly t

  BAT='/sys/class/power_supply/BAT0'
  AC='/sys/class/power_supply/ADP1'
  FULL=$(cat $BAT/energy_full)
  NOW=$(cat $BAT/energy_now)
  case $(cat $AC/online) in
    0) online="BAT" ;;
    1) online="AC " ;;
    *) online="???" ;;
  esac
  echo -ne "$online " ; dc -e "5k $NOW $FULL / p"

The $online variable tells me whether I'm on AC or BATtery, for the dc line it's
"5k" to set the five significant digits, then $NOW $FULL and the division "/"
(note that dc is a stack calculator [1]), note that the expansion of $NOW, etc.
is done by the shell.

If you wanted to catch the value instead of printing it right away, you would
do $fill=$(dc -e "5k $NOW $FULL / p")

With bc it'd be similar; I never wrapped my head around bc's syntax, since
dc has served me so well, but given enough motivation I don't think it's
too hard.

The script's comments hint at the next steps: COLORZ ;-)

Enjoy

[1] Like "Foot in yourself shoot.": look under Forth here:
    http://www.thealmightyguru.com/Humor/Docs/ShootYourselfInTheFoot.html

- -- tomás
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (GNU/Linux)

iEYEARECAAYFAli8PA0ACgkQBcgs9XrR2kYGPACfab6u+HPGQbzcvEnfoCAbwjjK
46cAnR9AlDZzX0GrEAtSHwRcmL+syaKE
=LElz
-----END PGP SIGNATURE-----

[toc] | [prev] | [next] | [standalone]


#178446

FromGiaThnYgeia <GiaThnYgeia@openmailbox.org>
Date2017-03-05 19:20 +0100
Message-ID<thIVb-49C-7@gated-at.bofh.it>
In reply to#178443
It is Sunday and I don't like Mondays
tell me why

tomas@tuxteam.de:
> Hm. Neither expr nor bc are bash, they are "external" binaries. If you
> want to do arithmetic in bash, there's $((...)):
> 
>   tomas@rasputin:~$ echo $(( (3+4)/3 ))
>   2

I see your 2 and raise you
nosuchagency@bottomofthesea:~$ echo $(((3000000000+4000000000)/3))
2333333333

Infinitely inaccurate digital systems

> -- tomás

kAt

-- 
 "The most violent element in society is ignorance" rEG

[toc] | [prev] | [next] | [standalone]


#178457

From<tomas@tuxteam.de>
Date2017-03-05 21:40 +0100
Message-ID<thL6F-5BR-3@gated-at.bofh.it>
In reply to#178446
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Sun, Mar 05, 2017 at 06:14:00PM +0000, GiaThnYgeia wrote:
> It is Sunday and I don't like Mondays
> tell me why
> 
> tomas@tuxteam.de:
> > Hm. Neither expr nor bc are bash, they are "external" binaries. If you
> > want to do arithmetic in bash, there's $((...)):
> > 
> >   tomas@rasputin:~$ echo $(( (3+4)/3 ))
> >   2
> 
> I see your 2 and raise you
> nosuchagency@bottomofthesea:~$ echo $(((3000000000+4000000000)/3))
> 2333333333
> 
> Infinitely inaccurate digital systems

:-)

Try GNU Guile: it'll happily fill your computer's memory with long integers:

  tomas@rasputin:~$ guile
  GNU Guile 2.0.13.5-458ae
  Copyright (C) 1995-2016 Free Software Foundation, Inc.
  
  Guile comes with ABSOLUTELY NO WARRANTY; for details type `,show w'.
  This program is free software, and you are welcome to redistribute it
  under certain conditions; type `,show c' for details.
  
  Enter `,help' for help.
  scheme@(guile-user)> (expt 2 2)
  $1 = 4
  ; aha: that's the function we're looking for ;-)
  scheme@(guile-user)> (expt 2 400)
  $2 = 2582249878086908589655919172003011874329705792829223512830659356540647622016841194629645353280137831435903171972747493376

regards
- -- tomás
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (GNU/Linux)

iEYEARECAAYFAli8dgEACgkQBcgs9XrR2kZ6kQCfSApe0fBbLHYUjrM5o251Z1j8
ojUAniMceGWgFKkSfcndntQDrWyi9BIB
=/cuA
-----END PGP SIGNATURE-----

[toc] | [prev] | [next] | [standalone]


#178491

FromGreg Wooledge <wooledg@eeg.ccf.org>
Date2017-03-06 14:40 +0100
Message-ID<ti11M-rk-9@gated-at.bofh.it>
In reply to#178446
On Sun, Mar 05, 2017 at 05:25:49PM +0100, tomas@tuxteam.de wrote:
> If you need floating point numbers, bc (or dc) are your next stops.

Or awk.  For some problems, awk is fantastic.


On Sun, Mar 05, 2017 at 06:14:00PM +0000, GiaThnYgeia wrote:
> I see your 2 and raise you
> nosuchagency@bottomofthesea:~$ echo $(((3000000000+4000000000)/3))
> 2333333333
> 
> Infinitely inaccurate digital systems

Bash uses 64-bit integers, since version 2.05b.  If you want arbitrary
precision, use bc (or a programming language with an arbitrary precision
math library).

POSIX shells in general may use smaller integers than that.  I wouldn't
expect anything outside the range (-2^31 .. +2^31) to be portable.

expr(1) is legacy rubbish and should never be used in new scripts.

[toc] | [prev] | [next] | [standalone]


#178492

From<tomas@tuxteam.de>
Date2017-03-06 15:00 +0100
Message-ID<ti1l7-yB-21@gated-at.bofh.it>
In reply to#178491
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Mon, Mar 06, 2017 at 08:38:05AM -0500, Greg Wooledge wrote:
> On Sun, Mar 05, 2017 at 05:25:49PM +0100, tomas@tuxteam.de wrote:
> > If you need floating point numbers, bc (or dc) are your next stops.
> 
> Or awk.  For some problems, awk is fantastic.
> 
> 
> On Sun, Mar 05, 2017 at 06:14:00PM +0000, GiaThnYgeia wrote:
> > I see your 2 and raise you
> > nosuchagency@bottomofthesea:~$ echo $(((3000000000+4000000000)/3))
> > 2333333333
> > 
> > Infinitely inaccurate digital systems
> 
> Bash uses 64-bit integers, since version 2.05b.  If you want arbitrary
> precision, use bc (or a programming language with an arbitrary precision
> math library).

As I found out, dc also supports arbitrary precision. Had I read the
man page's "NAME" entry

  NAME
       dc - an arbitrary precision calculator

with some more care, oh, well.

> POSIX shells in general may use smaller integers than that.  I wouldn't
> expect anything outside the range (-2^31 .. +2^31) to be portable.

Yes. Proceed with care.

> expr(1) is legacy rubbish and should never be used in new scripts.

It's from the times shells hadn't built-in arithmetic. If you are stuck
with, e.g. an old c shell (some over-expensive commercial application
at $COMPANY is), you might find calls to it deeply buried in shell
primordial soup. So it makes sense to keep it around. But yes, what
expr can do can/should be done (better) by $((...))

regards
- -- t
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (GNU/Linux)

iEYEARECAAYFAli9aX8ACgkQBcgs9XrR2kZ0kwCfRml26cNAb7uvl31UkB/gz+Ch
MMIAnjdfsjuUgpQ/JoP3Slha3I/OsQXQ
=czPp
-----END PGP SIGNATURE-----

[toc] | [prev] | [next] | [standalone]


#178494

FromJörg-Volker Peetz <jvpeetz@web.de>
Date2017-03-06 16:00 +0100
Message-ID<ti2hc-1cC-21@gated-at.bofh.it>
In reply to#178491
Greg Wooledge wrote on 03/06/17 14:38:
> On Sun, Mar 05, 2017 at 05:25:49PM +0100, tomas@tuxteam.de wrote:
>> If you need floating point numbers, bc (or dc) are your next stops.
> 
> Or awk.  For some problems, awk is fantastic.
> 

Yes, it helps to sample the number of "bytes" like so:

owl1=$(awk '/usb0/ {print $2}' /proc/net/dev)

# insert process to be measured

bytes=$(awk "/usb0/ {print (\$2 - $owl1)}" /proc/net/dev)


Regards,
jvp.

[toc] | [prev] | [next] | [standalone]


#178495

From<tomas@tuxteam.de>
Date2017-03-06 16:40 +0100
Message-ID<ti2TU-1G6-7@gated-at.bofh.it>
In reply to#178494
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Mon, Mar 06, 2017 at 03:50:06PM +0100, Jörg-Volker Peetz wrote:
> Greg Wooledge wrote on 03/06/17 14:38:
> > On Sun, Mar 05, 2017 at 05:25:49PM +0100, tomas@tuxteam.de wrote:
> >> If you need floating point numbers, bc (or dc) are your next stops.
> > 
> > Or awk.  For some problems, awk is fantastic.
> > 
> 
> Yes, it helps to sample the number of "bytes" like so:
> 
> owl1=$(awk '/usb0/ {print $2}' /proc/net/dev)
> 
> # insert process to be measured
> 
> bytes=$(awk "/usb0/ {print (\$2 - $owl1)}" /proc/net/dev)

Yep to Greg and thanks to Jörg. And to those who say "Perl": again,
I'm a Perl fan, but awk is *much* nimbler than Perl and thus far a
better match as a toolset utility in a shell script's context.

regards
- -- tomás
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (GNU/Linux)

iEYEARECAAYFAli9gY0ACgkQBcgs9XrR2kbDGACfZtsUq5bC0pgLDZsESy/NHCoa
mGkAnRabjRPiwTT2EERjVq5PUCnXyD2J
=cyV9
-----END PGP SIGNATURE-----

[toc] | [prev] | [next] | [standalone]


#178447

FromRichard Owlett <rowlett@cloud85.net>
Date2017-03-05 19:20 +0100
Message-ID<thIVb-49C-9@gated-at.bofh.it>
In reply to#178443
On 03/05/2017 10:25 AM, tomas@tuxteam.de wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> On Sun, Mar 05, 2017 at 09:42:16AM -0600, Richard Owlett wrote:
>> I'm interested in "expr" and "bc".
>> The man pages lack reasonable examples.
>> The tutorial/HOWTO pages confuse the issue with fancy page layouts
>> and/or code samples showing how impressive the author can make the
>> script's output.
>[snip]
>
> If you need floating point numbers, bc (or dc) are your next stops.

Actually  dc is the solution.
I date from Byte's FORTH issue. Benn a fan ever since.
>
> Perhaps you start with a couple of small examples on what you want
> to achieve, post them here and we take them as riddles :-)

How about the whole app <grin>
You solved my problem with one line.
The so called tutorial on dc went to great length to make it look like 
paper coming out of a desk calculator that it obliterated any 
information. Discouraged me from even looking at the man page.

>
> Here's a little example with dc, [snip]
>
> If you wanted to catch the value instead of printing it right away,
> you would do
> fill=$(dc -e "5k $NOW $FULL / p")

That's the hint I needed <*GRIN*>

I needed to report the number of bytes downloaded for each portion of a 
project. My 1st pass is below. [I messed up something when I tried to 
divide by 1024 to get kb. Symptom was I somehow had a bad value on the 
stack]


mystring=$(echo $(grep "usb0" /proc/net/dev))
read -r -a myarray <<<$mystring
owl1=${myarray[1]}
echo $owl1

# insert process to be measured

mystring=$(echo $(grep "usb0" /proc/net/dev))
read -r -a myarray <<<$mystring
owl2=${myarray[1]}
echo $owl2
bytes=$(dc -e "1k  $owl2 $owl1 - p ")
echo "You have just downloaded " $bytes " bytes"

Someone on another group wanted me to use LibreOffice Calc ;/

Thanks

[toc] | [prev] | [next] | [standalone]


#178449

FromRichard Owlett <rowlett@cloud85.net>
Date2017-03-05 19:50 +0100
Message-ID<thJoe-4lE-11@gated-at.bofh.it>
In reply to#178447
On 03/05/2017 12:10 PM, Richard Owlett wrote:
> On 03/05/2017 10:25 AM, tomas@tuxteam.de wrote:
>> -----BEGIN PGP SIGNED MESSAGE-----
>> Hash: SHA1
>>
>> On Sun, Mar 05, 2017 at 09:42:16AM -0600, Richard Owlett wrote:
>>> I'm interested in "expr" and "bc".
>>> The man pages lack reasonable examples.
>>> The tutorial/HOWTO pages confuse the issue with fancy page layouts
>>> and/or code samples showing how impressive the author can make the
>>> script's output.
>> [snip]
>>
>> If you need floating point numbers, bc (or dc) are your next stops.
>
> Actually  dc is the solution.
> I date from Byte's FORTH issue. Benn a fan ever since.
>>
>> Perhaps you start with a couple of small examples on what you want
>> to achieve, post them here and we take them as riddles :-)
>
> How about the whole app <grin>
> You solved my problem with one line.
> The so called tutorial on dc went to great length to make it look like
> paper coming out of a desk calculator that it obliterated any
> information. Discouraged me from even looking at the man page.
>
>>
>> Here's a little example with dc, [snip]
>>
>> If you wanted to catch the value instead of printing it right away,
>> you would do
>> fill=$(dc -e "5k $NOW $FULL / p")
>
> That's the hint I needed <*GRIN*>
>
> I needed to report the number of bytes downloaded for each portion of a
> project. My 1st pass is below. [I messed up something when I tried to
> divide by 1024 to get kb. Symptom was I somehow had a bad value on the
> stack]
>
>
> mystring=$(echo $(grep "usb0" /proc/net/dev))
> read -r -a myarray <<<$mystring
> owl1=${myarray[1]}
> echo $owl1
>
> # insert process to be measured
>
> mystring=$(echo $(grep "usb0" /proc/net/dev))
> read -r -a myarray <<<$mystring
> owl2=${myarray[1]}
> echo $owl2
> bytes=$(dc -e "1k  $owl2 $owl1 - p ")
> echo "You have just downloaded " $bytes " bytes"
>
> Someone on another group wanted me to use LibreOffice Calc ;/
>

<UGH> silly me had omitted a required SWAP.
Wonder why FORTH purists say even simplest code can benefit from stack 
comments ;>

[toc] | [prev] | [next] | [standalone]


#178455

From<tomas@tuxteam.de>
Date2017-03-05 21:30 +0100
Message-ID<thKWZ-5yk-1@gated-at.bofh.it>
In reply to#178447
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Sun, Mar 05, 2017 at 12:10:43PM -0600, Richard Owlett wrote:

[...]

> How about the whole app <grin>
> You solved my problem with one line.

Glad it helped :)

[...]

> I needed to report the number of bytes downloaded for each portion
> of a project [...]

Let me pick a nit...

> mystring=$(echo $(grep "usb0" /proc/net/dev))

This should be equivalent to

  mystring=$(grep "usb0" /proc/net/dev)

(background:

  - grep "usb0"/proc/net/dev
    spits out the line(s) containing the pattern "usb0"

  - the $(...) around it expands it in the shell inline

  - the echo spits that again out to stdout

  - the $(...) around it expands it again in-line

So unless the expansion is doing anything funky (which we won't hope,
but see below), you can unwrap the outer $(echo ...).

Now the second nit: I'm not sure whether there's a case when the
unquoted $(...) might undergo a further expansion by the shell,
so it's prudent to quote it, like so:

  mystring="$(grep "usb0" /proc/net/dev)"

(I know, my example wasn't... exemplar in this respect, but I knew
I was only getting plain numbers and I was kind of lazy: bad tomás)

> Someone on another group wanted me to use LibreOffice Calc ;/

Might work, but don't ask me how :-/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (GNU/Linux)

iEYEARECAAYFAli8c80ACgkQBcgs9XrR2kb3cwCfTzWmOlditJ0hK9vGMkpeJZQY
2BEAmwdhRnREpwGMQ9k8I1uS4jL10D9E
=+2Ss
-----END PGP SIGNATURE-----

[toc] | [prev] | [next] | [standalone]


#178462

FromRichard Owlett <rowlett@cloud85.net>
Date2017-03-05 22:00 +0100
Message-ID<thLq1-5IO-15@gated-at.bofh.it>
In reply to#178455
On 03/05/2017 02:23 PM, tomas@tuxteam.de wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> On Sun, Mar 05, 2017 at 12:10:43PM -0600, Richard Owlett wrote:
>
> [...]
>
>> How about the whole app <grin>
>> You solved my problem with one line.
>
> Glad it helped :)
>
> [...]
>
>> I needed to report the number of bytes downloaded for each portion
>> of a project [...]
>
> Let me pick a nit...
>
>> mystring=$(echo $(grep "usb0" /proc/net/dev))
>
> This should be equivalent to
>
>   mystring=$(grep "usb0" /proc/net/dev)

I was just copying the tutorial's syntax. I had no explanations, only 
code fragments. One of the sites that prompted me to ask for 
recommendations.

>
> (background:
>
>   - grep "usb0"/proc/net/dev
>     spits out the line(s) containing the pattern "usb0"
>
>   - the $(...) around it expands it in the shell inline
>
>   - the echo spits that again out to stdout
>
>   - the $(...) around it expands it again in-line
>
> So unless the expansion is doing anything funky (which we won't hope,
> but see below), you can unwrap the outer $(echo ...).
>
> Now the second nit: I'm not sure whether there's a case when the
> unquoted $(...) might undergo a further expansion by the shell,
> so it's prudent to quote it, like so:
>
>   mystring="$(grep "usb0" /proc/net/dev)"
>
> (I know, my example wasn't... exemplar in this respect, but I knew
> I was only getting plain numbers and I was kind of lazy: bad tomás)
>
>> Someone on another group wanted me to use LibreOffice Calc ;/
>
> Might work, but don't ask me how :-/

That poster's explanation made little sense. Only one of the reasons I 
didn't try it.

[toc] | [prev] | [next] | [standalone]


#178470

FromJude DaShiell <jdashiel@panix.com>
Date2017-03-05 23:20 +0100
Message-ID<thMFr-6PE-11@gated-at.bofh.it>
In reply to#178443
Another external tool at least as good as bc is wcalc and once that 
package gets installed just run wcalc at the command prompt and you'll 
have quite a load of examples show up.

On Sun, 5 Mar 2017, tomas@tuxteam.de wrote:

> Date: Sun, 5 Mar 2017 11:25:49
> From: tomas@tuxteam.de
> To: debian-user@lists.debian.org
> Subject: Re: Recomended tutoial(s) on doing arithmetic in Bash scripts
> Resent-Date: Sun,  5 Mar 2017 16:26:04 +0000 (UTC)
> Resent-From: debian-user@lists.debian.org
> 
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> On Sun, Mar 05, 2017 at 09:42:16AM -0600, Richard Owlett wrote:
>> I'm interested in "expr" and "bc".
>> The man pages lack reasonable examples.
>> The tutorial/HOWTO pages confuse the issue with fancy page layouts
>> and/or code samples showing how impressive the author can make the
>> script's output.
>
> Hm. Neither expr nor bc are bash, they are "external" binaries. If you
> want to do arithmetic in bash, there's $((...)):
>
>  tomas@rasputin:~$ echo $(( (3+4)/3 ))
>  2
>
> As you see, this does integer arithmetic. There's not much to it, the
> usuall stuff (more or less known from C, like pre/post increment, negation,
> bitwise and/or/xor... see the section "ARITHMETIC EVALUATION" in the
> bash manual.
>
> Expr and bc can do more -- but you've to take into account that they
> are external programs and thus give their response on stdout: you
> have to "catch" it somehow to make use of it. The `...` or the more
> modern and highly recommended $(...) come in:
>
>  tomas@rasputin:~$ foo=$(expr 3 + 4)
>  tomas@rasputin:~$ echo $foo
>  7
>
> Note that expr can also only do integers. I don't know whether expr
> brings anything to the table beyond portability. If you stick to bash
> (or dash, or...) it seems better to keep to the builtin $((...))
>
> If you need floating point numbers, bc (or dc) are your next stops.
>
> Perhaps you start with a couple of small examples on what you want
> to achieve, post them here and we take them as riddles :-)
>
> Here's a little example with dc, to get your appetite going. As you
> might know, I'm a Luddite and have no desktop environment. As a laptop
> user, I'm still interested on my battery's status: my laptop just
> quits pretty abruptly when empty, putting the excellent ext4 file
> system to test. For that, I've a small xterm which displays the
> battery fill status (which I want as a fraction of 1, to five
> significant digits, so I can see it's moving). The repeating is
> done outside the program, with "watch" -- invoked from my WM.
>
> Here's the shell snippet. The dc magic (dividing the battery's
> current status, called NOW, by the FULL status) is done at
> the last line:
>
>  #!/bin/bash
>  # Notes:
>  # for colors:
>  # tput setaf 1 ; tput bold ; echo -n 123 ; tput setaf 7 ; tput sgr0 ; echo 456
>  # cf tput(1) terminfo(5)
>  # do continuous mode with watch -c, possibly t
>
>  BAT='/sys/class/power_supply/BAT0'
>  AC='/sys/class/power_supply/ADP1'
>  FULL=$(cat $BAT/energy_full)
>  NOW=$(cat $BAT/energy_now)
>  case $(cat $AC/online) in
>    0) online="BAT" ;;
>    1) online="AC " ;;
>    *) online="???" ;;
>  esac
>  echo -ne "$online " ; dc -e "5k $NOW $FULL / p"
>
> The $online variable tells me whether I'm on AC or BATtery, for the dc line it's
> "5k" to set the five significant digits, then $NOW $FULL and the division "/"
> (note that dc is a stack calculator [1]), note that the expansion of $NOW, etc.
> is done by the shell.
>
> If you wanted to catch the value instead of printing it right away, you would
> do $fill=$(dc -e "5k $NOW $FULL / p")
>
> With bc it'd be similar; I never wrapped my head around bc's syntax, since
> dc has served me so well, but given enough motivation I don't think it's
> too hard.
>
> The script's comments hint at the next steps: COLORZ ;-)
>
> Enjoy
>
> [1] Like "Foot in yourself shoot.": look under Forth here:
>    http://www.thealmightyguru.com/Humor/Docs/ShootYourselfInTheFoot.html
>
> - -- tom?s
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.12 (GNU/Linux)
>
> iEYEARECAAYFAli8PA0ACgkQBcgs9XrR2kYGPACfab6u+HPGQbzcvEnfoCAbwjjK
> 46cAnR9AlDZzX0GrEAtSHwRcmL+syaKE
> =LElz
> -----END PGP SIGNATURE-----
>
>

-- 

[toc] | [prev] | [next] | [standalone]


#178487

FromRichard Owlett <rowlett@cloud85.net>
Date2017-03-06 12:20 +0100
Message-ID<thYQh-7rD-11@gated-at.bofh.it>
In reply to#178470
On 03/05/2017 04:12 PM, Jude DaShiell wrote:
> Another external tool at least as good as bc is wcalc and once that
> package gets installed just run wcalc at the command prompt and you'll
> have quite a load of examples show up.
>

For my current project I think dc, rather than expr or bc, is the better 
fit for my current project.

However, browsing thru http://w-calc.sourceforge.net/ and related pages 
indicates it might be a very nice alternative to the calculator that the 
default MATE package includes.

[toc] | [prev] | [next] | [standalone]


#178489

From<tomas@tuxteam.de>
Date2017-03-06 12:40 +0100
Message-ID<thZ9F-7yu-21@gated-at.bofh.it>
In reply to#178487
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Mon, Mar 06, 2017 at 05:13:36AM -0600, Richard Owlett wrote:
> On 03/05/2017 04:12 PM, Jude DaShiell wrote:
> >Another external tool at least as good as bc is wcalc and once that
> >package gets installed just run wcalc at the command prompt and you'll
> >have quite a load of examples show up.
> >
> 
> For my current project I think dc, rather than expr or bc, is the
> better fit for my current project.
> 
> However, browsing thru http://w-calc.sourceforge.net/ and related
> pages indicates it might be a very nice alternative to the
> calculator that the default MATE package includes.

Yes, wcalc looks nice, thanks Jude! And judging by its dependencies
(GNU gmp), it has a fair chance to pass GiaThnYgeia's big number
criterion ;-)

regards
- -- t
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (GNU/Linux)

iEYEARECAAYFAli9SN4ACgkQBcgs9XrR2kYVHgCfchLJNY6VRiqsDONZv5wdvylu
AtMAn2SWLqOPL7TFoDubiZdKkTLEIrNh
=LT2x
-----END PGP SIGNATURE-----

[toc] | [prev] | [next] | [standalone]


#178450

FromDavid Christensen <dpchrist@holgerdanske.com>
Date2017-03-05 20:50 +0100
Message-ID<thKki-51v-21@gated-at.bofh.it>
In reply to#178441
On 03/05/2017 07:42 AM, Richard Owlett wrote:
> I'm interested in "expr" and "bc".
> The man pages lack reasonable examples.
> The tutorial/HOWTO pages confuse the issue with fancy page layouts
> and/or code samples showing how impressive the author can make the
> script's output.
>
> Suggestions please.

https://www.perl.org/


David

[toc] | [prev] | [next] | [standalone]


#178459

FromRichard Owlett <rowlett@cloud85.net>
Date2017-03-05 21:50 +0100
Message-ID<thLgl-5Fg-11@gated-at.bofh.it>
In reply to#178450
On 03/05/2017 01:48 PM, David Christensen wrote:
> On 03/05/2017 07:42 AM, Richard Owlett wrote:
>> I'm interested in "expr" and "bc".
>> The man pages lack reasonable examples.
>> The tutorial/HOWTO pages confuse the issue with fancy page layouts
>> and/or code samples showing how impressive the author can make the
>> script's output.
>>
>> Suggestions please.
>
> https://www.perl.org/
>

Browsing the site I found some unintended humor - "The behavior of 
binary arithmetic operators depends on whether they're used on numbers 
or strings." http://learn.perl.org/faq/perlfaq4.html

More seriously, the site demonstrates to convey useful information to 
different audiences. I suspect I'm going get even less sleep ;>

Thank you.

[toc] | [prev] | [next] | [standalone]


#178480

FromDavid Christensen <dpchrist@holgerdanske.com>
Date2017-03-06 04:40 +0100
Message-ID<thRF7-1TU-5@gated-at.bofh.it>
In reply to#178459
On 03/05/2017 12:41 PM, Richard Owlett wrote:
> On 03/05/2017 01:48 PM, David Christensen wrote:
>> On 03/05/2017 07:42 AM, Richard Owlett wrote:
>>> I'm interested in "expr" and "bc".
>>> The man pages lack reasonable examples.
>>> The tutorial/HOWTO pages confuse the issue with fancy page layouts
>>> and/or code samples showing how impressive the author can make the
>>> script's output.
>>>
>>> Suggestions please.
>>
>> https://www.perl.org/
>
> Browsing the site I found some unintended humor - "The behavior of
> binary arithmetic operators depends on whether they're used on numbers
> or strings." http://learn.perl.org/faq/perlfaq4.html

That's not unintended humor, that's a bug in the documentation.  It 
should say:

     "The behavior of bitwise operators depends on whether they're
     used on numbers or strings."


I've filed a bug report -- thanks for the tip.


> More seriously, the site demonstrates to convey useful information to
> different audiences. I suspect I'm going get even less sleep ;>
>
> Thank you.

YW.  If you're interested in Perl 5, "Learning Perl" is the canonical 
introductory text:

    http://shop.oreilly.com/product/0636920049517.do


David

[toc] | [prev] | [next] | [standalone]


#178464

From<tomas@tuxteam.de>
Date2017-03-05 22:30 +0100
Message-ID<thLT3-6f2-3@gated-at.bofh.it>
In reply to#178450
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Sun, Mar 05, 2017 at 11:48:47AM -0800, David Christensen wrote:
> On 03/05/2017 07:42 AM, Richard Owlett wrote:
> >I'm interested in "expr" and "bc".
> >The man pages lack reasonable examples.
> >The tutorial/HOWTO pages confuse the issue with fancy page layouts
> >and/or code samples showing how impressive the author can make the
> >script's output.
> >
> >Suggestions please.
> 
> https://www.perl.org/

Perl's a nice language. But *if* you are doing things in shell and
just need to reach out to a small util to do a small thing (The
Shell Way, so to speak) you are better off with small utilities:

  tomas@rasputin:~$ time dc -e "2 2 + p"
  4
  
  real    0m0.004s
  user    0m0.000s
  sys     0m0.000s
  
  tomas@rasputin:~$ time perl -e "print 2 + 2"
  4
  real    0m0.011s
  user    0m0.012s
  sys     0m0.000s

Of course, if your program becomes complicated, Perl (or Guile, or
Python, or Lua or what not) will be a better choice: lexical variables,
a module system, closures, objects, all the kaboodle.

regards
- -- tomás
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (GNU/Linux)

iEYEARECAAYFAli8gO4ACgkQBcgs9XrR2kYsRwCbB62U94dZZrMTu4hkymzv75IO
VQUAn2lCn/vbrM7sD6wX6p9GNIBoE7P3
=rXYY
-----END PGP SIGNATURE-----

[toc] | [prev] | [next] | [standalone]


Page 1 of 2  [1] 2  Next page →

Back to top | Article view | linux.debian.user


csiph-web