Commands.page Logo

Compress Ubuntu Directory Preserving Symbolic Links

Managing file backups and transfers in Ubuntu often requires compressing folders to save space. A common challenge arises when directories contain symbolic links, as standard compression settings might copy the target files instead of the links themselves. This article explains how to compress a directory in Ubuntu using the tar utility while ensuring symbolic links remain intact within the archive.

Use Tar Without Dereferencing

The tar command is the standard tool for archiving files in Linux. By default, tar preserves symbolic links as links. You must avoid using the -h or --dereference flag, which tells tar to follow the links and archive the actual files they point to.

To create a compressed archive while keeping symlinks, run the following command in your terminal:

tar -czvf archive_name.tar.gz /path/to/directory

In this command: * -c: Creates a new archive. * -z: Compresses the archive using gzip. * -v: Verbose output, showing files as they are processed. * -f: Specifies the filename of the archive.

Extracting the Archive

When you extract the archive on the same or a different system, the symbolic links will be restored exactly as they were. Use the following command to extract the contents:

tar -xzvf archive_name.tar.gz

After extraction, you should verify that the links were preserved correctly. Use the ls -l command to list the files and check the arrow notation indicating a symlink.

ls -l /path/to/extracted/directory

If you see -> pointing to the target path instead of a full file size, the symbolic link was preserved successfully. Avoid adding the -h flag during creation if your goal is to maintain the link structure rather than duplicating large target files.