🚀 Start Here

# `foreach` on the command line: `xargs` for the 21st Century

How do I loop or iterate through a list or array on the command line? Is there a for each bash function?

Upgrade your shell one-liners with a straightforward foreach idiom.

This CLI tool can take from a pipe any list, and iterates over it using any command you wish.

Like xargs for the 21st Century.


go install


foreach will replace __ (double underscore) with each element in the list.

Simple Example

$ ls ./ | foreach echo __

$ ls | foreach printf "File name: %s \n" __

File name: Makefile
File name:
File name: main.go

Split on a different character

By default it will split on tabs & new lines, which is the standard way to separate shell list elements.

But you can split by any charater you like to serve your use-case, using the POSIX-standard “IFS” environment variable.

Perhaps we want to split a string into a list, by commas:

$ echo 'first,second,third' | IFS="," ./foreach printf "element: %s \n" __

element: first
element: second
element: third

A Realistic Example

A curl request is returning an array of data. For each element, we want to take the ID, and make another request to get more info.

$ curl | jq .[].id | IFS=\n foreach curl

{ "id": 4285, "name": "Harry" }
{ "id": 9734, "name": "Hermione" }
{ "id": 3598, "name": "Ron" }


Email me: sam AT this domain, or Tweet me.