Search code examples
cmdziptar

Tar.exe can't add 2 files from different folders


I am trying to add 2 different files to a zip-archive using tar.exe. The folder structure is as follows:

  • RootFolder
    • SubDirectory1
      • File1.txt
    • SubDirectory2
      • SubDirectory3
        • File2.txt
    • SubDirectory4
      • File3.txt
      • File4.txt

I'd like to add File1, File2 and all Files of SubDirectory4 to the archive with relative paths.

The command which I am using is while the current directory is RootFolder:
tar.exe -cf archive.zip -C SubDirectory1 File1.txt -C SubDirectory2\SubDirectory3 File2.txt SubDirectory4

After executing it gives the following error: tar.exe: could not chdir to 'SubDirectory2\SubDirectory3'
I couldn't find similiar problems or neither was the documentation of the -C flag good enough for me to understand the problem. Does anyone have an idea why it doesnt work?


Solution

  • When you cd'd into SubDirectory1 that became the current directory within the command, so in order to cd into SubDirectory3\Subdirectory4 you need to make that relative to SubDirectory1 not the original directory. Then when you cd into SubDirectory4, that will need to be relative to SubDirectory3.

    Given the above, and with RootFolder as your current directory, try this instead:

    %SystemRoot%\System32\tar.exe -cf "archive.zip" -C ".\SubDirectory1" "File1.txt" -C "..\SubDirectory2\SubDirectory3" "File2.txt" -C "..\..\SubDirectory4" "File3.txt" "File4.txt"
    

    If you wanted the entire content of SubDirectory4 then change the last glob accordingly:

    %SystemRoot%\System32\tar.exe -cf "archive.zip" -C ".\SubDirectory1" "File1.txt" -C "..\SubDirectory2\SubDirectory3" "File2.txt" -C "..\..\SubDirectory4" "*"
    

    I have used double-quotes here as best practice, although in the case of the provided file and directory names you've used, those can be omitted if preferred. I have also used the full path and extension to the default Windows 10 version of tar.exe, if you do not care about robust code, and wish to gamble that the %Path% and %PATHEXT% variables have not been corrupted, then feel free to change %SystemRoot%\System32\tar.exe to tar.