[EnglishFrontPage] [TitleIndex] [WordIndex

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.


1. 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).

#       pushqueue element ...
# Pushes the given arguments as elements onto the queue.
pushqueue() {
    [[ $_queue ]] || {
        coproc _queue {
            while IFS= read -r -d ''; do
                printf '%s\0' "$REPLY"

    printf '%s\0' "$@" >&"${_queue[1]}"
} # _____________________________________________________________________

#       popqueue
# Pops one element off the queue.
# If no elements are available on the queue, this command fails with exit code 1.
popqueue() {
    local REPLY
    [[ $_queue ]] && read -t0 <&"${_queue[0]}" || return
    IFS= read -r -d '' <&"${_queue[0]}"
    printf %s "$REPLY"
} # _____________________________________________________________________


2012-07-01 04:05