Remove parent directories from tar archives
You run a Linux web server, and have painstakingly crafted custom backup processes for all your important data. Undoubtedly, the backup copies end up being stored in the form of a tar archive. Everything works great – copies are made, compressed, and sent off-site. There’s just one naggy little issue: whenever you open one of those tar backups, it includes the entire directory tree above the folder you actually need.
This problem always drove me nuts when creating MySQL database backups. I want to make a tar backup of
/var/lib/mysql/database_name and call it
database_name.tar.gz. If I then unpack the tar under
/root, I’ll have a bunch of worthless subfolders to drill down through:
/root<strong color="red">/var/lib/mysql/**database_name. All I really want is the
database_name folder, the
/var/lib/mysql/ parent directories can all go away.
Here’s how to get rid of those pesky parent folders once and for all. Before running your tar command, you must first use
cd to move into the parent directory that contains the folder you want. Then, within your call to tar, leave the parent folders off your target files/folders.
Here’s the command sequence for previous example:
cd /var/lib/mysql tar -czf /any/folder/you/want/database_name.tar.gz database_name
The resulting file will unpack directly into a single subfolder called
If you run your tar process as part of a larger scripting event, your script might not run/maintain a shell interface. In these cases, the
cd command will be executed in a vacuum, and won’t have any effect. I run into this problem when I try to perform shell magic inside of PHP scripts.
Fortunately, there’s an easy workaround: you can append multiple shell commands together using
&&, each command will be executed and completed before the next one begins, mimicking a person typing out commands one line at a time.
Here’s what our MySQL example looks like as a single line:
cd /var/lib/mysql && tar -czf /any/folder/you/want/database_name.tar.gz database_name
Enjoy your tar backups sans worthless parent directories!
comments powered by Disqus