Skip to content
Anoncheg1 edited this page Oct 16, 2024 · 4 revisions

This is function for Bash shell users that should be saved in ~/.bashrc file

#!/usr/bin/env bash
function cache_exec() {
  if [ -z "$1" ] ; then echo cache_exec no \$1 for command name; return 1 ; fi
  
  local SUCCESS_LENGHT_TRASHOLD=2
  local CACHE_TIME=36000 # 10 hours
  local CACHE_DIR=/tmp/cache_exec

  local cmd="$*"
  local cache_file="$CACHE_DIR/"$(echo "$cmd" | sha1sum | cut -f 1 -d ' ')

  echo $cache_file

  mkdir -p $CACHE_DIR # create if not exist

  if [ -f "$cache_file" ] && [ $(($(date +%s) - $(stat -c "%Y" "$cache_file"))) -lt $CACHE_TIME ]; then
    cat "$cache_file"
  else
    local output=$("$@")
    echo $(echo "$output" | wc -l) $SUCCESS_LENGHT_TRASHOLD
    if [ $(echo "$output" | wc -l) -gt $SUCCESS_LENGHT_TRASHOLD ]; then
        echo "$output" > "$cache_file"
        echo "$output"
    fi
  fi
}

usage: cache_exec translate hello

Clone this wiki locally