Home

foreach - Bash alias to execute command on each line

$$769
https://toast.ooo/u/cm0002 posted on Feb 19, 2026 14:28

Just wanted to share an alias I have in use and found it useful again. It’s a simple wrapper around xargs, which I always forget how to use properly, so I set up an alias for. All it does is operate on each line on stdout.

The arguments are interpreted as the command to execute. The only thing to remember is using the {} as a placeholder for the input line. Look in the examples to understand how its used.

# Pipe each line and execute a command. The "{}" will be replaced by the line.
#
# Example:
#   cat url.txt | foreach echo download {} to directory
#   ls -1 | foreach echo {}
#   find . -maxdepth 2 -type f -name 'M*' | foreach grep "USB" {}
alias foreach='xargs -d "\n" -I{}'

Useful for quickly operating on each line of a file (in example to download from list of urls) or do something with any stdout output line by line. Without remembering or typing a for loop in terminal.

OC by @thingsiplay@lemmy.ml

https://toast.ooo/post/12355874
Reply
$$772
https://programming.dev/u/secana posted on Feb 19, 2026 14:32
In reply to: https://toast.ooo/post/12355874

Cool little trick!

https://programming.dev/comment/22276395
Reply
$$790
https://sh.itjust.works/u/wildbus8979 posted on Feb 19, 2026 14:55
In reply to: https://toast.ooo/post/12355874

Don’t steal people’s content, at least crosspost properly.

https://sh.itjust.works/comment/23861031
Reply
$$860
https://programming.dev/u/stewie410 posted on Feb 19, 2026 15:57
In reply to: https://toast.ooo/post/12355874

Or use a while-read loop anyway?

while read -r foo; do
  cmd "${foo}" 
done < <(ls -1)

The find example should just use -exec grep "USB" {} + also, though -exec generally is the correct way to do this.

https://programming.dev/comment/22277957
Reply
$$983
https://monero.town/u/GrumpyBike1020 posted on Feb 19, 2026 17:57
In reply to: https://sh.itjust.works/comment/23861031

See the link in this users profile which explains why

https://monero.town/comment/7865218
Reply
$$1034
https://sh.itjust.works/u/wildbus8979 posted on Feb 19, 2026 19:04
In reply to: https://monero.town/comment/7865218

I know why. The OP decided to post where they decided to post, it’s frankly unethical to steal OP’s shit and not crosspost properly.

https://sh.itjust.works/comment/23865753
Reply