Posts

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

OptionsDescriptionSyntax
-rRecursively zip a directoryzip -r [filename.zip] [dir_name]
-xExplicitly exclude the specified fileszip -r [filename.zip] [dir_name] -x [excluded_file]
-mMove the original files into the archivezip -m [filename.zip] [file_to_zip]

Examples

  1. Zipping files

    zip archive.zip file1.txt file2.txt
    
  2. 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.lst
    

    In this case, exclude.lst would contain one pattern per line, and zip would exclude files matching those patterns.

  3. 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)

OptionsDescriptionSyntax
-cCreate a new archivetar -cf [archive_name.tar] [file_to_archive]
-zCompress with gziptar -czf [archive_name.tar.gz] [file_to_archive]
-xExtract filestar -xf [archive_name.tar]
-vVerbose outputtar -xvf [archive_name.tar]
-CChange to [directory] before performing operationstar -C [directory] -xzf [archive_name.tar.gz]

Combining options or skipping dash is common, e.g. tar Cxzf output_dir archive.tar.gz is the same as tar -C output_dir -xzf archive.tar.gz

Examples

  1. Create a new .tar.gz archive

    tar -czf archive.tar.gz file1.txt file2.txt
    
  2. Extract a .tar.gz archive

    tar -xzf archive.tar.gz
    

    Or, 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