Backup Directories and Subdirectories Preserving File Structure

I needed a quick way to backup my small music collection on my laptop and preserve the complete file structure and permissions.  There are a few ways to do this of course…for example, you can just copy the files using whatever file manager you happen to be using in your Linux distribution.  In some cases though, you might want your backup to take up less space than the full monty.  Especially true if you are backing up to thumb drives!

You can use the tar command to make this a snap.

Tar combines multiple files into an archive and you can use it to preserve permissions and file structure and then you can compress the archive to save space.

tar -c --recursion -p --file=backup.tar directory

The -c flag creates an archive for us.  –recursion goes through all subdirectories.  The -p flag preserves permissions on all the files.  This is handy if you have certain folders or files that you need to sticky with individual users or groups.  The –file flag is the option for outputting to a file name.  You can also add multiple directories that you’re zipping up like the following:

tar -c --recursion -p --file=backup.tar directory1 directory2 directory3

After you have the file output as backup.tar it’s time to compress it.  The most standard way to do this is to use the gzip command:

gzip backup.tar

This command will output backup.tar.gz to the current directory which will take up less space than that of a standard 1-to-1 copy.  There are many other flags and options that you can use with the tar command.  For an in depth look at those flags and options, check the tar man page by typing ‘man tar’ in a terminal or view it online here.


Commenter ‘jack’ has offered a few extra flags to combine the archiving and zipping into one command:

tar -c -z --recursion -p --file=backup.tar directory1 directory2 directory3

The -z flag will gzip the archive after you’ve used tar to create it.  Substituting -j in for -z above will bzip the archive.  Thanks for the tips jack!

This content is published under the Attribution-Noncommercial-Share Alike 3.0 Unported license.


devnet has been a project manager for a Fortune 500 company, a Unix administrator, a Technical Writer, and a System Analyst during his 10 years working with Technology.