Sam

🚀 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.

Install

go install github.com/samsmi7h/foreach@latest

Use

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

Simple Example

$ ls ./ | foreach echo __

Makefile
README.md
main.go
$ ls | foreach printf "File name: %s \n" __

File name: Makefile
File name: README.md
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 https://mydomain.com/users | jq .[].id | IFS=\n foreach curl https://mydomain.com/user/__

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

Questions?

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