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 combine the entire contents of the current directory to one archive file, changes to the location of the destination directory (/opt/mysql in this case), and then extracts the archive. Before you move on, be sure to check out the other things you can do with tar :)