| name | state-directory-manager-5-cache-management |
| description | Sub-skill of state-directory-manager: 5. Cache Management (+1). |
| version | 1.0.0 |
| category | _core |
| type | reference |
| scripts_exempt | true |
5. Cache Management (+1)
5. Cache Management
Implement caching with expiration:
#!/bin/bash
CACHE_TTL="${CACHE_TTL:-3600}"
cache_path() {
local key="$1"
local hash=$(echo -n "$key" | md5sum | cut -c1-16)
echo "$CACHE_DIR/${hash}"
}
cache_valid() {
local key="$1"
local ttl="${2:-$CACHE_TTL}"
local path=$(cache_path "$key")
if [[ -f "$path" ]]; then
local age=$(($(date +%s) - $(stat -c %Y "$path" 2>/dev/null || stat -f %m "$path")))
[[ $age -lt $ttl ]]
else
return 1
fi
}
cache_get() {
local key="$1"
local ttl="${2:-$CACHE_TTL}"
local path=$(cache_path "$key")
if cache_valid "$key" "$ttl"; then
cat "$path"
return 0
fi
return 1
}
cache_set() {
local key="$1"
local value="$2"
local path=$(cache_path "$key")
mkdir -p "$CACHE_DIR"
echo "$value" > "$path"
}
cache_delete() {
local key="$1"
local path=$(cache_path "$key")
rm -f "$path"
}
cache_clear() {
rm -rf "$CACHE_DIR"/*
}
cache_clean() {
local ttl="${1:-$CACHE_TTL}"
find "$CACHE_DIR" -type f -mmin "+$((ttl / 60))" -delete 2>/dev/null || true
}
get_with_cache() {
local key="$1"
local command="$2"
local ttl="${3:-$CACHE_TTL}"
if cache_valid "$key" "$ttl"; then
cache_get "$key"
else
local result
result=$(eval "$command")
cache_set "$key" "$result"
echo "$result"
fi
}
result=$(get_with_cache "api_response" "curl -s https://api.example.com/data" 300)
6. Log File Management
Manage logs with rotation:
#!/bin/bash
LOG_FILE="$LOG_DIR/app.log"
LOG_MAX_SIZE=$((10 * 1024 * 1024))
LOG_MAX_FILES=5
init_logging() {
mkdir -p "$LOG_DIR"
touch "$LOG_FILE"
}
log_to_file() {
local level="$1"
shift
local message="$*"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[$timestamp] $level: $message" >> "$LOG_FILE"
maybe_rotate_logs
}
maybe_rotate_logs() {
if [[ -f "$LOG_FILE" ]]; then
local size=$(stat -c %s "$LOG_FILE" 2>/dev/null || stat -f %z "$LOG_FILE")
[[ -gt ]];
rotate_logs
}
() {
-f
((i=LOG_MAX_FILES-; i>=; i--));
[[ -f ]];
[[ -f ]];
}
() {
days=
find -name -mtime -delete 2>/dev/null ||
}
() {
lines=
-n
}
() {
pattern=
grep -h /*.* 2>/dev/null | -100
}