xargs
xargs lets you chain together and patch up results from piped commands into other commands or applications.
$ find "start/path" -name "filename.txt" -print0 | xargs -0 -o vim
$ git branch --merged | egrep -v "(^\*|master|main|dev|staging)" | xargs git branch -d
It is invoked like xargs [option...] [command [initial-arguments]]. For instance, the end result of that first example would be vim {result of find command}, and the end result of the second would be git branch -d {result of egrep on results of git command}.
Another example is sending a list of lines in a file as arguments in a command.
file="/tmp/args"
touch "$file"
echo "first" >> "$file"
echo "second" >> "$file"
echo "third" >> "$file"
# Send these lines as arguments
xargs echo < "$file"
Options
$ xargs -0 --max-args=2
-0: Use\0as the delimiter, which is useful for filenames with spaces. Ensure piped command delimits using\0and not spaces.-d delim: Usedelimas your delimiter between arguments-E eof-str: Useeof-stras the signifier of end of file. When found, all following text is ignored.-n max-args: Use at mostmax-argsarguments per command line.-o: Allow interactive programs to access pipe output. e.g.find "start/path" -name "filename.txt" -print0 | xargs -0 -o vim. This will send the filename found withfindas the argument tovim.
Simple Version
You can do simple xargs recipes in shell using command substitution.
This example sends the output of one command as arguments to another command.
$ # xargs version
$ find "start/path" -name "filename.txt" -print0 | xargs -0 -o vim
$ # shell versions
$ vim `find "start/path" -name "filename.txt"`
$ vim $(find "start/path" -name "filename.txt")
References
- https://www.man7.org/linux/man-pages/man1/xargs.1.html
- https://askubuntu.com/a/1158337
- https://unix.stackexchange.com/a/5865
Incoming Links
Last modified: 202503011623