Escaping a pipe inside xargs
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 !
2 Comments
Comments
2 Responses to “Escaping a pipe inside xargs”
Leave a Reply
You must be logged in to post a comment.
March 23rd, 2009 at 11:15 am
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.
March 23rd, 2009 at 12:22 pm
Lots of people on twitter have pointed out that for loops would have led to the most readable format for this code – good suggestion !