Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am attempting to create a script that can compress files with a certain extension in a number of directories into a single tar-ball. Currently what I have in the script file is:

find "$rootDir" -name '*doc' -exec tar rvf docs.tar {} \;

Where $rootDir is the base path to search.

This is fine except the paths are absolute in the tar file. I would prefer the paths to be relative to $rootDir. How would I go about doing this?

Example of current tar -tf docs.tar where $rootDir is /home/username/test output:


What I desire the output to be:

share|improve this question
up vote 8 down vote accepted

If you run find from the desired root directory and don't specify an absolute starting point in find's options, it will output relative paths to the tar command invocations it constructs. Like so:

cd $rootDir
find . -name '*doc' -exec tar rvf docs.tar {} \;

If you do not want to change the current working directory permanently and are using bash or similar as your shell you could do

pushd $rootDir
find . -name '*doc' -exec tar rvf docs.tar {} \;


Note that pushd/popd are not present in all shells, so check the man page as appropriate. They are present in bash but not in the base sh implementation so while explicitly using /bin/bash you can rely on them you can't if a script asks for /bin/sh instead (as this may map to a smaller shell that doesn't have bash's enhancements)

share|improve this answer
Thanks. Worked brilliantly. Didn't realise linux had pushd/popd. – Shane Nov 12 '09 at 10:37
Or just use cd $rootDir and cd - (at least in bash). ( cd $rootDir ; find ... ) would also be possible, i.e. doing everything in a subshell. – Daniel Beck Mar 25 '13 at 19:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .