I try to pack a .csv file with tar.gz, while being in the root directory.

The file myfile.csv is located at /mnt/sdb1/ So the full filename is /mnt/sdb1/myfile.csv

I try to save the tar.gz under /mnt/sdb1/old_files

I tried it like this:

tar -czf /mnt/sdb1/old_files/new.tar.gz mnt/sdb1/myfile.csv

But when i extract the file, then a folder with name "mnt" will be extracted which cointains another folder called "sdb1", which contains the file.

Is it possible to compress the file only, instead of copying all the directories?

3 Answers 3


use the --directory option from man tar :

-C,- -directory DIR

change to directory DIR


tar -C /mnt/sdb1/ -czf /mnt/sdb1/old_files/new.tar.gz myfile.csv
  • Thank you Fiximan! This solved the problem. I will upvote as soon i have 15 reputation.
    – Black
    Commented Jul 20, 2015 at 13:35

You have first to cd /mnt/sdb1, then launch the tar command.

FYI, you don't need to use tarhere as its purpose is to agglomerate several files in a tarball. Since you have only one file here, just use gzip.

  • I know, but i have to do it from the root directory, because i execute the command from a script.
    – Black
    Commented Jul 20, 2015 at 13:31
  • 1
    Man, so just add the cd command before tar, then you can go back, or use cd /mnt/sdb1 && tar -czf new.tar.gz myfile.csv && cd / if you prefer one line cmd.
    – McSinyx
    Commented Jul 20, 2015 at 13:37
  • @McSinyx The problem is that the directory is not saved, even when i execute cd /mnt/sdb1/ then i will be in the root directory again at the next execution of a command. But your second solution looks logical to me, i try it.
    – Black
    Commented Jul 20, 2015 at 13:41
  • @McSinyx NICE! It works :) Thank you, this will be VERY usefull!
    – Black
    Commented Jul 20, 2015 at 13:44
  • @EdwardBlack You can run a script from anywhere, just add the relevant absolute paths. In general, using relative paths is a bad idea as it can break things easily.
    – dr_
    Commented Jul 20, 2015 at 13:46

Use the -C option to tar:

   -C Directory
        Causes the tar command to perform a chdir subroutine to the
        directory specified by the Directory variable.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .