ARTICLE - Cloud Servers

Ways to Batch Extract Multiple zip Files on CentOS

Batch extracting multiple zip files on CentOS can be done with xargs, find -exec, or a for loop. This article covers four batch extraction methods and how to overwrite-extract zip files with a given prefix.

2023-04-03 cnblogs.com (CQZHUOMI)

Ways to Batch Extract Multiple zip Files on CentOS

When you deploy websites on CentOS, the files you pull down from a backup center or object storage are often a pile of zip archives: theme packages, plugin packages, log archives, or a full-site backup from a given time window. Extracting them one by one is slow and easy to miss. This article rounds up four batch-extraction approaches covering scenarios from a few files to hundreds or thousands.

Before you start, confirm unzip is installed.

1. Install the Extraction Tools

yum install unzip -y

If you also need to extract rar files, install unrar as well:

yum install unrar -y

unzip is tiny and takes up almost no space, so it's worth having as a standard utility.

2. Enter the Directory Containing the Files

cd /path/to/zips

Then choose one of the methods below for your situation.

Method 1: Separate with Semicolons or && (suitable for a small number)

unzip a.zip && unzip b.zip && unzip c.zip

Or:

unzip a.zip; unzip b.zip; unzip c.zip

The difference: && only runs the next command if the previous one succeeded, so a corrupted archive stops the chain and alerts you to the problem; ; keeps going regardless of success or failure. With just three or five files, this is the most obvious approach.

Method 2: Use find with -exec

find . -name '*.zip' -exec unzip {} \;

This recursively finds all .zip files under the current directory and extracts them one by one — ideal when the archives are scattered across subdirectories. {} is find's placeholder, and \; runs the command once per result. If filenames may contain spaces, switch to find . -name '*.zip' -print0 | xargs -0 -n1 unzip -o instead.

Method 3: Use ls with xargs (recommended)

ls *.zip | xargs -n1 unzip -o
  • -n1: pass only one filename to unzip at a time (note that this is the number 1, not the letter l);
  • -o: extract in overwrite mode without prompting for confirmation.

To extract password-protected zip files, add the -P option:

ls *.zip | xargs -n1 unzip -o -P password

Note: putting a password directly on the command line leaves it in your shell history. Fine for quick one-offs, but prefer interactive input in production.

Method 4: Use a for Loop

for i in *.zip
do
    unzip -o $i
done

The advantage of a for loop is that you can add logic: create a directory before extracting, delete the source archive afterward, or count failures. Reach for it when you need flexibility.

Batch Extract Files with a Given Prefix

For example, to overwrite-extract all zip files starting with ab:

ls ab*.zip | xargs -n1 unzip -o

Summary

Scenario Recommended Command
Few files unzip a.zip && unzip b.zip
All zips in a directory find . -name '*.zip' -exec unzip {} \;
Overwrite-extract zips in the current directory ls *.zip | xargs -n1 unzip -o
Extract password-protected zips ls *.zip | xargs -n1 unzip -o -P password
Given prefix ls ab*.zip | xargs -n1 unzip -o

A Real-World Example

When you launch a new site, if the theme and plugins are all zip archives, a typical workflow looks like this:

cd /www/wwwroot/mysite/wp-content/themes
ls *.zip | xargs -n1 unzip -o
chown -R www:www /www/wwwroot

After extracting, fix the ownership in the same step so the site doesn't complain about unwritable directories. The same logic applies to log backups: extract to a temp directory first, verify integrity, then overwrite the live files — safer than extracting in place.

Extract to a Specified Directory

By default unzip writes files to the current directory, which can get tangled with the archive's internal folder structure. To collect everything in a target directory, use the -d option:

mkdir -p /www/wwwroot/uploads
ls *.zip | xargs -n1 unzip -o -d /www/wwwroot/uploads

Log and backup files then stay out of the current directory. Before a batch run, it's a good idea to extract one archive first to check its internal structure with unzip -l:

unzip -l a.zip | head -20

A Few Handy Options

Besides -o and -P, two more options get regular use:

  • -q: quiet mode — suppress per-file detail while extracting, so the terminal isn't flooded when processing hundreds of archives;
  • -n: extract only files that don't already exist in the target directory and skip the rest — handy for "topping up missing files" rather than overwriting everything.

You can also swap \; for + in the find -exec form, letting find hand multiple filenames to a single unzip process:

find . -name '*.zip' -exec unzip -o {} +

This reduces how many processes get spawned, which is noticeably faster when there are many archives.

Notes on Extracting Untrusted Files

Before extracting zips downloaded from the internet, watch out for path traversal (zip slip): a maliciously crafted archive can carry ../ entries that write files outside the target directory, even over system files. Run unzip -l first and inspect the entry paths; if any contain .., discard the whole archive. Get into this habit on production servers especially — a clobbered live directory costs far more than a slightly slower extraction.

Q: If one zip is corrupted during a batch run, does the process stop?
A: The find -exec and xargs approaches keep going with the remaining files; only the && chained method stops on error. To count failures after a batch, check exit codes in a for loop:

for i in *.zip; do
  if unzip -o "$i" > /dev/null 2>&1; then
    echo "OK: $i"
  else
    echo "FAIL: $i"
  fi
done

Q: What about filenames with spaces or Chinese characters?
A: find -print0 | xargs -0 handles paths with spaces reliably. If Chinese filenames come out garbled, it's usually a zip encoding issue — specify it with unzip -O gbk first.

Q: How do I check disk space before extracting?
A: Use du -ch *.zip | tail -1 for the total archive size, then compare with the free space from df -h. Heavily compressed log archives can expand severalfold, so don't blindly batch-extract when the disk is nearly full.

The xargs approach is the most convenient for batch extraction, and -n1 is the key option (the number 1, not the letter l). For batch compressing folders, refer to batch compressing folders in Linux. For more server operations content, see the cloud servers category.

Reference: the unzip manual page https://man7.org/linux/man-pages/man1/unzip.1.html; original post: https://www.cnblogs.com/cqzhuomi/articles/17284290.html (cnblogs.com CQZHUOMI, repost)

Integration & Code Examples

Example 1: Batch extract in a loop and count successes

cd /data/zips || exit 1

# Test integrity first so a corrupt archive fails before extraction
for f in *.zip; do
  unzip -tqq "$f" > /dev/null 2>&1 || echo "corrupt: $f"
done

ok=0; fail=0
for f in *.zip; do
  # -O gbk handles Chinese filenames produced by Windows archivers
  if unzip -o -O gbk "$f" -d "/data/unzip/${f%.zip}" > /dev/null 2>&1; then
    ok=$((ok + 1))
  else
    fail=$((fail + 1)); echo "FAIL: $f"
  fi
done
echo "ok: ${ok}, failed: ${fail}"

Each archive lands in its own directory so identically named files cannot overwrite each other, and -t only tests without writing to disk.

Example 2: Handle filenames with spaces and cap concurrency

# Pair -print0 with xargs -0 so paths containing spaces stay intact
find /data/zips -name '*.zip' -print0 \
  | xargs -0 -n1 -P4 unzip -o -O gbk -d /data/unzip

# Need one subtree from a big archive? List, then extract by prefix
unzip -l /data/zips/site-backup.zip | grep '^.*uploads/'
unzip -o /data/zips/site-backup.zip 'uploads/*' -d /data/unzip/site-backup

# Estimate space before extracting: archives vs. free space
du -ch /data/zips/*.zip | tail -1
df -h /data

-P4 runs four extractions in parallel, a real speedup with many small archives, but watch disk I/O and memory pressure.

Comparing the Ways: Behaviour on Failure, Subdirectories, and Overwrites

The commands differ on three points that matter more than speed: whether a corrupt archive stops the run, whether subdirectories are scanned, and whether existing files are overwritten.

Command pattern When one archive is corrupt Scans subdirectories Suits
unzip a.zip && unzip b.zip Stops at the first failure No Three to five archives, failures must be noticed
unzip a.zip; unzip b.zip Continues with the next one No A handful of archives where partial success is fine
find . -name '*.zip' -exec unzip {} \; Continues with the next one Yes Archives scattered across nested directories
ls *.zip | xargs -n1 unzip -o Continues with the next one No One directory of many archives, overwrite intended
find . -name '*.zip' -exec unzip -o {} + Continues with the next one Yes Many archives, fewer process launches

&& is the only pattern that halts, which makes it useful when you want the first broken package to surface immediately. -o decides whether an existing file is replaced without prompting: without it, an interactive confirmation waits inside a batch run and the job stalls.

A for loop sits outside the table because it is a shell construct rather than a command pattern: it can create a target directory first, count failures, or delete the source archive after a successful extraction.

One Check Before and One After: Read the Listing, Then Fix Ownership

Before extracting, inspect one archive with unzip -l a.zip | head -20 and read the entry paths. Entries containing .. can write outside the target directory (zip slip), so discard the whole package rather than extracting it.

After extracting into a web root, fix ownership in the same session: chown -R www:www /www/wwwroot. Skip it and the site reports that it cannot write files, which looks like an application bug rather than a permission one.

For logs and backups, extract into a temporary directory first and copy over the live files only after the listing and contents check out. Extracting in place bypasses that check and leaves a half-written directory when something goes wrong.

Limitations

  • Each archive lands in its own directory so identically named files cannot overwrite each other, and -t only tests without writing to disk.
  • This article reflects public information as of 2023-04-03; terms, prices and quotas follow the provider's current published terms.
  • Third-party capability and limit statements follow their official documentation; no further commitment is implied here.
  • Licensing, filing and data-residency decisions must be verified against the regulations of your operating region.

FAQ

Is parallel batch extraction worth it?

Yes, but keep it to about four workers. unzip is single-threaded, so xargs -P4 saturates the disk queue; going higher yields diminishing returns and competes with a co-located database. The bottleneck is usually disk rather than CPU, so read iostat and df before adding worker processes.

How do you handle archive passwords without exposing secrets?

Use -P with a value read from the environment, never hard-coded: unzip -o -P "$ZIP_PASS". Otherwise the password survives in shell history and the process list. In production, prefer interactive entry, or stage archives in a directory protected by chmod 600 before running the batch.

Why does extraction fail on names with spaces or Chinese?

Because an ls pipe splits paths. Pair find -print0 with xargs -0 so each path stays intact and unzip does not report a missing file. For garbled Chinese names add -O gbk, and run unzip -t first to drop corrupt archives before anything is written to disk.

Related Providers

  • Alibaba Cloud ECS: check disk throughput and volume type when hundreds of archives must be unpacked on local disks of a large backup set.
  • Tencent Cloud: verify whether internal download from object storage is billed and how much system disk is left before pulling archives to a CVM.
  • Hetzner: compare disk and bandwidth specs in the German and Finnish data centres when cheap large-disk machines must hold archives long term.

Community & Resources

Official docs and communities

Learning resources and tools

Original source: cnblogs.com (CQZHUOMI) ↗