21

Command 1:

$ touch test"date"

Command 2:

$ date +"%F"
2018-01-16

I want to be able to run the command so the file test_2018-01-16 is created. How do or can I combine the 2 commands above to do this?

$ touch test_"date"

EDIT1 - Answer

tks

these commands

touch fred-`date +%F`
touch "test-$(date +%F)"
touch "test2_$(date +"%F %T")"

prduce the following files respectively

fred-2018-01-16
test-2018-01-16
test2_2018-01-16 11:51:53
HattrickNZ
  • 4,373
  • 15
  • 54
  • 98

2 Answers2

34

You should use double quotes and need to evaluate date +"%F" using command substitution.

  $ touch "test_$(date +%F)"

This will create an empty file test_2018-01-15

Double quote helps you create a single file where some options of date command would include a space.

For example, touch test_$(date) will create multiple files, where as touch "test_$(date)" won't.

As pointed out by OP, one would need additional quotes " around the format options, when multiple of them are used:

touch "test_$(date +"%F %T")" 
iamauser
  • 11,119
  • 5
  • 34
  • 52
  • Actually you don't. – ypnos Jan 15 '18 at 21:37
  • Is there something wrong with the answer ? – iamauser Jan 15 '18 at 21:38
  • I don't see anything wrong either actually. – PesaThe Jan 15 '18 at 21:40
  • "Don't need double quotes" (in this very specific case), maybe? – Benjamin W. Jan 15 '18 at 21:46
  • The original answer just said "You need double quotes" and no other explanation. It is all fixed now. – ypnos Jan 15 '18 at 21:48
  • Consider quoting the format string as well (I know it doesn't matter here) :) – PesaThe Jan 15 '18 at 21:51
  • @PesaThe You don't need additional quotes around the format options because they are covered under the quotes around the filename. Do you see an edge case that I don't see ? – iamauser Jan 15 '18 at 21:53
  • Careful here, `$()` creates a new quoting context. Try this: `touch "test_$(date +%F %T)"` :) – PesaThe Jan 15 '18 at 21:55
  • Is this `date +%F %T` even a valid syntax. I am using GNU date and it gives me error. If you are talking about `date +%F +%T`, there can't be a space between the format options without quoting them around. This answer doesn't cover how one should execute the `date` command correctly. – iamauser Jan 15 '18 at 22:00
  • 1
    Ah, that's what I meant. To quote the string like this: `touch "test_$(date +"%F %T")"`. It is not needed in this case. But shows to OP how easily he can add format strings with spaces. Which I think might come in handy since OP didn't know how to use command substitution :) it's up to you of course. – PesaThe Jan 15 '18 at 22:04
4

In my world (with Bash) its:

touch fred-`date +%F`

where 'fred-' is the prefix and teh date command provides the suffix

Mike Tubby
  • 41
  • 1
  • 2