cpio - Linux


Overview

cpio is a command-line utility in Linux used for managing archives of files. It can create, extract, and list the contents of archives. It is primarily used for generating archives in a format suitable for backups and software distribution. cpio stands out by its ability to handle file attributes like permissions and links, making it a reliable choice for system backups when combined with a pipeline.

Syntax

cpio -o|--create [options] <name-list >archive
cpio -i|--extract [options] <archive
cpio -p|--pass-through [options] destination-directory
  • name-list: Files and directories to be processed, typically provided via pipe |.
  • archive: The filename for the archive file.
  • destination-directory: Target directory for passing files.

Modes of Operation

  1. Copy-out mode (-o): Creates an archive.
  2. Copy-in mode (-i): Extracts an archive.
  3. Copy-pass mode (-p): Passes files to another directory.

Options/Flags

  • -o, --create: Create an archive.
  • -i, --extract: Extract files from an archive.
  • -p, --pass-through: Direct file copying between directories.
  • -v, --verbose: Provide a verbose output listing files processed.
  • -d, --make-directories: Create directories as needed.
  • -m, --preserve-modification-time: Preserve modification times.
  • -t, --list: List the contents of an archive.
  • -u, --unconditional: Unconditionally copy files; replace existing files.
  • --block-size, -B: Set the block size for I/O operations (in bytes).
  • --no-preserve-owner: Do not change the ownership.

Examples

  1. Creating an Archive:

    find . -type f | cpio -o > my_backup.cpio
    
  2. Extracting an Archive:

    cpio -i < my_backup.cpio
    
  3. List Contents of Archive:

    cpio -it < my_backup.cpio
    
  4. Copy Files Directly:

    echo "file1.txt" | cpio -pdm /destination-directory
    

Common Issues

  • Permission Denied: Ensure you have adequate permissions for the directories and files you are working with.
  • Corrupted Archive: This can happen if the archive is not correctly created or if it is modified. Use checksums like md5sum to verify archive integrity.

Integration

Combining with find for selective backups:

find /home/user/docs -name "*.txt" | cpio -o > textfiles.cpio

Using in scripts for automated backups:

#!/bin/bash
echo "Starting backup..."
find /home -mtime -1 | cpio -o > daily.cpio
echo "Backup completed."
  • tar: Another archive tool with different options and archive format.
  • gzip, bzip2: Tools for compressing files, often used in conjunction with cpio.
  • find: Useful for generating lists of files based on criteria (e.g., modification date).

For more detailed information, consult the cpio man page by running man cpio in your terminal.