1 Sep 2012 shlomif   » (Master)

Bash Function for Caching Results

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...
cache()
{
    local cache_fn="$1"
    shift

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

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

    local fn="$dir/$cache_fn"
    if ! test -f "$fn" ; then
        "$@" > "$fn"
    fi
    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.).

Syndicated 2012-09-01 15:05:58 from shlomif

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!