Archiving Commands in Unix
I'll introduce two commonly used archiving commands in Unix-like operating systems: zip and tar. These commands are essential for compressing files and directories, making it easier to store and transfer them.
Zip Command Syntax
zip [options] [filename.zip] [file_to_zip]
Options
| Options | Description | Syntax |
|---|---|---|
-r | Recursively zip a directory | zip -r [filename.zip] [dir_name] |
-x | Explicitly exclude the specified files | zip -r [filename.zip] [dir_name] -x [excluded_file] |
-m | Move the original files into the archive | zip -m [filename.zip] [file_to_zip] |
Examples
-
Zipping files
zip archive.zip file1.txt file2.txt -
Zipping a directory while excluding some subdirectories
zip -r archive.zip . -x "node_modules/*"For a large number of exclusions, a file can be used to list the patterns.
zip -r archive.zip . -x @exclude.lstIn this case,
exclude.lstwould contain one pattern per line, and zip would exclude files matching those patterns. -
Zipping files and moving them into the archive
zip -m documents.zip *.txt
Tar Command Syntax
tar [options] [archive_name.tar] [file_to_archive]
Options
The -f option is mandatory to specify the archive file name. Without it, tar will try to write this archive to the default output device (typically /dev/rmt0 or standard output)
| Options | Description | Syntax |
|---|---|---|
-c | Create a new archive | tar -cf [archive_name.tar] [file_to_archive] |
-z | Compress with gzip | tar -czf [archive_name.tar.gz] [file_to_archive] |
-x | Extract files | tar -xf [archive_name.tar] |
-v | Verbose output | tar -xvf [archive_name.tar] |
-C | Change to [directory] before performing operations | tar -C [directory] -xzf [archive_name.tar.gz] |
Combining options or skipping dash is common, e.g.
tar Cxzf output_dir archive.tar.gzis the same astar -C output_dir -xzf archive.tar.gz
Examples
-
Create a new
.tar.gzarchivetar -czf archive.tar.gz file1.txt file2.txt -
Extract a
.tar.gzarchivetar -xzf archive.tar.gzOr, extract specific files (file1.txt and file2.txt) from the archive:
tar -xzf archive.tar.gz file1.txt file2.txt
Browsing Archive Files
To browse the contents of a zip, tar, or tar.gz file using Vim or Neovim, you can simply open the them with either editor. These editors have built-in support for browsing zip archives.
# e.g.
vim filename.zip
nvim filename.tar.gz