bash 如何在bash中将日期附加到字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26768491/
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
How to append the date to a string in bash
提问by thelearnerofcode
I have a script that backups my Raspberry Pi
我有一个脚本可以备份我的 Raspberry Pi
sudo dd bs=1M if=/dev/sda1 of=/home/pi/backup.img
zip -r /home/pi/backup/backup.zip /home/pi/backup.img
cp backup.zip ~/backup
I want to know how I can append the date to the backup.zip file, generated by the second line.
我想知道如何将日期附加到第二行生成的 backup.zip 文件中。
Any tips?
有小费吗?
回答by Mr. Llama
You can use command substitutionto accomplish this.
You might also want to familiarize yourself with the date
components:
您可以使用命令替换来完成此操作。
您可能还想熟悉这些date
组件:
# Save the file name in a variable so we don't repeat ourselves
outfile="/home/pi/backup/backup.zip.$(date +%Y%m%d)"
sudo dd bs=1M if=/dev/sda1 of=/home/pi/backup.img
zip -r "${outfile}" /home/pi/backup.img
cp "${outfile}" ~/backup
The magic here is the $(date +%Y%m%d)
. This runs date +%Y%m%d
and captures the output which will be the current date in YYYYMMDD format.
这里的魔法是$(date +%Y%m%d)
. 这将运行date +%Y%m%d
并捕获输出,该输出将是 YYYYMMDD 格式的当前日期。