Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

zip

gzip

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.

Like -

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

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

Thanks in advance

like image 201
Arshdeep Avatar asked Jun 17 '10 22:06

Arshdeep


People also ask

How do I zip a tar folder?

tar -cf {tar-filename} /path/to/dir # step 1 - create the tarfile. gzip {tar-filename} # step 2 - compress the tarfile. However you can instruct the tar command to also do the gzipping for you: tar -cvzf {tar-filename} /path/to/dir # Here, tar compresses the tar file using the gzip utility.

Which command can be used to archive all the files with. txt extention into the parent directory with name archive tar?

gzip compression over tar archive with -z option It is the archive of every . txt file. The command is as follows: $ tar cvzf file.


3 Answers

# 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
like image 57
John Kugelman Avatar answered Nov 15 '22 22:11

John Kugelman


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

tar cvzf /var/file/bkup.tar.gz /home/code/bots/ /var/config/ . . . /var/system/
like image 31
ire_and_curses Avatar answered Nov 15 '22 20:11

ire_and_curses


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

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)


#!/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.

like image 40
Dennis Avatar answered Nov 15 '22 22:11

Dennis