Unpacking or Repacking initrd.img or initramfs.img

Need to tinker with an initrd.img or initramfs.img? Here are the steps to unpack these files and then put them back together again if you've made any changes.

First step, make a copy of the initrd.img or initramfs.img in question:

cp /boot/initramfs-*.img /tmp

The .img hides the fact that these files are actually gzip archives, so they need to be uncompressed.

cd /tmp
gunzip -S .img initramfs*.img
# -S .img allows gunzip to accept the .img extension
# alternative is to rename the image
mv initramfs*.img initramfs.gz
gunzip initramfs.gz

The result will be a file of the same name as the ramdisk without any extension. If you're concerned about repacking later it might be worth checking how the image was archived -- odds are it's in the newc format. If that's the case the file command will output something similar to this message:

file initramfs-3.8.9-200.fc18.x86_64
initramfs-3.8.9-200.fc18.x86_64: ASCII cpio archive (SVR4 with no CRC)

You can look up the other possible formatting options by reading the cpio manpage.

Now to unpack the cpio archive and get at the contents of the image:

# probably worth making a new directory to unpack this to. keeps things clean
mkdir ramdisk
cd ramdisk
cpio -id < ../initramfs*
105643 blocks

Now you can examine and play around with the contents of the image:

ls
bin  dev  etc  init  lib  lib64  proc  root  run  sbin  shutdown  sys  sysroot  tmp  usr  var

If you want to put it all back together just reverse the steps above:

pwd        # make sure we're in the root of the unpacked ramdisk
/tmp/ramdisk
find . | cpio --create --format='newc' > /tmp/newinitramfs
105731 blocks
cd /tmp
gzip -S .img newinitramfs
mv newinitramds.img /boot/initramfs-[kernel version].img