How to compress, move, and extract a directory – Bash one-liner

The other day I needed to migrate a directory containing a lot of files from one location on my Linux server to another. There are a number of ways I could do this. Using a simple cp command could have done the trick. However, as the data I was copying was a database and I wanted to make sure that the copying was done perfectly, I looked on the Internet and found a brilliant one line bash solution for this.

I wanted to move the contents of the directory /var/lib/mysql to /opt/mysql. First I changed to the directory /var/lib/mysql:

# cd /var/lib/mysql

Then I ran the following one liner to do the magic for me.

# tar cf – * | ( cd /opt/mysql; tar xfp -)

I used the command shown above to copy my database files. What it does is it compresses the entire contents of the current directory, changes to the location of the destination directory (/opt/mysql in this case), and then extracts the archive.

g33kadmin

I am a g33k, Linux blogger, developer, student and Tech Writer for Liquidweb.com/kb. My passion for all things tech drives my hunt for all the coolz. I often need a vacation after I get back from vacation....

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.