Gentoo Wiki


This article is part of the Tips & Tricks series.
Terminals / Shells Network X Window System Portage System Filesystems Kernel Other


I needed a way to autodetect swap early in my bootup. I am using PXE to boot into a small mini laptop so as to run Mythtv frontend as a thinclient. I soon discovered that my small laptop with its limitted memory was not meeting the demands that extra memory could provide. I did not want to try and hack my way through swap over NFS ( so I figured it would be better and possibly faster to find a way to use a swap partition on the local hard drive. I also wanted to be able to dynamically find swap on any computer, whether it was on hda1, hda2, or sda3, or sda4.

The script

File: /etc/init.d/my-autoswap
# Copyright 1999-2006 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: $
# Autodetect swap partition
# author: Mathias Laurin <>
# from the script found at
# left by an anonymous contributor.
# 2006-12-26, v.0.2.0

depend() {
	after checkfs

do_swap() {
	local CMD="$1"
	local DEVLIST
	local DEV

	DEVLIST="$(ls /dev/[h-s]d[a-z][0-9]*)"
	# LVM2 support
	[ -c /dev/mapper/control ] && DEVLIST="$DEVLIST $(ls /dev/mapper/*)"

	for DEV in $DEVLIST
		FS="$(file -sL "$DEV"| cut -d' ' -f3)"
		if [ "$FS" = "swap" ]
			einfo "    $DEV"
			$CMD "$DEV"
	return $?

start() {
	ebegin "Swap on"
	do_swap /sbin/swapon
	eend $?

stop() {
	ebegin "Remove swap from"
	do_swap /sbin/swapoff
	eend $?

Don't forget to:

chmod 755 /etc/init.d/my-autoswap
rc-update add my-autoswap boot
Note: Adding this script to the boot runlevel is recommended but not mandatory


Retrieved from ""

Last modified: Thu, 04 Sep 2008 06:18:00 +0000 Hits: 10,724