bash 脚本代码帮助制作多个文件夹的 zip/tar

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3066027/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:22:39  来源:igfitidea点击:

bash script code help to make zip/tar of several folders

bashzipgzip

提问by Arshdeep

I am very new in bash and never coded in before but this task is stuck so need to get rid of it . I need to make bash script to make a single compressed file with several dirs.

我对 bash 很陌生,以前从未编码过,但这项任务被卡住了,所以需要摆脱它。我需要制作 bash 脚本来制作一个包含多个目录的压缩文件。

Like -

喜欢 -

/home/code/bots/
/var/config/
.
.
.
/var/system/

and all will be compressed to single file /var/file/bkup.[zip][tar.gz]

所有将被压缩到单个文件 /var/file/bkup.[zip][tar.gz]

Thanks in advance

提前致谢

回答by John Kugelman

# tar: (c)reate g(z)ip (v)erbose (f)ile [filename.tar.gz] [contents]...
tar -czvf /var/file/bkup.tar.gz /home/code/bots /var/config /var/system

# zip: (r)ecursive [filename.zip] [contents]...
zip -r /var/file/bkup.zip /home/code/bots /var/config /var/system

回答by ire_and_curses

The problem as you've described it doesn't require a bash script, just tar.

您所描述的问题不需要 bash 脚本,只需要tar.

tar cvzf /var/file/bkup.tar.gz /home/code/bots/ /var/config/ . . . /var/system/

回答by Dennis

You could create a bash file for it, if you intend to run it in a cronjob for example and add some other commands like a mysqldump beforehand

您可以为它创建一个 bash 文件,例如,如果您打算在 cronjob 中运行它并预先添加一些其他命令,例如 mysqldump

You need to create a file like backup.sh with the following contents (You may need to alter the path to bash, you can find bash with whereis bash)

你需要创建一个像backup.sh这样的文件,内容如下(你可能需要改变bash的路径,你可以用 找到bash whereis bash


#!/bin/bash
# 
# Backup script
# 

# Format: YEAR MONTH DAY - HOUR MINUTE SECOND
DATE=$(date +%Y%m%d-%H%M%S)

# MySQL backup file
MYSQLTARGET="/var/file/backup-mysql-$DATE.sql"

# Target file
TARTARGET="/var/file/backup-$DATE.tar.gz"

# MySQL dump
# you cannot have a space between the option and the password. If you omit the password value 
# following the --password or -p option on the command line, you are prompted for one.
mysqldump -u root -ppassword --all-databases > $MYSQLTARGET

tar -czvf $TARTARGET $MYSQLTARGET /home/code/bots /var/config /var/system

PS. This is untested code. It's just an example of how a bash script works in the current replied context.

附注。这是未经测试的代码。这只是 bash 脚本如何在当前回复的上下文中工作的一个示例。