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.

  • non_burglar@lemmy.world
    link
    fedilink
    arrow-up
    2
    ·
    3 hours ago

    Be careful.

    Because it only formats stdin streams to into string(s), xargs can be very dangerous, depending on the command to which the arguments are being passed.

    Xargs used to be a practical way to get around bash globbing issues and parenthetical clause behavior, but most commands have alternate and safer ways of handling passed arguments.

    find -exec is preferable to xargs to avoid file expansion “bombs”, plus find doesn’t involve the shell, so it doesn’t care about whitespace problems.