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.

  • hades@feddit.uk
    link
    fedilink
    arrow-up
    11
    ·
    17 hours ago

    Nice! I used to do something like this, which avoids xargs altogether:

    cat urls.txt | while read url; do echo download $url; done
    
    • Static_Rocket@lemmy.world
      link
      fedilink
      English
      arrow-up
      8
      ·
      14 hours ago

      You can also avoid cat since you aren’t actually concatenating files (depending on file size this can be much faster):

      while read -r url; do echo "download $url"; done < urls.txt
      
    • davel [he/him]@lemmy.ml
      link
      fedilink
      English
      arrow-up
      8
      ·
      edit-2
      16 hours ago

      Usually this is the way. Once you enter xargs’ world, you lose access to your shell aliases, functions, and un-exported variables, which will often bite you in the ass.

    • thingsiplay@lemmy.mlOP
      link
      fedilink
      arrow-up
      8
      ·
      16 hours ago

      You should use -r option for read command to preserve backslashes. I was using while loops before too, but wanted to have a compact single command replacement. And doing it with a while loop as an alias (or function) didn’t work well, because the command has to be interpreted. xargs does exactly that, as it is designed for this kind of stuff. Other than having less stuff to type, I wonder if there are benefits from one over the other while vs xargs. In a script, I prefer writing full while loops instead.