Skip to content

Instantly share code, notes, and snippets.

@Knogle
Created March 12, 2024 21:23
Show Gist options
  • Save Knogle/64f57375ce7fe0e7efcd8a379a5ed493 to your computer and use it in GitHub Desktop.
Save Knogle/64f57375ce7fe0e7efcd8a379a5ed493 to your computer and use it in GitHub Desktop.
Optimized for creating of multiple Loop-Devices
#!/bin/bash
# Function to display help message
show_help() {
echo "Usage: $0 [OPTION]... [ARGUMENTS]..."
echo "Set up and mount a loop device for a given file, create a new file of specified size and mount it, or create multiple loop devices of specified size."
echo ""
echo " --help display this help and exit"
echo " automount <Size> automatically create a file of specified size, set up and mount it"
echo " multimount <Size> <Number> create multiple files of specified size and set them up as loop devices"
echo " <FilePath> path to the existing file to set up and mount"
echo ""
echo "Examples:"
echo " $0 /path/to/your/file.img Set up an existing file as a loop device."
echo " $0 automount 1M Create a 1M-sized file and set it up as a loop device."
echo " $0 multimount 1M 5 Create five 1M-sized files and set them up as loop devices."
echo ""
echo "Note: Run this script with root permissions or using sudo."
}
declare -a LOOPDEVICES
declare -a FILEPATHS
# Function to create, set up, and mount a loop device with a file of a specified size
automount() {
local FILESIZE=$1
local GUID=$(uuidgen)
local FILENAME="${GUID}.img"
local FILEPATH="/tmp/${FILENAME}"
dd if=/dev/zero of="$FILEPATH" bs=$FILESIZE count=1 &>/dev/null
local LOOPDEVICE=$(sudo losetup -fP --show "$FILEPATH")
if [ -z "$LOOPDEVICE" ]; then
echo "Error creating the loop device."
return 1
fi
echo "Loop device set up: $LOOPDEVICE"
LOOPDEVICES+=("$LOOPDEVICE")
FILEPATHS+=("$FILEPATH")
}
# Function to create multiple loop devices of specified size
multimount() {
local FILESIZE=$1
local NUMBER=$2
for ((i=1; i<=NUMBER; i++)); do
automount $FILESIZE
done
echo "Press [Enter] to detach all loop devices."
read
for LOOPDEVICE in "${LOOPDEVICES[@]}"; do
sudo losetup -d "$LOOPDEVICE"
echo "Loop device detached: $LOOPDEVICE"
done
for FILEPATH in "${FILEPATHS[@]}"; do
rm -f "$FILEPATH"
echo "Temporary file deleted: $FILEPATH"
done
}
# Main logic
case "$1" in
--help)
show_help
;;
automount)
if [ "$#" -ne 2 ]; then
echo "Usage: $0 automount <Size>"
exit 1
fi
automount $2
;;
multimount)
if [ "$#" -ne 3 ]; then
echo "Usage: $0 multimount <Size> <Number>"
exit 1
fi
multimount $2 $3
;;
*)
if [ "$#" -ne 1 ]; then
show_help
exit 1
fi
automount $1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment