What I found interesting in relation to extraction is, that it depends how you created the archive, see this example
cd /tmp
mkdir folder
touch folder/file.txt
when you do tar -zcvf folder.tar.gz folder everything is as expected = when you untar it now it will be untarred (folder will be create, if you removed it) as /tmp/folder/.
But, when you will create tar as tar -zcvf tmp-folder.tar.gz /tmp/folder and you untar it in /tmp folder, the result will be /tmp/tmp/folder directory ! In such case you have to untar it to / - tar -xf tmp-folder.tar.gz -C /
To extract an archive to a directory different from the current, use the
-C
, or--directory
, tar option, as inNote that the target directory has to exist before running that command (it can be created by
mkdir /target/directory
).Read the manual page (command:
man tar
) for other options.Note that if your tarball already contains a directory name you want to change, add the
--strip-components=1
option:Combining the previous answers and comments:
To simply extract the contents and create target directory if it is missing:
To extract and also remove the root(first level) directory in the zip
Another option is to use --one-top-level. This will automatically create a directory based on the filename of the original.
Additionally if you want, you can specify your own and tar will create it automatically.
What I found interesting in relation to extraction is, that it depends how you created the archive, see this example
when you do
tar -zcvf folder.tar.gz folder
everything is as expected = when you untar it now it will be untarred (folder will be create, if you removed it) as/tmp/folder/
.But, when you will create tar as
tar -zcvf tmp-folder.tar.gz /tmp/folder
and you untar it in /tmp folder, the result will be/tmp/tmp/folder
directory ! In such case you have to untar it to / -tar -xf tmp-folder.tar.gz -C /