17

I have a bash script containing the following 2 lines:

Hour=$(date +"%H")
Hour=$((10#$Hour))

What does line 2 do?

23

The 10# tells it to expand the number using base 10:

Constants with a leading 0 are interpreted as octal numbers. A leading ‘0x’ or ‘0X’ denotes hexadecimal. Otherwise, numbers take the form [base#]n, where the optional base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used. When specifying n, the digits greater than 9 are represented by the lowercase letters, the uppercase letters, ‘@’, and ‘_’, in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably to represent numbers between 10 and 35.

Examples:

Base 16:

$ echo $((16#A))
10

Base 8:

$ echo $((8#12))
10

Base 2:

$ echo $((2#1010))
10

As steeldriver points out this is likely being done to handle any potential leading zeros from the date command but with recent versions of GNU date it can be done easier using: date +%-H

  • 2
    In this particular case, it might be worth mentioning that (at least in recent versions of GNU date) leading zeros can be suppressed at source using a printf-style - format modifier +%-H – steeldriver Apr 7 '18 at 14:17
  • 2
    @steeldriver -yeah... unix.stackexchange.com/q/70966/22142 – don_crissti Apr 7 '18 at 14:19
  • @don_crissti - yes that's the one, I couldn't find it – steeldriver Apr 7 '18 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.