7

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:

enter image description here

  • Are you using FreeBSD, as the link to the man page implies? – roaima Apr 2 '17 at 21:49
  • Yes, I'm on macOS which uses bsd utilities – mbigras Apr 2 '17 at 22:25
  • OK. I've added that as a tag to people can identify this more easily. Otherwise you're likely to get some very Linux and GNU-centric responses. You might even want to mention it in passing within your question. – roaima Apr 2 '17 at 22:31
  • On mobile, will make edit when I get home – mbigras Apr 2 '17 at 22:50
  • 1
    @roaima Please don't put an OS tag on a question that isn't OS-specific. Since the question is largely OS-agnostic, a mention of the OS in the body is fine, and no OS tag should be used. – Gilles Apr 2 '17 at 23:40
14

BSD date and GNU date both have the form:

date +FORMAT

with FORMAT is the output format string for display the date. So what you would feed to date 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 with zsh:

date +'(%s)'

would work while:

date +(%s)

would not.

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.