Search code examples
bashshellarchivetar

Tar files from different directories without paths


I have a following structure:

-folder1
   -folder2
     -file1
     -file2
   -folder3
     -folder4
       -folder5
         -file3
         -file4

Using bash I need to create a .tar archive in the actual directory, which will contain 4 files(file1,file2,file3,file4). Everything that I've tried makes an archive of files with their paths. What I need is an archive of just files, which must contain:

file1
file2
file3
file4

Solution

  • If you know the filenames and their directories you can use the -C/--directory option to have tar change its operating directory as it processes arguments.

    So this command:

    tar -cf files.tar.gz -C folder1/folder2 file1 file2 -C ../folder3/folder4 file3 file4
    

    will create files.tar.gz in the current directory with just the files in it.

    You can automate creating the necessary command line arguments from find output or similar with a little bit of scripting if necessary.

    (You can't use globs like folder1/folder2/* in the file argument positions because the paths in those filenames will cause tar to fail to find them. You can use $(ls folder1/folder2/) in that position but that's obviously not safe for many valid filenames.)