Created
January 6, 2013 02:30
-
-
Save upsuper/4464839 to your computer and use it in GitHub Desktop.
Script for OS X to create ramdisk & mount to a given place. This script is also enabled to resize the ramdisk it creates by mounting a new one and copying files into it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/zsh | |
| INITIAL_SIZE=5 | |
| VOLUME_NAME='ramdisk' | |
| MOUNTPOINT='/tmp/upsuper' | |
| MOUNTPOINT_FILE='/tmp/ramdisk.mountpoint' | |
| # find a non-existent initial mount point | |
| mountpoint=$(mktemp -dt ramdisk) | |
| # set ramdisk size | |
| [[ -n "$1" ]] && size="$1" || size="$INITIAL_SIZE" | |
| # generate new ramdisk device | |
| # 2048 = 1024 * 1024 / 512 | |
| disk=$(hdiutil attach -nomount ram://$((size*2048))) | |
| disk=${disk/% */} | |
| # create fs & mount | |
| newfs_hfs -v "$VOLUME_NAME" -U $UID "$disk" >/dev/null | |
| mount -t hfs "$disk" "$mountpoint" | |
| # copy any existing files to new point | |
| if [[ -e "$MOUNTPOINT" ]]; then | |
| cp -pR "$MOUNTPOINT/" "$mountpoint" 2>/dev/null | |
| rm -rf "$MOUNTPOINT" | |
| fi | |
| # unmount old ramdisk | |
| if [[ -e "$MOUNTPOINT_FILE" ]]; then | |
| read old_mountpoint <"$MOUNTPOINT_FILE" | |
| if [[ -n "$old_mountpoint" ]]; then | |
| old_disk=$(mount | awk '/'"${old_mountpoint//\//\/}"'/ { print $1 }') | |
| if [[ -n "$old_disk" ]]; then | |
| umount "$old_disk" 2>/dev/null | |
| if [[ $? != 0 ]]; then | |
| # undo everything before | |
| umount "$mountpoint" 2>/dev/null | |
| hdiutil detach "$disk" >/dev/null | |
| rm -rf "$mountpoint" | |
| ln -s "$old_mountpoint" "$MOUNTPOINT" | |
| echo "Cannot umount $old_mountpoint" 1>&2 | |
| exit 1 | |
| fi | |
| hdiutil detach "$old_disk" >/dev/null | |
| fi | |
| rm -rf "$old_mountpoint" | |
| fi | |
| fi | |
| # write mountpoint file | |
| echo "$mountpoint" >"$MOUNTPOINT_FILE" | |
| # link new mountpoint to given place | |
| ln -s "$mountpoint" "$MOUNTPOINT" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment