Reputation: 83
So I found out the hard way that $(date +%H)
will return a base 8 number from 1 am to 9 am. No big deal, I forced it to be a base 10 number by writing: $((10#$(date +%H) ))
... Here is my issue, writing exactly that throws an error "-bash: 9: command not found" but if I say echo $((10#$(date +%H) ))
it will return me the proper number. Any clue to why this happens? And how will you go about fixing it? Thank you
Upvotes: 1
Views: 355
Reputation: 881553
If your variant of date
is fairly recent, there are format modifiers that can change or disable the padding as per the man
page:
By default, date
pads numeric fields with zeroes. The following optional flags may follow %
:
-
(hyphen) do not pad the field._
(underscore) pad with spaces.0
(zero) pad with zeros.Hence the first thing I would try would be date -%-H
. This should give you the hour without any padding.
On the off chance you have an ancient date
variant, you can get an actual number (single or double digit depending on the time) with something like:
((hr = 1$(date +%H) - 100))
The 1$(date +%H)
will give you a value between 100
and 123
inclusive then subtract 100
to give you the numeric hour.
For example, at 4:23am, this will take the 04
from date +%H
, turn that into 104
then subtract 100
to get the number 4
.
Numbers greater than 9
will also work. The time 4:42pm will take the 16
from date +%H
, turn that into 116
then subtract 100
to get the number 16
.
In respect to why you're getting an error, the command $((10#$(date +%H)))
will evaluate to 9
(assuming time is 09:xx
) and then just try to execute that (which, unless you have an executable 9
somewhere in you path, will error).
Prefixing it with echo
will cause the command echo 9
to be run, which is valid.
As you can see, you don't need to echo it, you can store it in a variable (like hr
above) for later use.
Upvotes: 3