-3
    ubu@bruntu:/home/wideDB1$ echo $(($(date +%s%N)/1000000))
1441637184683
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/1000000))
730
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/1000))
bash: 088253206: value too great for base (error token is "088253206")
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/1000))
bash: 085061725: value too great for base (error token is "085061725")
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/10000))
59078
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/1000))
672523
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/10))
12079796
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/10000))
74644
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/100000))
1403
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/1000000))
5
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/100000))
9977
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/1000000))
360
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/100000))
6663
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/10))
10325856
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/100))
8020128
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/1000))
9461
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/10000))
81272
ubu@bruntu:/home/wideDB1$ echo $(($(date +%N)/10000))
bash: 046340492: value too great for base (error token is "046340492")

I must use this function in a bash script accurately for synchronizing milliseconds between tasks but here is very unstable. Anyone can help me to figure out what best solution for this work?

Cheers! Alessandro

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Alessandro
  • 55
  • 1
  • 4

2 Answers2

2

A string of digits beginning with 0 is treated as an octal number by default; you just need to tell bash to treat the string captured from date +%N as a decimal number in all cases, by prefix it with 10#.

$ echo $(( 10#$(date +%N)/1000000))
chepner
  • 497,756
  • 71
  • 530
  • 681
1

Digit strings inside of $((...)) are interpreted as numbers, but numbers starting with 0 are interpreted as octal numbers, i.e. in base 8.

You can easily remove the leading zeroes by parameter expansion:

#!/bin/bash
shopt -s extglob          # Enable extended globbing -- in this case, +(0)

for i in {1..20} ; do
    nanos=$(date +%N)
    echo -n "$nanos -> "
    nanos=${nanos##+(0)}  # Remove as many 0's from the left as possible.
    echo $nanos
done
choroba
  • 231,213
  • 25
  • 204
  • 289