How to use cpio command in Linux

May 21, 2005
This article explains how to use cpio command in Linux.

cpio is a tool for creating and extracting archives, or copying files from one place to another. It handles a number of cpio formats as well as reading and writing tar files.

cpio command performs three primary functions namely -

  1. Copying files to an archive,
  2. Extracting files from an archive, and
  3. Passing files to another directory tree.

cpio can take input from find command which is an advantage while taking selective backups.

The following are a few examples of using cpio in Linux.

Backup Files

Take a backup of all the configuration files residing in your /etc directory.

$ find /etc -iname \*.conf | cpio -o --format=tar > backup.tar

You can use -H option instead of --format in the above command for the same effect.

$ find /etc -iname \*.conf | cpio -o -H tar > backup.tar

You can also achieve the same without using redirection >

$ find /etc -iname \*.conf  | cpio -o --format=tar -F backup.tar

OR

$ find /etc -iname \*.conf | cpio -o -H tar -F backup.tar

Add files to an already existing Tar file

Use the --append option to add more files to an already existing tape archive (Tar file).

As an example, let's first create an archive backup.tar which contains the directory dir1.

$ find ../dir1 | cpio -o --format=tar -F backup.tar

Now let's add some more files from another directory - dir2 to the newly created backup.tar archive. For this we use the --append option as shown below.

$ find ../dir2 | cpio -o --format=tar --append -F backup.tar

List contents of the Tar file

$ cpio -it  < test.tar

OR

$ cpio -it -F test.tar

Extract the contents from the tar file

You use the -i option for the purpose.

$ cpio -i -F test.tar

Copy all (or a subset) of files from current directory to another directory

$ find . -print0 -depth | cpio --null -pvd new-dir

In the above command, the -print0 and the --null switches will act together to send file names between find and cpio, even if special characters are embedded in the file names.

The -p switch tells cpio to pass the files it finds to the directory new-dir.

0 comments: