Bash Toolbox

This is a collection of handy little bash snippets that can be useful to solve certain common problems.

If you contribute a tool, please make sure the quality is good. Format the code properly too, so that it's readable for others. For the sake of code quality, we assume a minimum Bash shell of version 3 or 4 is available. No POSIX code, please, and definitely no Bourne/CSH/ZSH code.

Please describe your tool above the code. Explain what it does, how it works, what input it takes, what output it yields and what side-effects it has.


An in-memory queue

The following creates an in-memory queue using a coprocess and communicates with it using file descriptors.

The pushqueue function first checks to see if the coprocess that holds the queue is up. If not, it starts it. Subsequently, it writes its arguments to the coprocess' standard input (using NUL bytes as delimitor, so that you can pass in whatever string in your arguments safely).

The _queue coprocess just reads input and writes its input back as output, relying on the system's file descriptor buffers to define its queue size.

The popqueue function begins by checking whether the coprocess is up and whether input is available from its standard output. If either condition fails, the function fails since no element is available from the queue. If the checks pass, the function attempts to read an element from the queue (again, we use NUL bytes as delimitors since that's how the queue writes its elements, making it safe to put any string in the elements).

   1 #       pushqueue element ...
   2 #
   3 # Pushes the given arguments as elements onto the queue.
   4 #
   5 pushqueue() {
   6     [[ $_queue ]] || {
   7         coproc _queue {
   8             while IFS= read -r -d ''; do
   9                 printf '%s\0' "$REPLY"
  10             done
  11         }
  12     }
  14     printf '%s\0' "$@" >&"${_queue[1]}"
  15 } # _____________________________________________________________________
  17 #       popqueue
  18 #
  19 # Pops one element off the queue.
  20 # If no elements are available on the queue, this command fails with exit code 1.
  21 #
  22 popqueue() {
  23     local REPLY
  24     [[ $_queue ]] && read -t0 <&"${_queue[0]}" || return
  25     IFS= read -r -d '' <&"${_queue[0]}"
  26     printf %s "$REPLY"
  27 } # _____________________________________________________________________


BashToolbox (last edited 2024-05-04 12:56:47 by emanuele6)