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 github.com/samsmi7h/foreach@latest
foreach
will replace __
(double underscore) with each element in the list.
$ 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
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 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" }
Email me: sam AT this domain, or Tweet me.