Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gzipping up a set of directories and creating a tar compressed file

My bash fu is not what it should be.

I want to create a little batch script which will copy a list of directories into a new zip file.

There are (at least) two ways I can think of proving the list of files:

  1. read from a file (say config.txt). The file will contain the list of directories to zip up OR

  2. hard code the list directly into the bash script

The first option seems more straightforward (though less elegant).

The two problems I am facing are that I am not sure how to do the following:

  • provide the list of directories to the shell script
  • iterate over the list of directories

Could someone suggest in a few lines, how I can do this?

BTW, I am running on Ubuntu 10.0.4

like image 756
morpheous Avatar asked Jul 27 '10 06:07

morpheous


People also ask

How do I compress a folder with tar?

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.

How do I create a tar file?

To create a tar file, use the cvf command line option, list the name of the resulting tar file first followed by a directory whose contents you want to tar-up. If you forget to list the tar file target (hw10. tar) in the tar command, tar will exit with an error message.


1 Answers

You can create a gzipped tar on the commandline as follows:

tar czvf mytar.tar.gz dir1 dir2 .. dirN

If you wanted to do that in a bash script and pass the directories as arguments to the script, those arguments would end up in $@. So then you have:

tar czvf mytar.tar.gz "$@"

If that is in a script (lets say myscript.sh), you would call that as:

./myscript.sh dir1 dir2 .. dirN

If you want to read from a list (your option 1) you could do that like so (this does not work if there is whitespace in directory names):

tar czvf mytar.tar.gz $(<config.txt)
like image 175
heijp06 Avatar answered Oct 08 '22 07:10

heijp06