help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

SECONDS=0 does not reset SECONDS, or I'm missing something


From: Andreas Kusalananda Kähäri
Subject: SECONDS=0 does not reset SECONDS, or I'm missing something
Date: Thu, 4 Jun 2020 12:14:03 +0200

I wrote a small script to delete many hundreds of thousands of files
off a very slow disk.  The script is executed from find(1) and is
given pathnames of directories to delete as arguments.  If a directory
takes a second or more to delete a directory, the script sleeps for
the amount of time it took to delete that directory before proceeding,
in an attempt to let the filesystem sync metadata (this may have been
misguided but it's not really important).

        #!/usr/local/bin/bash -x

        for name do
                SECONDS=0
                rm -r -f "$name"
                [[ SECONDS -gt 0 ]] && sleep "$SECONDS"
        done

What I noticed was that the script would go to sleep for a second
every second, even if the deletion of directories was quick.  This
indicates that SECONDS=0 didn't properly reset the SECONDS timer.  Or,
it indicates that the timer is set by the system's clock (the current
second according to the current time), and that it is not a real "timer"
at all.  Or, that I have misunderstood something about how SECONDS is
supposed to work.  Or, all of the above (please confirm).

A sample script (see below) reproduces this with a tight loop on macOS
Catalina running "5.0.17(1)-release (x86_64-apple-darwin19.4.0)"
(bash from Homebrew) and on OpenBSD 6.7 running "5.0.17(1)-release
(x86_64-unknown-openbsd6.7)".

        while true; do SECONDS=0; [[ SECONDS -gt 0 ]] && echo hi; done

(will print "hi" more or less once a second, and possibly slightly less
often occasionally)

So, I don't know whether this is an error in the documentation, my
understanding of it, or in how the SECONDS variable is set/managed
internally by the shell.  I'm assuming I'm misunderstanding.

For reference (from the bash manual):

        SECONDS
               Each time this parameter is referenced, the number
               of seconds since shell invocation is returned.  If a
               value is assigned to SECONDS, the value returned upon
               subsequent references is the number of seconds since
               the assignment plus the value assigned.  If SECONDS is
               unset, it loses its special properties, even if it is
               subsequently reset.



-- 
Andreas (Kusalananda) Kähäri
SciLifeLab, NBIS, ICM
Uppsala University, Sweden

.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]