5

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")
_file="$_nowout.log"
touch $_file.txt # creating new file with the timedate

How can I create the new file with the datetime?

  • 1
    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 '16 at 23:31
14

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")
_file="${_now}out.log"
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.

  • 3
    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 '16 at 12:26
  • @StéphaneChazelas useful suggestion, thanks. I'll mention it in my answer. – Dmitry Grigoryev Mar 8 '16 at 14:36
9

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.

Use

_file="${_now}out.log"

to explicitly use the $_now variable.

So the script becomes:

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

Which, for the record can be shortened to:

touch "$(date +%m_%d_%Y)out.txt"

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.