NewsCrawler.org

Concurrent Shell Command Queues in Bash and Zsh

The author shows how to run shell commands in parallel in Bash while limiting how many run at once. The approach creates a command queue with functions to start it, submit commands to it, and wait for it to finish. Commands can be added over time, not all at once, and concurrency is handled by xargs[1] with its -P option.

The queue is a FIFO[2] file in a temporary directory, and each submitted command is written to it as a NUL-separated string. The code finds a free file descriptor[3] between 3 and 9 to keep the queue open. Calling queue_wait closes the queue so that running jobs finish before the script continues.

The code works in Bash and Zsh, and the author says it has many defensive checks but may have failure modes that are hard to predict. The author also says Python is probably a better choice for this kind of work. The examples use Postman Echo for web requests and show that output appears as each job finishes.

Read the original emmer.devDiscussion

Discussion

Commenters mostly suggest existing tools instead, such as make -j, GNU Parallel's sem command, and pueue. One commenter says Bash concurrency is useful when a shell script grows too slow and rewriting it in another language is not practical.

Sources

Published: First seen: Читать по-русски

Open as a page