1

I have this code:

printf -v s '%(%S)T' -1 # grab the current second
if ((s == 0)); then
  # at the top of the minute, run some code
fi

This code throws an error on the eighth and ninth second of every minute:

bash: ((: 08: value too great for base (error token is "08")
bash: ((: 09: value too great for base (error token is "09")

How can I rectify this? Basically, we need to suppress the leading zero in the date output generated by printf.

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • 2
    `s=${s##*0}` is a simply parameter expansion to remove all leading zeros. – David C. Rankin Dec 19 '17 at 06:25
  • @DavidC.RankinDav what about `s=10`? That would remove everything. – PesaThe Dec 19 '17 at 09:36
  • @DavidC.Rankin this may be better: `shopt -s extglob; s=${s##+(0)}`. – PesaThe Dec 19 '17 at 09:41
  • Agreed. `extglob` provides a better way to protect non-leading zeros. Another is substring replacement, e.g. `${a//^0*/}` – David C. Rankin Dec 19 '17 at 18:06
  • @DavidC.Rankin The anchor should be actually `#`. However, using `${a//#0*/}` won't help (`#` is not considered an anchor here because of the extra `/`), neither will `${a/#0*/}` (`#` is considered an anchor here but it will discard everything if the number starts with at least one `0` -- because of the `*`). I see only one possible option, using extglob again: `${a/#+(0)/}` or `${a/#*(0)/}`. – PesaThe Dec 20 '17 at 01:50

1 Answers1

4

Use a - prefix in the format string, thus:

printf -v s '%(%-S)T' -1

This suppresses the leading zero.

A more generic way of solving this is to specify the base in Bash arithmetic this way, while keeping the printf command unchanged:

if ((10#$s == 0)); then

Related post on Unix & Linux Stack Exchange:

codeforester
  • 39,467
  • 16
  • 112
  • 140