8

This question already has an answer here:

I'd like to build an error handler which will make an empty file marked with the error_occur time.

The core idea is to use the result of date command as a parameter.

I did:

time_stamp=$(date)
touch $time_stamp

But this turns out to create a series of empty file like 2014, Wed, 11:15:20.

How to convert time_stamp to a whole string here?

marked as duplicate by Gilles bash Oct 29 '14 at 23:09

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    cuonglm and Anthon have both given good answers to your question. But you will make your life simpler by avoiding making files that have spaces (or other special characters) in their names, especially if you want to use bash (and similar shells) with them. It's not hard to handle such file names in bash, but dealing with such names can certainly bloat what could be a simple one line shell command into something that you need to write a proper script for. – PM 2Ring Oct 29 '14 at 10:22
14

You must double quote your variable:

time_stamp="$(date)"
touch "$time_stamp"

In this case, double quote in "$(date)" is not mandatory, but it's a good practice to do that. You can read this for more understanding.

13

cuonglm's answer solves the problem of creating a file with spaces in general, but the problem starts by using the default output from date.

If you ever want to use a date or date-time string as part of your file name you should always use the --rfc-3339 option (if on a recent GNU system) or an appropriate format string. This will give you file names that are sortable in a logical way. The --rfc-3339 option takes a parameter, use seconds, ns or date depending on the accuracy you want in the filename:

time_stamp="$(date --rfc-3339=seconds)"
touch "$time_stamp"

You can also get a specific string without any spaces and just the info that you need from date +FORMAT (use man date for details).

time_stamp="$(date +%Y%m%d-%H%M)"
touch "$time_stamp"

will give you a file with a name like 20141029-0944 with no spaces and give you the illusion that you don't need to quote. But you still do, as you'd still be invoking the split+glob operator which could still actually split if used in a context where $IFS has been changed from the default.

  • 1
    The output of date --rfc-3339=seconds still contains spaces, why not date --iso-8601=seconds (or just date -Iseconds)? – nyuszika7h Oct 29 '14 at 14:11
  • 1
    @nyuszika7h That looks good and works for date on my Ubuntu 12.04 box, but neither man date nor date --help mentions it. So I hope that is good enough an excuse. – Anthon Oct 29 '14 at 14:15
  • 1
    It appears to be undocumented on Debian too, but it's in the man page on Arch Linux. Not sure why. – nyuszika7h Oct 29 '14 at 14:20

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