Q1What happens when you run tar -cf docs.tar docs?
tar — Archive and Extract
Bundle multiple files into a single uncompressed archive with tar -cf docs.tar docs, list its contents with tar -tf docs.tar, and restore them with tar -xf — illustrated and run hands-on in a browser terminal.
Bundle and List — tar -cf / tar -tf
tar bundles several files or directories into a single file. That single file is called a tar archive, conventionally named with a .tar extension. You bundle with tar -cf archive.tar target and check the contents with tar -tf archive.tar. -c means create, -t means list, and -f specifies the file name.
| Syntax | Effect |
|---|---|
tar -cf a.tar dir | Bundle dir into a single a.tar |
tar -tf a.tar | List the contents (files) inside a.tar |
tar -xf a.tar | Extract a.tar back into the original files |
tar -xf a.tar -C dest | Set the extraction target directory to dest |
tar -cf d.tar d bundles d into a single d.tar, and tar -tf d.tar lists the included files without extracting them.mkdir -p docs # Create the source directory
printf 'note A\n' > docs/a.txt # Put two files inside
printf 'note B\n' > docs/b.txt
tar -cf docs.tar docs # Bundle docs into docs.tar
tar -tf docs.tar # List docs/ docs/a.txt docs/b.txt
# On a production server, tar -czf docs.tar.gz docs also gzips while bundling (this learning environment is uncompressed only)
This course learns tar with uncompressed archives
gzip compression such as tar -czf works on production servers like Ubuntu. This course learns how tar works with the uncompressed -cf / -tf / -xf (please don't run compression in this learning environment).
Extract — tar -xf and -C
To pull the original files back out of a tar archive, use tar -xf archive.tar. -x means extract. Run it as-is and it extracts into the current directory, but adding -C target extracts into the directory you specify. After extracting, check the pulled-out files with ls.
tar -xf docs.tar extracts into the current directory, while tar -xf docs.tar -C out extracts into out by specifying the target.mkdir -p pack # Create the source directory
printf 'x\n' > pack/a.txt # Put a file inside
tar -cf pack.tar pack # Bundle pack into pack.tar
mkdir -p out # Prepare the extraction target
tar -xf pack.tar -C out # Extract into out/
ls out # out/pack has been extracted
Knowledge Check
Answer each question one by one.
Q2Which command lists the contents of a docs.tar archive without extracting it?
Q3In tar -xf pack.tar -C out, what does -C out specify?