Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to add date and time to the file name, for example: 08032016out.log.zip

This is what I try to do:

_now=$(date +"%m_%d_%Y")
touch $_file.txt # creating new file with the timedate

How can I create the new file with the datetime?

share|improve this question
I very strongly recommend using YYYYMMDD rather than DDMMYYYY. YYYYMMDD is the only format that sorts correctly, which (along with the fact that it's unambiguous) is why it's the ISO standard recommended date format (see en.wikipedia.org/wiki/ISO_8601) – cas Mar 8 at 23:31

You have created a variable named _now, but later you reference a variable named _nowout. To avoid such issues, use curly braces to delimit variable names:

_now=$(date +"%m_%d_%Y")
touch "$_file.txt"

Note that I have left "$_file.txt" as is, because . is already a variable names delimiter. When in doubt, "${_file}.txt" could be used just as well.

Bonus 1: ${varname} syntax actually provides several useful string operations on variables, in addition to delimiting.

Bonus 2: creative shell escaping and quoting can also be used to delimit variable names. You could quote the variable and the string literal separately (i.e. file="$_now""out.log" or file="$_now"'out.log') or leave one of the parts unquoted (i.e. file=$_now"out.log" or file="$_now"out.log). Finally, you can escape a single character which follows your variable name: file=$_now\out.log. Though I wouldn't recommend reusing these examples without good understanding of shell quoting and escaping rules.

share|improve this answer
Note that you could also do file="$_now"'out.log' or file=$_now\out.log, that is using quoting operators would also delimit variables (${var} is a lot better/canonical though) – Stéphane Chazelas Mar 8 at 12:26
@StéphaneChazelas useful suggestion, thanks. I'll mention it in my answer. – Dmitry Grigoryev Mar 8 at 14:36

You need to specify the boundaries of the variable name.

_file will be set to $_nowout.log but the shell can not determine if you mean $_now or $_nowout.



to explicitly use the $_now variable.

So the script becomes:

_now=$(date +"%m_%d_%Y")
touch "${_file}.txt"

Which, for the record can be shortened to:

touch "$(date +%m_%d_%Y)out.txt"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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