Just discovered in amazement that in Bash scripts, any variable named `SECONDS` will automatically increment every second. Bash is bonkers
Just discovered in amazement that in Bash scripts, any variable named `SECONDS` will automatically increment every second. Bash is bonkers 43 comments
@eisfunke @Cykelero @jakehamilton the actual use of the variable is to count the number of seconds since the bash instance was started - you don't have to assign anything to it but assigning a value resets it to that value (and it normally only works with the uppercase SECONDS). Bash also offers $RANDOM (you can guess what it does) as well as $EPOCHSECONDS and $EPOCHREALTIME for the more exotic ones. And.. many more (https://www.gnu.org/software/bash/manual/bash.html#Bash-Variables) @Cykelero it took me ages to track down that bug in one of my scripts a few months back. And when I say "track down" I mean "ineffectually whine for hours WHY DO YOU HATE ME? WHY IS THE COMPUTER DOING RANDOM STUPID SHIT?" until I asked someone on the internet and got an answer within approximately six seconds. Or was it seven? eight? nine? ... @DrHyde Exactly!! Their intent was good, but the implementation deeply unfortunate Huh… that's a pre-defined variable counting the runtime of the script. The core issue here is that you used a reserved variable. There is exactly one variable named SECONDS, so "bash incrementing any variable named SECONDS" doesn't make much sense. @nik Right! That’s the technically-accurate explanation. But I think many people will write a script *thinking* they’re just creating a regular old variable, not realizing they’re stepping on a landmine of good intentions @Cykelero If I randomly do "echo $SECONDS", it seems to start at the number of seconds since the shell was launched. It does not show up in "env | grep SECONDS". Bonkers, like the man said. @Cykelero Zsh too, and in zsh it can be floating point, if you want. Another reason to prefer lowercase for your local $variables @Cykelero you are just referencing a magic variable called SECONDS built into bash (and zsh). There are a few others that do ‘interesting’ things too! @grumpyoldtechie @Cykelero yep, it’s a bash-ism. Nothing to do with posix Bourne shell. Not sure about ksh. @grumpyoldtechie @Cykelero looks like ksh also has SECONDS but theirs is more sensible, which is generally true of ksh vs bash in my experience: @Cykelero Have you ever looked at /dev/tcp/… and /dev/udp/… ? Non-existent "files" that allow you to do networking from Bash. @Cykelero did you check the man page for bash? it's documented there under shell variables. @Cykelero@mas.to |
@Cykelero didn't want to believe you, so I tried it and now I'm staring at my screen in disbelief
yields