Nono.MA

Zip a Folder with Terminal

OCTOBER 15, 2020

To zip a folder and its content with Terminal you can use the zip command in the cli1, and here are a few other goodies you can use to simplify your workflow, making sure the folder is compressed properly, all subdirectories are compressed recursively, and the zip filename is automatically set using the current folder.

zip -qr9 ../$(basename "$PWD").zip *

Anatomy of a zip command

  • zip is the command that archives files and folders
  • -qr9 are the arguments for the command
    • -q (or "quiet operation") is the argument to zip silently, without listing the files that are being added (useful for not to clutter Terminal or notebook outputs)
    • -r (or "recurse into directories") is the argument to zip everything in the directory recursively, and not only files at the first level
    • -9 (or "compress better") is the argument to trade speed for compression, the operation will take longer to complete but the compression will be better, use -1 to "compress faster" or -0 to "store only," without compression
  • ../$(basename "$PWD").zip is the argument that defines the name of your zip file
    • ../ specifies the file should be one level up in the directory structure
    • basename is a command to obtain the folder or file name of a path
    • pwd is a command to obtain the current path of the Terminal (in our case the folder path)
    • .zip specifies the file extension
  • * is the argument of the files to compress, the asterisk is to zip everything in the current directory (and subdirectories due to the -r argument) - you could list individual files instead (say, file.txt file.json file.png) or multiple wildcards (say, *.txt *.json *.png)

  1. Command-line interface. 

CodeZipAutomation