Backup Home Directory In Linux Using Tar

Share on FacebookShare on Google+Tweet about this on TwitterPin on PinterestShare on RedditPrint this page

The tar command in Linux can quickly create archives of entire directories. All of this can be done just with a single command.

Here is how :

Suppose, the home directory of a user needs to be archived for backup purposes. This directory and all the sub-directories can be “tarred” by the following command :

tar -zcvf homedirarchive.tar.gz /home/avp

compressed tar archive in linux

The above command will create an archive named homedirarchive.tar.gz and compress the specified folder and it’s contents (/home/avp).

Now, to restore the contents of this archive, the command will be :

tar -zxvf  homedirarchive.tar.gz

extracted tar file in linux

This will extract the contents of the specified archive in the folder where it is located.

Often, it can be useful to add timestamps to created archives automatically for backups or for reference.

Here is a simple shell script that does that :

#!/bin/sh

#Add timestamp

TS=$(date +"%F")

#Specify how the tar archive will be named

BKPNAME="homedir-$TS"

#Tar it
tar -zcvf "$BKPNAME.tar.gz" /home/avp

Save the script as maketar.sh and make it executable :

chmod a+x maketar.sh

Finally, run it :

./maketar.sh

timestamped tar archive using linux shell script

The archive created with this script will have the day, month and year timestamp.

Also, as with all command line utilities, the various ways tar command can be used can be found out using the “man” command :

man tar

tar manual in linux

So any specific folder can be compressed by this small but very powerful command.

Happy Tar-ing!

Comments are closed.