Commands.page Logo

Create Tar Archive Excluding Directory Itself in Ubuntu

Creating a tar archive on Ubuntu often includes the top-level directory name in the file paths, which can be inconvenient during extraction. This article explains how to use the tar command to archive only the contents of a directory, excluding the directory name itself from the archive structure.

When you run a standard tar command on a folder, the archive preserves the folder name as the root path. To avoid this, you must change the working directory before archiving the files. This ensures the archive contains only the files and subfolders inside, without the parent directory name.

Use the -C flag to change the directory context during the command execution. The syntax requires you to specify the path to the parent folder or the folder itself, followed by the dot . to represent all contents within it.

Run the following command in your terminal:

tar -cvf archive_name.tar -C /path/to/directory .

In this example, replace /path/to/directory with the actual path of the folder you want to archive. The -c flag creates a new archive, -v displays the progress verbosely, and -f specifies the filename. The -C option switches to the target directory before adding files, and the . tells tar to include everything inside that location.

When you extract this archive later, the files will appear directly in the current directory rather than inside a new folder matching the original directory name. This method is ideal for deploying code or sharing content where the specific folder structure name is not required.