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

我怕爱的太早我们不能终老 提交于 2019-12-30 00:59:12

问题


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


回答1:


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)



回答2:


create two files: filelist - place all required directories ( one on single line )

and create a simple bash script:

    #!/bin/bash


for DIR in `cat filelist` 
do 
    if [ -d $DIR ] 
    then
        echo $DIR
    fi
done



回答3:


You can export a variable like DIRECTORIES="DIR1 DIR2 DIR3 ...." And in the script you need to use the variable like tar czvf $DIRECTORIES




回答4:


Just use the null-byte as delimiter when you write file / directory names to file. This way you need not worry about spaces, newlines, etc. in file names!

printf "%s\000" */ > listOfDirs.txt    # alternative: find ... -print0 

while IFS="" read -r -d '' dir; do command ls -1abd "$dir"; done < listOfDirs.txt

tar --null -czvf mytar.tar.gz --files-from listOfDirs.txt 



回答5:


In case, you are looking for compressing a directory, the following command can help.

pbzip2 compresses directories using parallel implementation

tar cf <outputfile_name> --use-compress-prog=pbzip2 <directory_name>


来源:https://stackoverflow.com/questions/3341131/gzipping-up-a-set-of-directories-and-creating-a-tar-compressed-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!