June 07, 2016

Mounting a ramdisk at login

I rebooted my apple box with 2 terminals and several tabs in each terminal. I say sure, restore open windows after boot. Then a hammer hit me after boot as my box had almost no ram?

A simple ls -l /Volumes/ showed that my firefox_cache was mounted once pr open tab terminal. Which is excatly what I told it to do. My .bash_profile has this statement:

[ ! -d /Volumes/firefox_cache ] && diskutil erasevolume HFS+ 'firefox_cache' `hdiutil attach -nomount ram://1165430`

Since every one of these start simultaneously when a terminal starts the first time crap happens... :/ So lets try to create the firefox_cache using a login script instead of the .bash_profile start. The apple documentation states:

Use the defaults tool to install your login script. Create the script file and put it in a directory that is accessible to all users. In Terminal, use the following command to install the script (where /path/to/script is the full path to your script file):
sudo defaults write com.apple.loginwindow LoginHook /path/to/script
To remove this hook, delete the property:
sudo defaults delete com.apple.loginwindow LoginHook
Use the same procedure to add or remove a logout hook, but type LogoutHook instead of LoginHook.



So, lets extract the mount part from .bash_profile and add a hook to the new script.

$ echo "[ ! -d /Volumes/firefox_cache ] && diskutil erasevolume HFS+ 'firefox_cache' `hdiutil attach -nomount ram://1165430`" > ~/bin/firefox_cache.sh
$ chmod u+x ~/bin/firefox_cache.sh 
$ sudo defaults write com.apple.loginwindow LoginHook \ /home/$USER/bin/firefox_cache.sh

Remove the line from .bash_profile and logout and back in to see those changes.

$ sed -i -e 's/^.*firefox_cache.*$//g' ~/.bash_profile
tell application "System Events" to log out

Once you're logged out, log right back in and check to see that the ram-disk is mounted and after you fire up a terminal or multiple terminals you only have one entry.

$ ls -l /Volumes/

Macintosh HD  MobileBackups firefox_cache

No comments: