1

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.

skyork
  • 7,113
  • 18
  • 63
  • 103
  • Add `set -x` before the `tar rf` command and add the `v` flag to the `rf` command and see what you get as output? – Etan Reisner Jan 12 '16 at 03:32
  • 1
    Why do you think that the tar file is incorrect? All the files in the archive *except* the .plist file are hidden, so you won't see them if you unpack the archive and then do `ls`; you need `ls -a` to see hidden files. (Hidden files have names starting with a `.`. Probably your Mac finder also hides them from you.) Other than that, the answer by @PanRouchen is correct, although I would personally leave out the `v` because it just pollutes stdout. (Useful for verifying that things are working, I guess.) – rici Jan 12 '16 at 04:54
  • 2
    Your tar has all the files. It's just that the files beginning with `.` are hidden. – Martin Konecny Jan 12 '16 at 05:02
  • 1
    Sorry guys, that's a stupid question from me. Of course, I was checking the files in Finder, which does not show hidden files by default – skyork Jan 12 '16 at 05:05
  • Nah, the only stupid questions are the ones from which you learn nothing. And while you may not have learned much about tar with this one, you've certainly learned something! :) – ghoti Jan 12 '16 at 06:02

1 Answers1

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

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

Andy
  • 49,085
  • 60
  • 166
  • 233
Pan Ruochen
  • 1,990
  • 6
  • 23
  • 34