Skip to main content
added 700 characters in body
Source Link
Stewart
  • 16k
  • 5
  • 49
  • 101

Alternatively, you didn't need to pack the whole directory. This would have also worked. I also added test2.txt to show the whole directory isn't unpacked.

$ cd $(mktemp -d)                 # New directory
$ touch test.txt test2.txt        # Let's make a few files
$ tar -cf playground.tar *.txt    # Pack everything
$ tar -tf playground.tar          # What's in the archive?
test2.txt
test.txt                          # Look: No directory!
$ rm *.txt                        # Clear the source files to test unpacking
$ tar -xf playground.tar test.txt # Unpack one file (no directory name)
$ find .
.
./test.txt
./playground.tar                  # There it is!

Alternatively, you didn't need to pack the whole directory. This would have also worked. I also added test2.txt to show the whole directory isn't unpacked.

$ cd $(mktemp -d)                 # New directory
$ touch test.txt test2.txt        # Let's make a few files
$ tar -cf playground.tar *.txt    # Pack everything
$ tar -tf playground.tar          # What's in the archive?
test2.txt
test.txt                          # Look: No directory!
$ rm *.txt                        # Clear the source files to test unpacking
$ tar -xf playground.tar test.txt # Unpack one file (no directory name)
$ find .
.
./test.txt
./playground.tar                  # There it is!
Source Link
Stewart
  • 16k
  • 5
  • 49
  • 101

You need to specify the whole path:

tar -xf playground.tar playground/test.txt

You can use tar --list or tar -t to list the contents of an archive to see what's in there:

$ tar -tf playground.tar
playground/
playground/text.txt

Here's a complete log of what I did to reproduce your issue:

$ cd $(mktemp -d)                              # Go to a new empty directory
$ mkdir playground
$ touch playground/test.txt                    # Make the file we will tar

$ tar cf playground.tar playground             # Make the tar
$ tar -tf playground.tar                       # List the contents of a tar
playground/
playground/test.txt                            # There's our file! It has a full path

$ rm -r playground                             # Let's delete the source so we can test extraction
$ tar -xf playground.tar playground/test.txt   # Extract that file
$ find .                                       # Check if the file is now there
.
./playground.tar
./playground
./playground/text.txt                          # Here it is!