2

I'm trying to tar a large directory, and I'd like the output file to contain the date. Here's what I have so far.

tar -zcvf "mywebsite website backup" $(date "+%Y-%m-%d %T") public_html

This doesn't quite work though. As an example, I'm trying to get the single string below to be the file name. The call to date is working fine and I don't need help with that, but I'm not sure how to concatenate the "my website backup" with the output from date without first storing them in variables (which seems ham fisted).

mywebsite website backup 2001-12-01 12:04:03

2 Answers 2

4

Variables and such are interpreted within double quotes (but not within single quotes):

tar -zcvf "mywebsite website backup $(date '+%Y-%m-%d %T').tgz" public_html

(I added the .tgz suffix, you apparently forgot.)

If you had no white space in your file name, you could do it without quotes:

tar -zcvf foo_backup_$(date '+%Y-%m-%d_%T').tgz foo/

Or you could turn it around and use the fact that date already accepts a format string:

tar -zcvf $(date +'foo_backup_%Y-%m-%d_%T.tgz') foo/

(Still needs double quotes around $() if the file name contains white space.)

NB: For various reasons it is usually not a good idea to include colons in file names.

Sign up to request clarification or add additional context in comments.

6 Comments

I tried the command you listed and it threw this error. Just incase this wasn't clear $(date) is a call to the date command, not a variable. tar (child): Cannot connect to mywebsite website backup 2012-02-05 09: resolve failed
@Jazzepi: The colon might present a problem with your setup (seems to be interpreted as network path). Use another time format. This has nothing to do with your original question.
Yeah that seems to have been the problem. I didn't realize you could do $() calls inside of a string literal.
@Jazzepi: Your last comment doesn't make much sense, since you already used $() in a "string literal" in your original question. Quotes are not necessary to make somthing a literal in bash. (Also, accepting my answer would be nice, if it did help you.)
@Jazzepi: double-quotes don't make a string literal in bash; in fact, most things are string literals by default. For example in echo foo bar, foo and bar are string literals. That's what @hop meant by saying you'd already used $() inside a string literal. What double-quotes actually do is prevent some types of interpretation (e.g. spaces as "word" breaks) but allow others (e.g. $var, $(cmd)). Single-quotes, on the other hand, prevent almost all types of interpretation.
|
1

You can also try syntax:

tar -zcvf "mywebsite website backup `date \"+%Y-%m-%d %T\"`.tgz" public_html

1 Comment

backticks are deprecated in favor of $(). using single quotes for the format string would make escaping unnecessary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.