tar all the files under a directory on linux
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
1 2 3 4 |
my_folder --- file1 --- file2 --- file3 |
By running the following command, we can tar all the files of my_folder into the tgz file.
1 |
tar -czvf my_folder.tgz my_folder |
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.
1 2 3 4 5 |
my_folder --- file1 --- file2 --- file3 |
What if you want the file structures like this:
1 2 3 |
file1 file2 </code>file3 |
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:
1 2 3 4 5 6 7 8 |
cd my_folder tar -zcvf ../my_folder.tgz . cd .. or cd my_folder/ && tar -zcvf ../my_folder.tgz . && cd .. |
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:
1 2 |
tar -czvf my_folder.tar.gz -C my_folder . |
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.