cwrite/cread cache

Concept: cwrite/cread

Purpose:
Simplify caching of piped input in shell scripts without using variable assignments like local some_var_name="$(...)". These commands allow easy writing and reading of intermediate data using cache files.

Key Idea:

  • cwrite: Writes piped input into a cache file.
  • cread: Reads data from the cache.

Even with a specified cache name, the cache is scoped to the process using the process ID ($$), ensuring isolation per process.

Example:

ls "${BOOKS:?}" | fzf | cwrite bookname
cread bookname | strings.prefix "${BOOKS:?}/" | cwrite bookpath
cread bookpath | openm

Example with checking data

 echo -e "hi\nhi2\nhi3" | fzf | cwrite

 cread_has_data && {
   cread
 } || echo "cread did NOT have data"

Functionality

  • cwrite:
    Writes input to a cache file. Can specify a name, or it defaults to a process-scoped file.
  • cread:
    Reads from the cache. Returns an error if the file is missing or empty.

Note: Cache files are tied to the current process ID ($$), ensuring each process has its own cache, even when using the same cache name.


Error Handling

  • cwrite: Errors if not called from a pipe.
  • cread: Errors if the cache file is missing or empty.

Common Use Cases

  1. Cache intermediate command outputs.
  2. Per-process cache isolation using the process ID ($$).
  3. Cross-subshell communication by writing in one and reading in another.