Are you sure you really want to have swap on an external disk like that, over USB? It seems a little unusual, and might not be all that fast, so you might want to double check that requirement...
Assuming you do want to do that, the easiest way to have swap enabled at boot is via fstab. This would require the disk always be there, but if you can manage that, add an entry like:
UUID=b5958d5a-a89e-48c5-aea3-69296a43a50a none swap sw 0 0
To work out the UUID, one easy way is to cd to /dev/disk/by-uuid
and do a ls -l
. Look for the one that is symlinked to the partition you want (dmesg / logs should tell you the disk when you add it, fdisk -l
can help you work out which partition on the disk you want)
Otherwise, if you want something that will enable swap when you add the disk, that will likely want to be a udev
rule. This is quite a good tutorial. I suspect you'd want to write something that got all ACTION=="add", SUBSYSTEM=="usb"
events and then in that script check the type and decide if it's your disk or not. If it is, have it mount your partitions, enable swap etc.
For shutting down the disk, I'd suggest a script that you run, which would both turn off swap and unmount the partitions. Anything else is likely to not fire at the right time, and Linux will object if the disk with swap on it vanishes... The script would be something like:
DISK_ID=wwn-0x500153203458ed3f
# TODO Find this more nicely!
DISK=`ls -l /dev/disk/by-id/$DISK_ID | awk '{print $11}' | awk -F'/' '{print $3}'`
if [[ "$DISK" == "" ]]; then
echo "Disk not found!"
exit 1;
fi
# Disable swap on partition
SP=`grep /proc/swaps /dev/$DISK | awk '{print $1}'`
if [[ "$SP" == "" ]]; then
echo "No active swap found on $DISK"
exit 1
fi
swapoff $SP
# Unmount other partitions on that disk
for PART in `mount | grep /dev/$DISK | awk '{print $3}'`; do
echo "Unmounting $PART"
umount $PART
done
# Mark disk as finished with
eject /dev/$DISK
free -m
shows that none of it is being used. It will not be any slower than having a swap on the SD card or not having a swap at all.time dd if=/dev/zero of=[sd or usb location] bs=1024 count =102400
(writing 100 MB) and got 7-10 MB/s on the (class 10) SD card and 12-23 MB/s to the USB drive. +1 for you ;) The compressed ramdisk swap will obviously be faster but that is maybe sort of a dubious arrangement.