Last Updated on September 27, 2015 by admin
In the following post, I will show you several examples on how to create a tar gz file while preserving file permissions and ownerships of the archived files.
Create tar.gz command
Here is the tar command that has to be run on the shell. I will explain the command line options below.
tar pczf myarchive.tar.gz /home/till/mydocuments
This command creates the archive myarchive.tar.gz which contains the files and folders from the path /home/till/mydocuments.
The command line options explained:
- [p] This option stand for "preserve", it instructs tar to store details on file owner and file permissions in the archive.
- [c] Stands for create. This option is mandatory when a file is created.
- [z] The z option enables gzip compression.
- [f] The file option tells tar to create an archive file. Tar will send the output to stdout if this option is omitted.
Tar command examples
Example 1: Backup the /etc Directory
Create a backup of the /etc config directory. The backup is stored in the root folder.
tar pczvf /root/etc.tar.gz /etc
The command should be run as root to ensure that all files in /etc are included in the backup.
This time I've added the [v] option in the command. This option stands for verbose, it tells tar to show all file names that get added into the archive.
Example 2: Backup your /home directory
Create a backup of your home directory. The backup will be stored in a directory /backup.
tar czf /backup/myuser.tar.gz /home/myuser
Replace myuser with your username. In this command, I've omitted the [p] switch, so the permissions get not preserved.
Example 3: A file-based backup of MySQL databases
The MySQL databases are stored in /var/lib/mysql on most Linux distributions. You can check that with the command:
Stop the database server to get a consistent MySQL file backup with tar. The backup will be written to the /backup folder.
1) Create the backup folder
mkdir /backup chmod 600 /backup
2) Stop MySQL, run the backup with tar and start the database server again.
service mysql stop tar pczf /backup/mysql.tar.gz /var/lib/mysql service mysql start ls -lah /backup