Can I use the tar command to change directories and use a wildcard file pattern?

Here is what I am trying to do:

tar -cf example.tar -C /path/to/file *.xml

It works if I don't change directory (-C), but I'm trying avoid absolute paths in the tar file.

tar -cf example.tar /path/to/file/*.xml

Here are some of the other attempts I've made:

tar -cf example.tar -C /path/to/file *.xml
tar -cf example.tar -C /path/to/file/ *.xml
tar -cf example.tar -C /path/to/file/ ./*.xml
tar -cf example.tar -C /path/to/file "*.xml"

And this is the error I get:

tar: *.xml: Cannot stat: No such file or directory

I know there are other ways ways to make this work (using find, xargs, etc.) but I was hoping to do this with just the tar command.

Any ideas?


The problem is, the *.xml gets interpreted by the shell, not by tar. Therefore the xml files that it finds (if any) are in the directory you ran the tar command in.

You would have to use a multi-stage operation (maybe involving pipes) to select the files you want and then tar them.

The easiest way would just be to cd into the directory where the files are:

$ (cd /path/to/file && tar -cf /path/to/example.tar *.xml)

should work.

The brackets group the commands together, so when they have finished you will still be in your original directory. The && means the tar will only run if the initial cd was successful.


In one of your attempts:

tar -cf example.tar -C /path/to/file "*.xml"

the * character is indeed passed to tar. The problem, however, is that tar only supports wildcard matching on the names of members of an archive. So, while you can use wildcards when extracting or listing members from an archive, you cannot use wildcards when you are creating an archive.

In such situations often I resort to find (like you mentioned already). If you have GNU find, it has the nice option to print only the relative path, using the -printf option:

find '/path/to/file' -maxdepth 1 -name '*.xml' -printf '%P\0' \
| tar --null -C '/path/to/file' --files-from=- -cf 'example.tar'

The accepted answer assumes the files are taken from a single directory. If you use multiple -C options, then you need a more general approach. The following command has the shell expand the file names, which are then passed to tar.

tar -cf example.tar -C /path/to/file $(cd /path/to/file ; echo *.xml)
  • 1
    I was looking for a multiple directory cmd, it works perfectly, thanks ! And just add to append extension if we also want multiple extensions, like echo *.xml *.txt – 1ronmat Mar 11 at 11:17

Try the command

tar -cvf *.xml example.tar  

It should work without any issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.