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

Re: Is there a POSIX compliant way of turning a "HH:MM:SS" formatted string to seconds? ...



On 19/07/2025 19:26, Greg Wooledge wrote:
On Sat, Jul 19, 2025 at 10:14:49 +0700, Max Nikulin wrote:
A mathematical trick may be used instead even if external processes like sed
are considered as undesired overhead

for i in 0 09 008 59 080; do i1=1$i; i2=2$i; echo "$i = $((2*i1 - i2))";
done

0 = 0
09 = 9
008 = 8
59 = 59
080 = 80
Oh, I like this one.  I'm gonna add that to my wiki.

I have no idea to which degree the following is portable:

strip_zeroes() { zeroes="${1%%[!0]*}"; printf '%s\n' "${1#"$zeroes"}"; }

for i in 0 09 008 59 080 008000 0xABCD -008; do echo "$i = '$(strip_zeroes "$i")'"; done
0 = ''
09 = '9'
008 = '8'
59 = '59'
080 = '80'
008000 = '8000'
0xABCD = 'xABCD'
-008 = '-008'

It should help if you care concerning overflow (original problem in this thread is for formatted duration, so many digits are unlikely). However what I am really afraid of is

https://mywiki.wooledge.org/BashPitfalls#pf46
46. read num; echo $((num+1))

Always validate your input (see BashFAQ/054) before using num in an arithmetic context as it allows code injection.

$ echo 'a[$(echo injection >&2)]' | bash -c 'read num; echo $((num+1))'
injection
1

P.S.

JavaScript (browser dev tools console)
009 === 9 // => true
parseInt("009") // => 9
010 === 8 // => true
parseInt("010") // => 10



Reply to: