ARTICLE - Cloud Servers

Ways to Batch Compress Folders in Linux

Use a for loop in Linux to compress every folder in the current directory into a zip file with the same name, or use tar to package multiple folders into one archive. This article covers both common batch compression approaches.

2023-04-03 cnblogs.com (CQZHUOMI)

Ways to Batch Compress Folders in Linux

Imagine you just migrated a stack of site directories to a new machine. Under /var/www sit a dozen project folders — blog, shop, crm, docs — and each one needs to be archived into a compressed package, or bundled together to hand off to a teammate. Running zip -r by hand for each one is not realistic, and that is exactly when loops and pipelines earn their keep. This article covers several practical ways to batch-compress folders in Linux, split into "one archive per folder" and "everything into one archive".

Two approaches at a glance

Need Tool Output Best for
Each folder as its own archive zip + for loop xxx.zip Archiving, download mirrors, per-directory distribution
Many folders merged into one archive tar xxx.tar.gz Whole-site migration, backups, sharing with colleagues
Only folders with a given prefix zip + wildcard / find same-named zip Processing a subset of directories

The division of labour is clear: zip suits "compress each directory on its own", while tar suits "keep the directory structure and package everything together". If zip is not installed, install it with apt install zip on Debian/Ubuntu or yum install zip on CentOS/RHEL.

Method 1: Compress every folder in the current directory to a same-named zip

for i in `ls -1`; do zip -r $i.zip $i; done

In Bash this produces a zip named after each entry: blog becomes blog.zip, shop becomes shop.zip. The idea is straightforward, but there are two traps:

  1. ls -1 also lists regular files, so if you only meant to compress folders, you end up with a pile of unexpected archives mixed in;
  2. Names containing spaces or special characters get split on whitespace, producing broken archives or wrong filenames.

A more robust version uses a glob that only matches directories, with nullglob enabled so the loop does not error when nothing matches:

shopt -s nullglob
for d in */; do zip -r "${d%/}.zip" "$d"; done

*/ matches directories only, ${d%/} strips the trailing slash, and the quotes keep names with spaces intact. On a directory with 30 subfolders totalling about 40GB, a single-threaded zip can take anywhere from a few minutes to well over ten, depending on disk and CPU; if speed matters, switch to 7z a -t7z or parallel compression with pigz.

Method 2: Package multiple folders into a single archive

tar -zcvf backup-2026-08-07.tar.gz blog shop docs

-z compresses with gzip, -c creates a new archive, -v prints each file as it is processed, and -f names the output. Unlike the zip loop, tar tucks several directories into one archive while preserving relative paths, which is ideal for whole-site migration or date-based archiving:

tar -zcvf /backup/www-$(date +%F).tar.gz -C /var/www blog shop docs

The -C flag changes directory before packing, so the archive does not carry the leading /var/www path segment and can be extracted anywhere more cleanly. To pull out just one directory later, run tar -xzf backup.tar.gz blog.

Method 3: Compress only folders with a given prefix

The most common batch scenario is "handle only part of the tree". For example, to compress directories starting with ab:

for i in ab*; do zip -r "$i.zip" "$i"; done

Or combine both conditions — "is a directory AND matches the name" — in a single find command:

find . -maxdepth 1 -type d -name "ab*" -exec zip -r {}.zip {} \;

-maxdepth 1 limits the search to the current level so subdirectories are not re-archived; -exec ... {} runs zip once per matched directory. This form is more flexible than a glob when you have many directories or need to exclude certain names.

A practical script: dated batch archiving with a log

Combine the approaches above into a small, repeatable script with a date stamp, then drop it into crontab for scheduled archiving:

#!/bin/bash
# Batch archive every subdirectory under /var/www to /backup, dated, with a log
shopt -s nullglob
out=/backup/archive-$(date +%F)
mkdir -p "$out"
log=$out/archive.log
for d in /var/www/*/; do
  name=${d%/}; name=${name##*/}
  tar -zcf "$out/$name.tar.gz" -C /var/www "$name"
  echo "$(date +%T) done $name" >> "$log"
done
echo "total $(ls "$out"/*.tar.gz 2>/dev/null | wc -l) archives" >> "$log"

Two notes: ${name##*/} extracts the plain directory name from the full path, and 2>/dev/null suppresses the ls error when the output directory is empty. The tar -zcf drops -v so the log does not get flooded; on the first run, keep -v and watch the output once to confirm nothing is missing. Once the script is wired into crontab, combined with the server backup strategy, it gives you a closed loop of "auto-archive + periodic cleanup", with a log to trace which run failed and when.

  • Permissions or timestamps lost after extraction: zip does not preserve Unix permission bits by default; prefer tar for archival use.
  • Symlinks copied as their targets: zip follows symlinks by default; pass -y to keep the links themselves.
  • How to verify the result: validate archives with unzip -t blog.zip or tar -tzf backup.tar.gz | wc -l; for archival jobs, wrap the run in a script and record the checksum.
  • Disk space: when the archives and the source live on the same disk, leave at least as much free space as the source size, or the job may fill the partition halfway through.
  • Compression ratio too low: gzip defaults to compression level 6; for a smaller result, request level 9 explicitly (e.g. tar -zcf --use-compress-program='gzip -9'), or switch to xz with parallel cores to trade time for size.

Batch compression is a routine file-management task. Combined with the cloud servers category, such as server operations tips and Linux server basics, it forms a complete daily operations workflow. For the symmetric operation of bulk extraction, see bulk unzip on CentOS.

Reference: the man zip and man tar pages cover both tools, and the GNU tar manual is at https://www.gnu.org/software/tar/manual/.
Original post: https://www.cnblogs.com/cqzhuomi/articles/17284350.html (cnblogs.com CQZHUOMI, repost)

Integration & Code Examples

Example 1: Batch archive with tar and zstd, keeping the directory layout

#!/usr/bin/env bash
set -euo pipefail

src=/data/sites
dst=/backup/2026-11
mkdir -p "$dst"

for d in "$src"/*/; do
  name=$(basename "$d")
  tar --use-compress-program='zstd -T0' \
      -cf "$dst/$name.tar.zst" -C "$src" "$name"
  echo "packed $name"
done

Using -C "$src" "$name" instead of absolute paths keeps the archive from extracting the whole /data/sites/... tree, and -T0 lets zstd use every core.

Example 2: Parallel runs plus an integrity check

mkdir -p /backup/today

# only directories touched in the last 7 days; -print0/-0 survive spaces in names
find /data/sites -mindepth 1 -maxdepth 1 -type d -mtime -7 -print0 \
  | xargs -0 -P 4 -I{} sh -c '
      n=$(basename "{}")
      tar --use-compress-program="zstd -T0 -19" -cf "/backup/today/$n.tar.zst" -C /data/sites "$n"
      echo "done $n"'

# verify: zstd -t checks integrity without extracting
zstd -t /backup/today/*.tar.zst

-P 4 is the number of parallel processes, not threads: match it to your core count, because pairing a high level like -19 with all cores usually makes IO the bottleneck anyway.

Output Shapes and Tool Choice for Batch Archiving

Choose by output shape first, then by whether Unix permission bits and timestamps must survive. zip suits one package per directory that can be handed out separately; tar suits several directories packed into one archive with the tree preserved; zstd and pigz address speed and still sit behind tar or zip.

The differences are in the details: zip does not keep Unix permission bits by default, so software directories and executables change permissions after archiving, which makes tar the better choice for archiving; find with -maxdepth 1 keeps the job at the current level; names containing spaces need -print0 with xargs -0 rather than output from ls -1.

Tool Output shape Permissions and timestamps Parallelism When it fits
zip with a glob loop One xxx.zip per directory Permission bits dropped by default; -y keeps symlinks Single process Per-directory distribution, download archives
tar -zcf Several directories in one xxx.tar.gz Tree and permissions preserved Single-process gzip Whole-site migration, dated archives
tar with zstd -T0 One .tar.zst Preserved Multi-core compression Large data where the window matters
find with -exec One package per match Depends on the tool called Parallel via xargs -P Prefix or time-based subsets

Estimating Runtime at the 40GB Scale and Setting Parallelism

The reference in this article: a directory with 30 subdirectories and about 40GB of data takes roughly a few minutes to a dozen minutes with single-threaded zip, depending on disk and CPU. At that scale the bottleneck is usually disk I/O rather than the algorithm, so check whether the device is saturated before adding parallelism.

Parallelism has two controls: zstd -T0 lets the compressor use every core, while xargs -P 4 sets how many packaging processes run at once. Watch the machine's baseline when stacking them — setting -P near the core count is enough, and combining a high compression level such as -19 with all cores tends to turn I/O into the bottleneck and lengthen total runtime.

When the archive lands on the same disk as the source, keep headroom close to the source directory's size or the partition fills up mid-write. After archiving, verify with zstd -t or unzip -t and write the result into the log instead of relying on a directory listing later.

Limitations

  • This form is more flexible than a glob when you have many directories or need to exclude certain names.
  • The tar -zcf drops -v so the log does not get flooded; on the first run, keep -v and watch the output once to confirm nothing is missing.
  • Figures reflect public information at publication; terms, prices and quotas follow the provider's current published terms.

FAQ

Which is better: per-folder archives or one tarball?

Choose by output shape. Use zip with a for loop when each folder needs its own archive; use tar when several folders go into one file. tar keeps Unix permissions and timestamps that zip drops by default, so pick tar for archival work such as the 40GB tree here and zip for per-directory distribution.

Which packages does the zip loop require?

Install zip with apt on Debian, yum on RHEL. Packing needs nothing else; for a higher ratio add zstd and run tar --use-compress-program='zstd -T0' so every core is used. Test the flags on a small directory before pointing them at production data, and check free space first.

How long does packing 40GB take?

Expect a few minutes to about fifteen for that tree. Disk and CPU set the ceiling: zstd -T0 with four xargs workers cuts it down, while -19 pushes you back into an IO bottleneck on spinning disks. Keep -v on the first run and read the output once.

When shouldn't you loop over ls output?

Avoid it when names may contain spaces, because word splitting breaks the archive names. Use for d in */ with nullglob and quotes instead. If you also need plain files, mtime filters or exclusions, go straight to find -print0 piped into xargs -0, and dry-run the pipeline on one folder first.

Related Providers

  • AWS EC2: when archive tarballs land on EBS volumes and snapshots are the retention mechanism.
  • Alibaba Cloud ECS: when site data under /var/www already sits on Alibaba Cloud disks and archives must stay in the same region.
  • Hetzner: when cold archives are large enough that HDD-backed plans lower the cost per TB.

Community & Resources

Official docs and communities

  • tar(1) — -C, --use-compress-program and friends
  • zstd(1) — compression levels and multithreading flags
  • find(1) — -mtime, -print0 and depth control
  • xargs(1) — the correct use of -0 and -P

Learning resources and tools

Original source: cnblogs.com (CQZHUOMI) ↗