Shlomif's Technical Posts Community - Bash Function for Caching Results [entries|archive|friends|userinfo]
Shlomif's Technical Posts Community

[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

[Links:| Shlomi Fish's Homepage Main Journal Homesite Blog Planet Linux-IL Amir Aharoni in Unicode open dot dot dot ]

Bash Function for Caching Results [Sep. 1st, 2012|06:05 pm]
Previous Entry Add to Memories Share Next Entry


[Tags|, , , , ]
[Current Location |Home]
[Current Music |Kira Isabella - A Little More Work to Do]

In this blog I’d like to blog about the newest edition to my Bash (the UNIX shell) aliases file: the cache() function. What it does is cache the result of a lengthy command in a file in a common place, and then simply output this file if it already exists. I found it of use when I compiled a report which involved some lengthy recursive grep operations which were time consuming, and required a lot of waiting. Another upside to caching is the fact that one can monitor its progress by following the file on disk.

Here is the cache function, available under the MIT/X11 licence:

# What this function does is cache the result of a command in a file, and
# use the file to output the results in case it exists.
# Format is: cache "$basename_to_cache_in" $cmd $arg1 $arg2 $arg3...
    local cache_fn="$1"

    local dir="${CACHE_DIR:-.}"

    if ! test -d "$dir"; then
        mkdir -p "$dir"

    local fn="$dir/$cache_fn"
    if ! test -f "$fn" ; then
        "$@" > "$fn"
    cat "$fn"

Hope you find it useful.

(Note: part of the reason why I'm writing this post is to see if it shifts away the spam comments from my previous post, which attracted a lot of spam in the past days. It's an experiment to see how spam behaves.).