| Bash Function for Caching Results |
[Sep. 1st, 2012|06:05 pm]
|
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.).
|
|
|