bash,  Uncategorized

Scripting the Temp and Cache Directories on a Mac

Ever see a weird folder like /var/folders/g0/lr10g_wx4t75s2hd5129qhkc0000gn/T/ and wonder why it’s there? Those are usually Darwin or shell temporary or cache directories. They are where those weird temp directories you need to access are written to and read from. Apple uses these to host volatile sql databases and a number of scripts use them to house a file and protobuffs prior to processing.

You too can access them in your scripts when needed. The most common is a built-in shell temp that you can easily access just by echoing out the contents of $TMPDIR:

echo $TMPDIR

Darwin has some as well; most notably in DARWIN_USER_CACHE_DIR and DARWIN_USER_TEMP_DIR where each can be used for what their name denotes. The getconf command will provide the contents of each. For example:

getconf DARWIN_USER_TEMP_DIR

Reading from apps that start with that directory hierarchy can usually easily be programmatically done by calling the appropriate location. When solutioning in bash, you can add some logic to look for the $TMPDIR and write there first or move on to a user cache or user temp instead, as follows:

if [ -z ${TMPDIR} ]; then
USERCACHE=getconf DARWIN_USER_CACHE_DIR
USERTMP=getconf DARWIN_USER_TEMP_DIR
echo $USERCACHE
echo $USERTMP
else
echo $TMPDIR
fi

In the above script we don’t really have any program logic, just echoing out locations. But this lays out the basic function I’ve been using for years when I’m doing this kind of thing. Enjoy and feel free to provide any other locations you might like to check in the comments!