19 ms·
An Opinionated Guide to Xargs
- fiddlerwoaroof 5y agoI frequently find myself reaching for this pattern instead of xargs: do_something | ( while read -r v; do . . . done ) I’ve found that it has fewer edge cases (except it creates a subshell, which can be avoided in some shells by using braces instead of parens)
- tomcam 5y agoThank you. Your comment coalesced a number of things in my mind that I hadn’t grasped properly as a UNIX midwit, especially the braces thing.
- ptspts 5y agoFor thousands of arguments this sloution is much slower (high CPU usage) than xargs, because either it implements the logic as a shell script (slow) or it runs an external program for each argument (slow).
- fiddlerwoaroof 5y agoSure, if performance matters use xargs. I find this is easier to read and think about.
- aaaaaaaaaaab 5y agoSome additional tips: 1. You don't need the parentheses. 2. If you use process substitution [1] instead of a pipe, you will stay in the same process and can modify variables of the enclosing scope: i=0 while read -r v; do ... i=$(( i + 1)) done < <(do_something) The drawback is that this way `do_something` has to come after `done`, but that's bash for you ¯\_(ツ)_/¯ [1] https://www.gnu.org/software/bash/manual/html_node/Process-Substitution.html https://www.gnu.org/software/bash/manual/html_node/Process-S...
- fiddlerwoaroof 5y agoYeah, although I use the parentheses mostly because I like how it reads. And that process substitution trick is important too. I think the redirection can come first, though (not at a computer to test): < <( do_something ) while read . . .
- aaaaaaaaaaab 5y agoYeah, for commands, the input/output redirections can precede them, but for some reason it doesn't work for builtin constructs like `while`: $ < <( echo foo ) while read -r f; do echo "$f"; done -bash: syntax error near unexpected token `do' $ < <( echo foo ) xargs echo foo $ bash --version GNU bash, version 5.1.4(1)-release (x86_64-apple-darwin20.2.0)
- fiddlerwoaroof 5y agoMaybe wrap the loop either with parentheses or braces?
- aaaaaaaaaaab 5y agoTried that, but nope :D I'll let you figure this one out once you get near a computer!
- entire-name 5y agoRedirection like this doesn't seem to work if it comes first on GNU bash 5.0.17(1)-release. For documentation purposes, this is the exact thing I tried to run: $ < <(echo hi) while read a; do echo "got $a"; done -bash: syntax error near unexpected token `do' $ while read a; do echo "got $a"; done < <(echo hi) got hi Maybe there is another way...
- JNRowe 5y agoOne way which isn't great, but an option nonetheless… The zsh parser is happy with that form: $ zsh -c '< <(echo hi) while read a; do echo "got $a"; done' got hi My position isn't that it is a good reason to switch shells, but if you're using it anyway then it is an option.
- aaaaaaaaaaab 5y agoAlso for the `while` enthusiasts, here's how you zip the output of two processes in bash: paste -d \\n <(do_something1) <(do_something2) | while read -r var1 && read -r var2; do ... # var1 comes from do_something1, var2 comes from do_something2 done
- thayne 5y agocreating a subshell can lead to some surprising behavior if you aren't careful though.
- rcpt 5y agoawk '{ print your_command }' | bash Never can remember all the -I stuff around xargs
- chubot 5y agoThis is like the sed|bash anti-pattern mentioned in the original post, and quoted in the appendix on shell injection. I wouldn't say "never use it", but I would hesitate to ever put it in a script, vs. doing a one-off at the command line.
- rcpt 5y agoYou don't pipe to bash on the first run. Use awk/sed without piping to workshop your commands. Once you've got them right send over to bash. This is far superior to futzing with xargs interactive or whatever dry run feature they have.
- chubot 5y agoSee the string injection comment: http://www.oilshell.org/blog/2021/08/xargs.html#more-comments http://www.oilshell.org/blog/2021/08/xargs.html#more-comment... https://lobste.rs/s/wlqveb/xargs_considered_harmful#c_kwsxtc https://lobste.rs/s/wlqveb/xargs_considered_harmful#c_kwsxtc
- HMH 5y agoI always wonder why something like xargs is not a shell built-in. It's such a common pattern, but I dread formulating the correct incantation every time. I was happy to read that the author comes to the same conclusion and proposes an `each` builtin (albeit only for the Oil shell)! Like that there is no need to learn another mini language as pointed out.
- JNRowe 5y agoIf you're a zsh user it offers a version of something like xargs in zargs¹. As the documentation shows it can be really quite powerful in part because of zsh's excellent globbing facilities, and I think without that support it wouldn't be all that useful as a built-in. I'd also perhaps argue that the reason we don't want xargs to be a built-in is precisely because of zargs and the point in your second paragraph. If it was built-in it would no doubt be obscenely different in each shell, and five decades later a standard that no one follows would eventually specify its behaviour ;) ¹ https://zsh.sourceforge.io/Doc/Release/User-Contributions.html https://zsh.sourceforge.io/Doc/Release/User-Contributions.ht... - search for "zargs", it has no anchor. Sorry.
- senkora 5y agoI always think of xargs as the inverse of echo. echo converts arguments to text streams, and xargs converts text streams to arguments.
- 0xdeadb00f 5y agoThat's a pretty neat way of thinking about it!
- lisper 5y agoNote that the suggested: rm $(ls | grep foo) will not work if you have file names that contain spaces. Shell programming is planted thick with landmines like this.
- ViViDboarder 5y agoThe linked article doesn’t suggest this. They explicitly suggest against it. > Besides the extra ls, the suggestion is bad because it relies on shell's word splitting. This is due to the unquoted $(). It's better to rely on the splitting algorithms in xargs, because they're simpler and more powerful.
- yakubin 5y agoUsing "ls" is also problematic, because it will outright skip large classes of characters.
- pwg 5y agoSince the blog author is commenting here, you have this statement part way down your blog: > That is, grep doesn't support an analogous -0 flag. However, the GNU grep variant does have an analogous flag: -z, --null-data Treat the input as a set of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names.
- chubot 5y agoAh cool, I didn't know that! I'll update the blog post. (What a cacophony of flags) Edit: It seems that grep -0 isn't taken for something else and they should have used it for consistency? The man page says it's meant to be used with find -print0, xargs -0, perl -0, and sort -z (another inconsistency)
- cben 5y agoSee https://github.com/fish-shell/fish-shell/issues/3164#issuecomment-354600352 https://github.com/fish-shell/fish-shell/issues/3164#issueco... for incomplete but large survey of NUL flags. Takeaways: (1) There is no consistency in flag names, even --long ones (2) impressively many tools do support it! Note that some affect only input or only output. (3) All do NUL-terminated, not NUL-separated. That's fortunate — matches \n usage, and gives distinct representations for [] vs [""].
- l0b0 5y agoIt's best to give up on any kind of consistency between command options. Any project is free to do anything it wants, and they all do. Someone is eventually going to come up with standard N+1[1] which does things consistently, but they are going to have to either recreate a bazillion tools or create some sort of huge translation framework configuration on top of existing tools to get there. And even then it'll take literally decades before people migrate away from the current tools. Basically, the sad truth is this isn't going to happen. [1] https://xkcd.com/927/ https://xkcd.com/927/
- deleted 5y ago
- ahawkins 5y agoXargs ftw!
- kazinator 5y agoIn 2002, I implemented xargs in Lisp, in the Meta-CVS project. It is quite necessary, because you cannot pass an arbitrarily large command line or environment in exec system calls. Of course, this doesn't have the problem requiring -0 because we're not reading textual lines from standard input, but working with lists of strings. ;;; This source file is part of the Meta-CVS program, ;;; which is distributed under the GNU license. ;;; Copyright 2002 Kaz Kylheku (in-package :meta-cvs) (defconstant *argument-limit* (* 64 1024)) (defun execute-program-xargs (fixed-args &optional extra-args fixed-trail-args) (let* ((fixed-size (reduce #'(lambda (x y) (+ x (length y) 1)) (append fixed-args fixed-trail-args) :initial-value 0)) (size fixed-size)) (if extra-args (let ((chopped-arg ()) (combined-status t)) (dolist (arg extra-args) (push arg chopped-arg) (when (> (incf size (1+ (length arg))) *argument-limit*) (setf combined-status (and combined-status (execute-program (append fixed-args (nreverse chopped-arg) fixed-trail-args)))) (setf chopped-arg nil) (setf size fixed-size))) (when chopped-arg (execute-program (append fixed-args (nreverse chopped-arg) fixed-trail-args))) combined-status) (execute-program (append fixed-args fixed-trail-args)))))
- legobmw99 5y agoThis is only tangentially related, but after all the posts here the last few days about thought terminating cliches, I can’t help but reflect on the “X considered harmful” title cliche
- JadeNB 5y agoIs it thought terminating, though? "X considered harmful" seems more intended to spark discussion in an intentionally inflammatory way than to stifle it. (In any case, this surely is tangential, since the title is not "X considered harmful" for any value of X—at best it comments on a post by that title, as, indeed, you are doing.)
- MichaelGroves 5y agoWould you say the title terminated your consideration of the article?
- legobmw99 5y agoNo I think if anything seeing it was a response to “xargs considered harmful” made me take the authors side quicker
- Zababa 5y agoI've been thinking about titles, and it's hard to make a good one that doesn't look like a total cliché. "X considered harmful", "an opinionated guide to X", some kind of joke or reference, what could be a collection of tags (X, Y and Z), "things I have learned doing X", etc.
- ineedasername 5y agoIn this case a less cliche/click-baity title could simply be: "A Response to Xargs Criticism"
- Zababa 5y agoI think this title is fine, it's mostly that after spending some time on Hacker News all the titles start to look the same.
- MichaelGroves 5y ago> A lobste.rs user asked why you would use find | xargs rather than find -exec. The answer is that it can be much faster. If you’re trying to rm 10,000 files, you can start one process instead of 10,000 processes! Fair enough, but I still favor find -exec. I find it generally less error prone, and it's never been so slow that I wished I had instead used xargs. Also, if you're specifically using -exec rm with find, you could instead use find with -delete.
- bobbylarrybobby 5y agoYou can also use `find -exec` with `'+'` instead of `';'` as the terminator. This will call `rm` on all of the found files in one call.
- masklinn 5y agoI tend to prefer xargs because it works in more contexts e.g. I've got a tool which automatically generates databases but sometimes the cleanup doesn't work. `find -exec` does nothing, but `xargs -n1 dropdb` (following an intermediate grep) does the job. From there, it makes sense to… just use xargs everywhere. And I always fail to remember that the -exec terminator must be escaped in zsh, so using -exec always takes me multiple tries. So I only use -exec when I must (for `find` predicates).
- shoo 5y agoi agree. `find somewhere -exec some_command {} +` can be dramatically faster. but it does not guarantee a single invocation of `some_command`, it may make multiple invocations if you pass very large numbers of matching files after spending a bit of time reading the man page for find, i rarely use xargs any more. find is pretty good. tangent: another instance i've seen where spawning many processes can lead to bad performance is in bash scripts for git pre-recieve hooks, to scan and validate the commit message of a range of commits before accepting them. it is pretty easy to cobble together some loop in a bash script that executes multiple processes _per commit_. that's fine for typical small pushes of 1-20 commits -- but if someone needs to do serious graph surgery and push a branch of 1000 - 10,000 commits that can can cause very long running times -- and more seriously, timeouts, where the entire push gets rejected as the pre-receive script takes too long. a small program using the libgit2 API can do the same work at the cost of a single process, although then you have the fun of figuring out how to build, install and maintain binary git pre-receive hooks.
- westurner 5y agoWanting verbose logging from xargs, years ago I wrote a script called `el` (edit lines) that basically does `xargs -0` with logging. https://github.com/westurner/dotfiles/blob/develop/scripts/el.py https://github.com/westurner/dotfiles/blob/develop/scripts/e... It turns out that e.g. -print0 and -0 are the only safe way: line endings aren't escaped: find . -type f -print0 | el -0 --each -x echo GNU Parallel is a much better tool: https://en.wikipedia.org/wiki/GNU_parallel https://en.wikipedia.org/wiki/GNU_parallel
- LeoPanthera 5y agoYeah but xargs doesn't refuse to run until I have agreed to a EULA stating I will cite it in my next academic paper.
- jeffbee 5y agoparallel doesn't either, it just nags. I agree about how silly and annoying it is. Imagine if every time the parallel author opened Firefox he got a message reminding him to personally thank me if he uses his web browser for research, or if every time his research program calls malloc he has to acknowledge and cite Ulrich Drepper. Very very silly. Parallel is the better tool but the nagware impairs its reputation.
- blibble 5y agoor every time a process called fork() you had to read some stupid message
- michaelsbradley 5y agoecho will cite | parallel --bibtex
- chubot 5y ago(author here) Hm I don't see either of these points because: GNU xargs has --verbose which logs every command. Does that not do what you want? (Maybe I should mention its existence in the post) xargs -P can do everything GNU parallel do, which I mention in the post. Any counterexamples? GNU parallel is a very ugly DSL IMO, and I don't see what it adds. -- edit: Logging can also be done with by recursively invoking shell functions that log with the $0 Dispatch Pattern, explained in the post. I don't see a need for another tool; this is the Unix philosophy and compositionality of shell at work :)
- andy81 5y agoToday I appreciated Powershell
- jmholla 5y agoCan you expand on that? I've never had trouble leveraging xargs and find it aligns well with shell piping.
- bialpio 5y agoNot OP but to me the best thing about PowerShell is that it recognizes that text is not always the best way to output results from commands if you care about creating pipelines. In short, it passes objects around so there's no need for parsing text.
- bialpio 5y agoTwo examples from the article translated into PS (sorry, I'm a bit rusty so the second one may not be the shortest possible): PS> "alice", "bob" | echo PS> Get-ChildItem . -Include "*test.cpp","*test.py" -Recurse | foreach { Remove-Item $_.Name } No text parsing in sight, and the object attributes can be tab-completed from the shell (e.g. I tab-completed the `$_.Name`).
- andy81 5y agoThanks, we were thinking of the same thing.
- Arnavion 5y agoYou don't need to `foreach { Remove-Item $_.Name }` because Remove-Item can take the objects returned by Get-ChildItem directly. Also, expanding the regex into `-Include` parameters is somewhat cheating since `-Include` only takes globs, and it just so happens that that particular regex can be converted into globs. The general equivalent is: gci -re | ?{ $_.Name -match '.*_test\.(py|cc)' } | ri (I used the shorter aliases because someone will probably read yours and reinforce the stereotype that PS is overly verbose.)
- WhatIsDukkha 5y agoI tend to reach for gnu parallel instead of xargs - https://www.gnu.org/software/parallel/parallel_alternatives.html#differences-between-xargs-and-gnu-parallel https://www.gnu.org/software/parallel/parallel_alternatives.... parallel is probably on the complex side but its also been actively developed, bugfixed and had a lot of road miles from large computing users.
- chubot 5y agoI mention it here: https://www.oilshell.org/blog/2021/08/xargs.html#xargs-p-automatically-parallelizes-tasks https://www.oilshell.org/blog/2021/08/xargs.html#xargs-p-aut... What does it do that xargs and shell can't? (honest question)
- leephillips 5y agoRemote execution.
- chubot 5y agoI'd like to see a demo of it! I will try rewriting it with the $0 Dispatch Pattern and ssh :)
- xmcqdpt2 5y agoGood luck balancing node usage! Here is an example of how it works, https://docs.computecanada.ca/mediawiki/index.php?title=GNU_Parallel&mobileaction=toggle_view_desktop#Running_on_Multiple_Nodes https://docs.computecanada.ca/mediawiki/index.php?title=GNU_... This + restart capabilities make gnu parallel very well suited to running 1000s of compute-heavy jobs on HPC clusters.
- figomore 5y agoI used Parallel to distribute the rendering of a little Blender animation It worked very well. https://github.com/tfmoraes/blender_gnu_parallel_render/blob/master/render_blender_parallel.sh https://github.com/tfmoraes/blender_gnu_parallel_render/blob...
- masklinn 5y ago> Shell functions and $1, instead of xargs -I {} > -n instead of -L (to avoid an ad hoc data language) Apparently GNU xargs is missing it, but BSD xargs has -J, which is a `-I` which works with `-n`: with `-I` each replstr gets replaced by one of the inputs, with `-J` the replstr gets replaced by the entire batch (as determined by `-n`).
- aaaaaaaaaaab 5y agoI would recommend using -0 instead of -d, as the latter is not supported on BSD (and macOS) xargs: do_something | tr \\n \\0 | xargs -0 ...
- derriz 5y agoI wish this was the default behavior of xargs (the 'tr \\n \\0 | xargs -0' bit). I don't know why xargs splits on spaces and tabs as well as newlines by default and doesn't even have a flag to just split on lines. Ok filenames can theoretically have newlines in them but I'd be happy to deal with that weird case. I can't recall ever having encountered it in years of using bash on various systems. Shell pipes would then orthogonally provide the stuff like substitution that xargs does in it's own unique way (that I just can't be bothered learning) - instead you'd just pipe the find output through sed or 'grep -v' or whatever you wanted before piping into xargs. I guess that's what aliases but I'm too lazy anymore to bother with configuring often short-lived systems all the time.
- fl0wenol 5y agoxargs defaults to all whitespace because it was designed to get around the problem of short argv lengths (like, I'm talking 4k or less on older Unix-y systems, sometimes as low as 255 bytes). So the defaults went with principle of least surprise, pretending it's like a very long args list that you could theoretically enter at the shell, including quotes. You could, for example, edit the args list in vi and line split / indent as you please but not impact the end result.
- agumonkey 5y agoI used to have bash fun like `curry { xargs -I {} $1 }` or something like that. Pretty useful to simplify one liners.
- pgtan 5y agoFWIW AIX also has an apply command https://www.ibm.com/docs/en/aix/7.2?topic=apply-command https://www.ibm.com/docs/en/aix/7.2?topic=apply-command
- 2OEH8eoCRo0 5y agoI spent a year using AIX at my previous job and never heard of this or saw anybody use it. Is it new in 7.2? We were far behind on AIX 6.
- pgtan 5y agoNo idea how old this command is. Most of the AIX/Linux admins I knew were very bad shell programmers, skills end with awfull for-loops, useless use of cat, and awk '{print $3}'.
- yudlejoza 5y agoOf xargs, for, and while, I have limited myself to while. It's more typing everytime but saves me from having to remember so many quirks of each command. cat input.file | ... | while read -r unit; do <cmd> ${unit}; done | ... between 'while read -r unit' and 'while IFS= read -r unit' I can probably handle 90% of the cases. (maybe I should always use IFS since I tend to forget the proper way to use it).
- patrickdavey 5y agoWould you mind expanding with a couple of examples? (E.g. using "foo bar" as a single line or split by whitespace). I suspect I'll really like your way of doing things, but an example would be very handy.
- yudlejoza 5y agoThe example of "foo bar" didn't work with while but inserting tr fixes it: echo "foo bar" | tr ' ' '\n' | while read -r var; do echo ${var}; done For examples in general, I guess something like "cat file.csv" could work. (the difference between using IFS= and not using it is essentially whether we want to preserve leading and trailing whitespaces or not. If we want to preserve, then we should use IFS=).
- scottlamb 5y agoThat way will bite you when the tasks in question are cheaper than fork+exec. There was a thread just the other day in which folks were creating 8 million empty files with a bash loop over touch. But it's 60X faster (really, I measured) to use xargs, which will do batches (and parallelism if you tell it to). https://news.ycombinator.com/item?id=28192946 https://news.ycombinator.com/item?id=28192946
- jordemort 5y agoI appreciate this. If I wrote my own opinionated guide to xargs, it would be a single profane sentence.
- deleted 5y ago[deleted]
- l0b0 5y agoI scanned until I saw `ls | egrep '.*_test\.(py|cc)' | xargs -d $'\n' -- rm`, and then stopped. This is a terrible idea[1][2]. [1] https://mywiki.wooledge.org/ParsingLs https://mywiki.wooledge.org/ParsingLs [2] https://unix.stackexchange.com/q/128985/3645 https://unix.stackexchange.com/q/128985/3645
- tyingq 5y agoI'm surprised the links don't mention find. The -print0 flag makes it safe for crazy filenames, which pairs with the xargs -0 flag, or the perl -0 flag, etc. And you have -maxdepth if you don't want it to trawl.
- reilly3000 5y agoI’m unconvinced by the post OP was responding to. It’s a utility, it provides some means to get things done. *nix provides many means of parsing text and running commands, each have their idioms based on their own axioms. It seems as if a composer is lambasting the clarinet because they don’t care for its fingerings. I’ve only used xargs sparingly, can somebody enlighten me as to why it’s bad, aside from the fact that there are other ways to do some things it does?
- thayne 5y agoI'm not sure I like the `$1` and shell function pattern. It might avoid the -I minilanguage, but at the cost of "being clever" in a way that takes a minute to wrap your head around. It's a neat trick, but I don't think it would be easy to understand if you are reading the code for the first time.
- t4p4n 5y agoi found nothing in this blog post useful other than string slicing/splitting. and you forgot put the ultimate flag of this program that is -r.
- thrwyexecbrain 5y agoIn Bash (not every shell supports this) functions can be exported, which enables this nice pattern with xargs: myfunc() { printf " %s" "I got these arguments:" "$@" $'\n' } export -f myfunc seq 6 | xargs -n2 bash -c 'myfunc "$@"' "$0"
- Karellen 5y agoI find that using the example of `rm` to discuss whether to pick `find -exec` or `find | xargs` rather strange, given the existence of `find -delete`. Maybe pick a different example operation to automate.
- michaelcampbell 5y ago> I've used -P 32 to make day-long jobs take an hour! You can't do that with a for loop. for file in *; do command_using_file & done wait ? I use variations on this all the time; pause while load is high, pause while 'x' or more things are running, sleep between invocations, etc. It may not be as convenient for some cases, but "can't do that..." is not quite correct either. The post is starting to feel like a hammer/nail argument, IMO.