tar all the files under a directory on linux

Tags: , ,

We often need to tar all the files under a directory into a zip file.  This post gives two examples to show how to tar all the contents under a directory into a tgz file. 

Suppose we have directory structures like

By running the following command, we can tar all the files of my_folder into the tgz file.

However, you will find that you actually include the my_folder in the zip file. The structure of the tgz file will looks like this.

What if you want the file structures like this:

Two methods tar all the files under a directory into a tgz  file

You can use the following command to include only the files under my_folder to the zip file:

Using the -C option to tar all the files under a directory into a tgz file

You can also using the -C option to include all the files under your directory into a zip file:

The -C my_folder tells tar to change the current directory to my_folder, and then .means “add the entire current directory”.  The hidden files and sub-directories are included. 

Make sure  -C my_folder  is before  . , otherwise,  you’ll get the files in the current directory.