alexs333 alexs333 - 3 months ago 13x
Bash Question

Bash - creating tar for array items

I have an array with files and directories that I wish to add to the compressed tar (tar.gz). Originally I was planning to loop through the array and add each item to the tar, something like that:

tar czf my_app.tar.gz

for app_item in "${app_items[@]}"
tar rzf my_app.tar.gz $app_item

Running the script I have found that I cannot add files to the compressed tar. I was wondering whether there is any other way of creating a tar from my list of location in the array.

Any help would be greatly appreciated!


The problem only exists with compressed archives. I propose to create and use an uncompressed archive first and compress it later when the loop has been run through.

tar cf my_app.tar --files-from /dev/null
for app_item in "${app_items[@]}"
    tar rf my_app.tar "$app_item"
gzip my_app.tar

As @Matthias pointed out in a comment, creating an empty archive (what we want in the first line) is typically refused by tar. To force it to do this, we need a trick which differs from operating system to operating system:

  • BSD: tar cf empty.tar --from-file /dev/null
  • GNU (Linux): tar cvf empty.tar --files-from /dev/null
  • Solaris: tar cvf empty.tar -I /dev/null

More details about this explains the page he linked to.