Tuesday, April 16, 2013

Script in bash for compiling a kernel linux

This is a script that helps me in the process of compiling the kernel linux.

I test it on Arch Linux and Ubuntu and works fine if the source of the kernel is in
~/src/linux-KERNEL_VERSION
#!/bin/bash

set -e

if (( $EUID != 0 )); then
 echo "this script must be run as root"
 exit 1
fi

if (( $# != 1 )); then
 echo "pass only the KERNEL_VERSION as parameter"
 exit 1
fi

DISTRO=$(cat /etc/issue | awk '{print $1}')
CORE=$(grep -c processor /proc/cpuinfo)
FLAGS=`expr $CORE + 1`
JFLAGS=-j$FLAGS

cd /home/$SUDO_USER/src/linux-$1

echo "copy the config file"
sleep 1

case $DISTRO in
 "Arch")
  zcat /proc/config.gz > .config
  ;;
 "Ubuntu")
  cp /boot/config* .config
  ;;
esac

KER_NAME=$(cat .config | grep CONFIG_LOCALVERSION | grep -Po '(?<=\")[^)]*(?=\")')

echo "start make"
sleep 1
make $JFLAGS
make modules_install
echo "finish make"
echo "install the kernel"
sleep 1
cp -v arch/x86/boot/bzImage /boot/vmlinuz-$1$KER_NAME
case $DISTRO in
 "Arch")
  mkinitcpio -k $1$KER_NAME -c /etc/mkinitcpio.conf -g /boot/initramfs-$1$KER_NAME.img
  ;;
 "Ubuntu")
  mkinitramfs -o /boot/initrd.img-$1$KER_NAME $1
  ;;
esac

cp System.map /boot/System.map-$1$KER_NAME
echo "updating grub"
sleep 1
cp /boot/grub/grub.cfg /boot/grub/grub.cfg.old
grub-mkconfig -o /boot/grub/grub.cfg