Skip to content

Instantly share code, notes, and snippets.

@zmwangx
Last active October 12, 2021 08:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmwangx/9877838 to your computer and use it in GitHub Desktop.
Save zmwangx/9877838 to your computer and use it in GitHub Desktop.
Explains how to use custom script with xargs without eating up all arguments in the first call.

To use xargs with custom script that takes in a fixed number of arguments, we need to use the replacement feature of xargs. For instance, given a script that indends to take one argument, e.g.

$ cat awesome.sh                                                      
#!/bin/zsh
is_awesome=' is awesome!'
awesome_sentence=$1$is_awesome
echo $awesome_sentence

A naive xargs call

$ls -1 | xargs ./awesome.sh

eats up all arguments in the first call to ./awesome.sh, hence only dealing with the first line in ls -1: (here the directory contains four files: awesome.sh, gist, git, github)

awesome.sh is awesome!

However, if we use a replacement pattern: (the following code works on OS X; on other operating systems the -I option might be a bit different)

$ls -1 | xargs -I {} ./awesome.sh {}

we will get

awesome.sh is awesome!
gist is awesome!
git is awesome!
github is awesome!

which is truly awesome.


04/14/2014 update: Another nice way:

$ls -1 | xargs -L 1 ./awesome.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment