I’ve got a nasty dose of bashfail this morning. I had a bash one-liner which generated a list of strings. I needed to iterate over that list in xargs, but the command in xargs was itself a dirty multi-command one-liner :
crazy | stuff | xargs -i {} this {} | that {} (with this and that expanded by xargs, not the shell)
I solved it by generating the command in xargs using ‘echo’, and then passing that into the shell. Example :
crazy | stuff | xargs -i {} echo ” this {} | that {} ” | sh
Is this the cleanest way of doing it ? This works fine, but loses readability points !
That way is fine. The | is a function of the shell, but xargs just execs the command you pass to it so escaping the pipes just makes the process think you’re passing a | character on the command line. You can wrap the whole command line inside a shell by passing ‘sh -c’ to xargs instead of echo, like this:
crazy | stuff | xargs -i {} sh -c “this {} | that {}”
That doesn’t really add anything to your current method, though, and you do get the benefit of being able to pipe to a file for sanity checks if you use echo.
Posted by craiga | March 23, 2009, 11:15 amLots of people on twitter have pointed out that for loops would have led to the most readable format for this code – good suggestion !
Posted by andy | March 23, 2009, 12:22 pm