kindwolf.org Git repositories xavierg-snippets / master create-multiple-swap-files / determine-max-swapfiles-2.bash
master

Tree @master (Download .tar.gz)

determine-max-swapfiles-2.bash @masterraw · history · blame

#!/usr/bin/env bash
# Compute MAX_SWAPFILES by "running" swap.h using the C preprocessor.

kernel_config="/boot/config-$(uname -r)"
kernel_release="$(uname -r | cut -d- -f1,2)"
# Debian provides swap.h through package linux-headers-xxx-common:
swap_h_path="/usr/src/linux-headers-${kernel_release}-common/include/linux/swap.h"
MAX_SWAPFILES=$(
	{
		# Turn the current kernel's configuration into a sequence of #define statements:
		perl -ne 'printf(qq[#define %s %s\n], $1, $2) if m#^([^=]+)=(.*)$#' "${kernel_config}"
		# Append include/linux/swap.h but get rid of #include statements for the sake of simplicity:
		grep -v '#include' "${swap_h_path}"
		# Last line: instruct the C preprocessor to output the value of
		# MAX_SWAPFILES; we expect a single-line math expression, written with C in
		# mind yet Python/Perl-friendly, hence the addition of print() for Perl:
		echo 'print(MAX_SWAPFILES)'
	} | cpp | tail -1 | perl -
	# ^ Feed the whole thing to the C preprocessor, keep only the last line and feed it to Perl
)