How to treat strings with spaces as a whole in bash?
Solution 1
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.
Solution 2
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.
Related videos on Youtube
Zen
Updated on September 18, 2022Comments
-
Zen over 1 year
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?
-
nyuszika7h over 9 yearsThe output of
date --rfc-3339=seconds
still contains spaces, why notdate --iso-8601=seconds
(or justdate -Iseconds
)? -
Anthon over 9 years@nyuszika7h That looks good and works for
date
on my Ubuntu 12.04 box, but neitherman date
nordate --help
mentions it. So I hope that is good enough an excuse. -
nyuszika7h over 9 yearsIt appears to be undocumented on Debian too, but it's in the man page on Arch Linux. Not sure why.
-
user1730706 over 9 yearsYou do not need quotes on the first line unix.stackexchange.com/a/131784
-
cuonglm over 9 years@StevenPenny: Yes, of course, I also noted this in my answer.