bash 创建 tar 文件并按当前日期命名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18498359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating tar file and naming by current date
提问by Anonymous Entity
I'm trying to create a backup script in bash, to tar the contents of a folder and move the resulting file somewhere, but I don't really know how to do it.
我正在尝试在 bash 中创建一个备份脚本,以 tar 文件夹的内容并将生成的文件移动到某个地方,但我真的不知道该怎么做。
#!/bin/bash
name="$date +"%y-%m-%d""
tar -zcvf $name code
But the result is that the file is just named +%y-%m-%d
. How can I change the script to name the file by the date as intended?
但结果是该文件只是命名为+%y-%m-%d
. 如何更改脚本以按预期日期命名文件?
Intended output: 2013-08-29.tar
预期输出: 2013-08-29.tar
回答by Aleks-Daniel Jakimenko-A.
Like this:
像这样:
name=$(date '+%Y-%m-%d')
tar -zcvf "$name.tar.gz" code
or even in one line:
甚至在一行中:
tar -zcvf "$(date '+%Y-%m-%d').tar.gz" code
Drop -z
flag if you want .tar
instead of .tar.gz
.
-z
如果需要.tar
,请删除标志而不是.tar.gz
.
Use %y
instead of %Y
if you want just 2 digits of a year (17
instead of 2017
).
如果您只需要年份的 2 位数(而不是),请使用%y
代替。%Y
17
2017
$()
is used for command substitution.
$()
用于命令替换。
回答by Gianfranco P.
tar -zcvf "$(date '+%F').tar.gz" code-path
will produce full date; same as %Y-%m-%d
. (see man date
follow by /
) to search and %F
.
将产生完整的日期;一样%Y-%m-%d
。(见man date
后面的/
)搜索和%F
。
For example, it will generate:
例如,它将生成:
2015-07-21.tar.gz
If code-path
is a directory it will compress and archive all the files in it.
如果code-path
是一个目录,它将压缩并存档其中的所有文件。
回答by Kyle Coots
On BSD System you may need to use it like this:
在 BSD 系统上,您可能需要像这样使用它:
/usr/bin/tar -czvf /home/user/backup-`(date +%y-%m-%d)`.tar.gz /some/file.txt