[Toybox] Would someone please explain what bash is doing here?

Chet Ramey chet.ramey at case.edu
Wed Apr 1 15:20:36 PDT 2020


On 3/30/20 6:45 PM, Rob Landley wrote:
> Bash's handling of $SECONDS is kind of inconsistent:

Dynamic variables like SECONDS and RANDOM (and FUNCNAME, and HISTCMD, and
BASH_COMMAND, etc.) are different beasts, to be sure.

For one thing, dynamic variables have complete freedom over their behavior:
they can ignore the readonly attribute (or any others), silently swallow
assignments, process assigned values in arbitrary ways, and so on.

The implementation is via functions to reference and assign values. When
the variable is referenced ($SECONDS), the function is called and its
return value stored into the variable, which is then returned as usual.
The same basic thing happens on assignment, which generally has side
effects. Not all dynamic variables have assignment functions.

Dynamic variables only have their value functions called when the variable
is referenced. When the variables are simply fetched (declare -p, and
similar) or enumerated (building an export array), you get the value
stored in the variable, which is the result of the last time the value
function was called.

> 
> $ SECONDS=0; echo $SECONDS # why does this print nothing?

I can't reproduce this.

> $ readonly SECONDS; declare -p SECONDS ; SECONDS=0
> declare -ir SECONDS="6"
> $ echo $SECONDS # readonly was ignored, assignment happened anyway

Yep.

> $ SECONDS=123+456 # it STARTS integer, but integer assignment sets it to 0

It's never processed assignments as expressions, but it probably should if
it has the integer attribute. That would be consistent with the ksh93
behavior.


> I can't be the first person to test these corner cases, can I? (Version 4.4.12
> as in devuan ascii.)

Pretty much. Or any reports happened long enough ago that I've forgotten
them. Bash has pretty much always behaved this way.

> Speaking of inconsistent, an inherited SECONDS in the environment will init
> $SECONDS in a new bash instance, but will NOT init RANDOM to a reproducible
> series. Is this an intentional security thing or an oversight?

Well, it's a potential security problem if you can control what a script
does with RANDOM, if the script assumes that the shell will seed the
random number generator when it starts (e.g., constructing file names).
ksh93 behaves the same way.

I agree with you that dynamic variables should honor the readonly attribute
and will make that change in the next devel branch push.

Chet
-- 
``The lyf so short, the craft so long to lerne.'' - Chaucer
		 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    chet at case.edu    http://tiswww.cwru.edu/~chet/



More information about the Toybox mailing list