Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

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.

share|improve this answer
Thanks for the great explanation. –  Nick C. Apr 4 '11 at 14:42
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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