Skip to content

Instantly share code, notes, and snippets.

@ThinGuy
Last active January 6, 2020 01:08
Show Gist options
  • Save ThinGuy/3128ee34a3e92ca0d1ec55299d9552a8 to your computer and use it in GitHub Desktop.
Save ThinGuy/3128ee34a3e92ca0d1ec55299d9552a8 to your computer and use it in GitHub Desktop.
Function to add loop devices, that ensures max_loop is not exceed
add-loops() {
[[ -n ${1} && ${1} =~ ^[0-9]+$ ]] && local C=${1} || { printf "${FUNCNAME} <count>\n";return 2; }
[[ ${EUID} = 0 ]] && export SU= || export SU=sudo
local -a LOOP_DEVS=($(find /dev -maxdepth 1 -iregex '.*loop[0-9]+'|sort -V))
local M=$(cat 2>/dev/null /proc/cmdline|grep -oP '(?<=max_loop=)[^ ]+')
[[ -n ${M} && ${M} =~ ^[0-9]+$ ]] || local M=256
[[ $((${#LOOP_DEVS[@]}+${C})) -gt ${M} ]] && { printf "Can only add up to $(($M-${#LOOP_DEVS[@]})) new devices\n";return 2; }
local L=${LOOP_DEVS[-1]//[^0-9]/}
local S=$(($L+1))
local E=$(($S+$C))
printf "Current loop device count: ${#LOOP_DEVS[@]}\n"
printf "First new loop device: /dev/loop${S}\n"
printf "Last new loop device: /dev/loop${E}\n"
eval printf '%s\\n' {$S..$E}|xargs -n1 -P0 bash -c '${SU} bash -c "mknod -m0660 /dev/loop${0} b 7 ${0} && chown root.disk /dev/loop${0}"'
local -a LOOP_DEVS=($(find /dev -maxdepth 1 -iregex '.*loop[0-9]+'|sort -V))
printf "New loop device count: ${#LOOP_DEVS[@]}\n"
unset SU
}
@ThinGuy
Copy link
Author

ThinGuy commented Nov 17, 2018

$ add-loops 10
Current loop device count: 11
First new loop device: /dev/loop11
Last new loop device: /dev/loop21
New loop device count: 22

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment