Skip to content

Instantly share code, notes, and snippets.

@dwallraff
Last active February 9, 2024 01:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dwallraff/f37610e6b357b5a28dd56ec94632480c to your computer and use it in GitHub Desktop.
Save dwallraff/f37610e6b357b5a28dd56ec94632480c to your computer and use it in GitHub Desktop.
Create and mount a loopback filesystem
#!/usr/bin/env bash
## Loopback Filesystem
# This script will create and mount a loopback filesystem
# Useful if you need to limit director(ies) by size
# but only have one volume
# This script needs to be run with sudo
LO_FILESYSTEM_NAME=my_loopback
LO_FILESYSTEM_MB_SIZE=5
MOUNT_LOCATION="/backup"
# Check if we have proper permissions
if [ "$EUID" -ne 0 ]; then
echo "Please run as root/with sudo"
exit
fi
# Check if $MOUNT_LOCATION already exists
if [ -d "$MOUNT_LOCATION" ]; then
echo "Directory $MOUNT_LOCATION already exists. Please clean up and run again."
exit
fi
# Create a file that is the size you want your filesystem to be
# Size = bs*count
# You CAN change the block size (bs) to be bigger, and then lower your count
# but that will create performance problems for anything that is comparing blocks
LO_FILESYSTEM_SIZE=$((LO_FILESYSTEM_MB_SIZE*10000))
echo "Creating file..."
dd if=/dev/zero of=$LO_FILESYSTEM_NAME bs=1024 count=$LO_FILESYSTEM_SIZE &> /dev/null
# Check to see which loop device we can use
for LOOP_DEVICE in {0..7}; do
losetup /dev/loop$LOOP_DEVICE &> /dev/null
if [ $? -eq 1 ]; then
break
fi
done
# Attach file as loopback device
echo "Using /dev/loop$LOOP_DEVICE"
losetup /dev/loop$LOOP_DEVICE $LO_FILESYSTEM_NAME &> /dev/null
# Add a filesystem to our new device
echo "Adding filesystem to /dev/loop$LOOP_DEVICE"
mkfs -t ext4 /dev/loop$LOOP_DEVICE &> /dev/null
# Mount the filesystem
echo "Mounting at $MOUNT_LOCATION"
mkdir -p $MOUNT_LOCATION
mount -t ext4 /dev/loop$LOOP_DEVICE $MOUNT_LOCATION
# Add entry to /etc/fstab
echo "/dev/loop$LOOP_DEVICE $MOUNT_LOCATION ext4 defaults 0 0" >> /etc/fstab
#dd if=/dev/zero of="$image" bs=1024K count="$img_size"
#mkfs.xfs "$image"
#sudo mount -o loop "$image" "$mount_path"
#sudo chown $USER:$USER "$mount_path"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment