Skip to content

Instantly share code, notes, and snippets.

@ipernet
Forked from koshigoe/mount-ram.sh
Last active May 12, 2018 20:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ipernet/4696907 to your computer and use it in GitHub Desktop.
Save ipernet/4696907 to your computer and use it in GitHub Desktop.
#!/bin/sh
# This program has two feature.
#
# 1. Create a disk image on RAM.
# 2. Mount that disk image.
#
# Usage:
# $0 <dir> <size> <name>
#
# size:
# The `size' is a size of disk image (MB).
#
# dir:
# The `dir' is a directory, the dir is used to mount the disk image.
#
# name:
# The volume name of the mounted disk image.
#
# See also:
# - hdid(8)
#
# Mounting at system boot:
# - Terminal > $ export VISUAL=nano && crontab -e
# - Add "@reboot /path/to/mount-ram.sh <dir> <size> <name>
#
if [ $# -lt 1 ]; then
cat <<EOF >&2
Usage: $0 <dir> [size]
Creates a disk image of the given size in megabyte (default: 64) and mounts it at the given directory.
EOF
exit 1
fi
mount_point=${1}
size=${2:-64}
volume_name=${3:-ramdisk}
mkdir -p $mount_point
if [ $? -ne 0 ]; then
echo "The mount point isn't available." >&2
exit $?
fi
sector=$(expr $size \* 1024 \* 1024 / 512)
device_name=$(hdid -nomount "ram://${sector}" | awk '{print $1}')
if [ $? -ne 0 ]; then
echo "Could not create disk image." >&2
exit $?
fi
newfs_hfs -v $volume_name $device_name > /dev/null
if [ $? -ne 0 ]; then
echo "Could not format disk image." >&2
hdiutil detach -quiet $device_name
exit $?
fi
mount -t hfs $device_name $mount_point
if [ $? -ne 0 ]; then
echo "Could not mount disk image." >&2
hdiutil detach -quiet $device_name
exit $?
fi
#Like having a default temp dir in it
mkdir -p $mount_point/temp
#!/bin/sh
# This program has two features.
#
# 1. Unmount a disk image.
# 2. Detach the disk image from RAM.
#
# Usage:
# $0 <dir>
#
# dir:
# The `dir' is a directory, the dir is mounting a disk image.
#
# See also:
# - hdid(8)
#
mount_point=$1
if [ ! -d "${mount_point}" ]; then
echo "The mount point didn't available." >&2
exit 1
fi
mount_point=$(cd $mount_point && pwd)
device_name=$(df "${mount_point}" 2>/dev/null | tail -1 | grep "${mount_point}" | cut -d' ' -f1)
if [ -z "${device_name}" ]; then
echo "The mount point didn't mount disk image." >&2
exit 1
fi
umount "${mount_point}"
if [ $? -ne 0 ]; then
echo "Could not unmount." >&2
exit $?
fi
hdiutil detach -quiet $device_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment