Figure 1. Directory tree

Some Linux-commands for work with archives from command line. In this tutorial we have this structure (Figure 1 and Figure 2): /home/alexey/Documents/mydir/ - is a directory for adding to archive.

Figure 1. Directory tree

Figure 1. Directory tree

Figure 2. Files for adding to archive

Figure 2. Files for adding to archive

Packing files

tar -zcvfC md.tar.gz  /home/alexey/Documents/mydir/


If we execute this while we are in root dir, we'll get the error (of course if we didn't use sudo):

tar (child): md.tar.gz: Cannot open: Permission denied

tar (child): Error is not recoverable: exiting now


So at first change your directory where your new file should be stored, for example:

cd /home/alexey/Documents/


If we open  md.tar.gz in Midnight commander, we can see that it has full directory structure:



Each of directories 'home', 'alexey' and 'Documents' has only one child folder and inside 'mydir' you can see files.


Of course, you don't always want to copy your structure, for example, if you want to upload your archive to a public storage. Then you want to add to archive only directories you want to. Then I can advice you the command like this:


cd /home/alexey/Documents/ && tar -zcvf  md.tar.gz mydir/


It consists of 2 parts -  'cd /home/alexey/Documents/' and 'tar -zcvf  md.tar.gz mydir/'. In the first part you change your current directory to the nearest to which you want to add to archive, and in the second one you enter relative path to your dir. If you open the archive, you can see that start directory is 'mydir'.


Move tar archive to a specific directory

To move file to a specific directory you should use mv command. It' syntax is like 'mv source dest':

mv md.tar.gz -t  new_directory/


If  new_directory doesn't exist, use combo with 'mkdir':

mkdir -p new_directory && mv md.tar.gz -t new_directory/


The key '-p' with 'mkdir' allows not to get error if directory already exists.


Extract tar archive

The simplest – extract to current directory:

tar -zxvf md.tar.gz


Extract to specific directory:

 mkdir -p ../newdir/ && tar -zxvf md.tar.gz -C ../newdir/


Directory 'newdir' that is level up to current will be created if it doesn't exist.

If you open 'newdir', you can see that there's a directory 'mydir' and files and another directory inside. But if you want to move all the content from 'mydir' to level up ('newdir') folder, you can use this command: 

mv * ../


Don't forget to remove directory 'mydir'

rm mydir