From reading another answer I know the following command can be used to print the current epoch time:
$ date +'%s'
1491150773
From reading through the date(1)
man page (note: I actually use macOS) I found an example illustrating the usage:
Finally the command: date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s" can be used to parse the output from date and express it in Epoch time.
From reading the example, it seems like the +
can go inside the single quotes:
$ date '+%s'
1491150781
Even though I'm able to successfully print the current epoch time I don't understand why it's working and have some questions:
- Why does
date +'%s'
print the current epoch time? Is there a more general example that illustrates the pattern behind it's usage in this example? - Why am I able to put the
+
inside the quotes?
I've tried putting the command into explainshell, but it isn't very helpful:
Best Answer
BSD date and GNU date both have the form:
with
FORMAT
is the output format string for display the date. So what you would feed todate
is just a string, starting with+
.Before you passing the string to
date
, the string is interpreted by your shell. So+%s
or+'%s'
or"+%s"
are both equivalent, interpreted as-is by all POSIX shells.The only advantage of
+'%s'
is that you can quickly detect which string format was used, or copying, parsing it without worrying about the+
.Also,
+'FORMAT'
will helps you when you use some special formats, which can be interpreted as your shell expansion. Example withzsh
:would work while:
would not.