Last active
October 6, 2023 20:02
-
-
Save Nezteb/01eb349b65ce3caa4afd1f6e271aabd2 to your computer and use it in GitHub Desktop.
A dumb shell command cacher.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage `cache ls` or `cache ./myScript.sh` | |
cache() { | |
local expiry_minutes=20 | |
local command_name="$1" | |
local command_hash=$(echo "$*" | md5sum | cut -d' ' -f1) | |
local cache_dir="$HOME/.cache/cli_cache" | |
local command_cache_dir="$cache_dir/$command_name" | |
local cache_file="$cache_dir/$command_hash" | |
# If command is "c" or "clear", clear the cache directory | |
if [ "$command_name" = "clear" ] || [ "$command_name" = "c" ]; then | |
# echo "Clearing cache: $cache_dir" | |
rm -rf "$cache_dir" | |
return | |
fi | |
# Create cache directory and file if they don't | |
mkdir -p "$cache_dir" | |
mod_time=$(stat -f %m "$cache_file" 2>/dev/null) | |
current_time=$(date +%s) | |
minutes_old=$(((current_time - mod_time) / 60)) | |
# Check if cache file exists and is not older than 20 minutes | |
if [ "$minutes_old" -ge $expiry_minutes ]; then | |
if [ -f "$cache_file" ]; then | |
# echo "Cache file is $minutes_old minutes old (>=$expiry_minutes), updating cache: $cache_file" | |
else | |
# echo "Cache file does not exist, creating cache: $$cache_file" | |
touch "$cache_file" | |
fi | |
# Supposedly does colors, but it doesn't seem to work for me | |
script -q "$cache_file" "$*" | |
# Doesn't do colors | |
# "$@" > "$cache_file" | |
# Doesn't do colors | |
# "$@" | tee "$cache_file" | |
else | |
# echo "File is $minutes_old minutes old (<$expiry_minutes), using cache: $cache_file" | |
cat "$cache_file" | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment