Search code examples
bashshelltarbz2

Create a .tar.bz2 file given an array of files


In a Bash script, I have an array that contains a list of files (in the form of their complete file paths):

declare -a individual_files=("/path/to/a" "/path/to/b" "/path/to/c")

I want to create a compressed file in tar.bz2 which contains all the files in the array, using tar command.

So far, I have tried

tar rf files.tar "${individual_files[@]}"
tar cjf files.tar.bz2 files.tar

But for some reason, files.tar.bz2 always contains the last file in the array only.

What is the correct command(s) for doing so, preferably without creating the intermediate .tar file?

UPDATED: using @PanRuochen's answer, this is what I see in the verbose info:

+ tar cfvj /Users/skyork/test.tar.bz2 /Users/skyork/.emacs /Users/skyork/.Rprofile /Users/skyork/.aspell.en.pws /Users/skyork/.bash_profile /Users/skyork/.vimrc /Users/skyork/com.googlecode.iterm2.plist
tar: Removing leading '/' from member names 
a Users/skyork/.emacs
a Users/skyork/.Rprofile
a Users/skyork/.aspell.en.pws
a Users/skyork/.bash_profile
a Users/skyork/.vimrc
a Users/skyork/com.googlecode.iterm2.plist

But still, the resulted test.tar.bz2 file has only the last file of the array (/Users/skyork/com.googlecode.iterm2.plist) in it.

My bad, the files are indeed there but hidden.


Solution

  • tar cfvj files.tar.bz2 "${individual_files[@]}"
    

    v should give you verbose information about how bz2 file is created.