[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Can Bash do simple math?
From: |
bash |
Subject: |
Re: Can Bash do simple math? |
Date: |
Tue, 6 Aug 2024 11:35:43 +0200 |
On Mon, Aug 05, 2024 at 07:10:05PM -0400, Greg Wooledge wrote:
> My first comment is that by using all-caps variable names, you're stepping
> on internal variables that bash uses for its own purposes. SECONDS has
> a special meaning. [...]
> Avoid all-caps variable names for precisely this reason.
>
This is very helpful. I always did uppercase variable names in Bash as I
thought this was the "standard way" of naming variables. Guess I should
reconsider!
> I wonder if the bug you're seeing goes away if you rename your variables.
>
It does! I have lowered the case of all variables in the script and run
the test for almost 8 million rounds without any errors.
> I wonder if your bug goes away if you stop calling the function in a
> command substitution. Something like this, perhaps:
>
No, it doesn't. Using your code but with a uppercase $SECONDS variable
name an error was produced after some 70k rounds:
70700 processed.
Round 70760 unexpected result: 1:1:36
With the $SECONDS variable lowercase, however, the script runs to
completion without any errors.
>
> If this doesn't generate errors, but your original does, then you'll have
> to figure out which one of my changes made the errors go away.
>
My guess is that the $SECONDS variable was updated by Bash _after_ my
assignment but _before_ the printf command, resulting in a "erroneous"
value being printed. A kind of race condition, perhaps :)
I appreciate your help in realising what I did wrong and the pointers to
improve my scripting in the future! Thanks :)
Re: Can Bash do simple math?, alex xmb sw ratchev, 2024/08/06