xargs short-circuit

Devin Teske devin.teske at fisglobal.com
Tue Feb 14 19:05:52 UTC 2012



> -----Original Message-----
> From: owner-freebsd-hackers at freebsd.org [mailto:owner-freebsd-
> hackers at freebsd.org] On Behalf Of Matthew Story
> Sent: Tuesday, February 14, 2012 10:35 AM
> To: freebsd-hackers at freebsd.org
> Subject: xargs short-circuit
> 
> After reading the man-page, and browsing around the internet for a minute,
> I was just wondering if there is an option in (any) xargs to short-circuit
> on first failure of [utility [arguments]].
> 
> e.g.
> 
> $ jot - 1 10 | xargs -e -n1 sh -c 'echo "$*"; echo exit 1' worker || echo $?
> 1
> 1
> 
> such that any non-0 exit code in a child process would cause xargs to stop
> processing.  seems like this would be a nice feature to have.
> 

You can achieve this quite easily with a sub-shell:

As a bourne-shell script:

#!/bin/sh
jot - 1 10 | ( while read ARG1 REST; do
	sh -c 'echo "$*"; exit 1' worker $ARG1 || exit $?
	shift 1
done )

Or interactively in sh/bash:

$ jot - 1 10 | ( while read ARG1 REST; do sh -c 'echo "$*"; exit 1' worker $ARG1
|| exit $?; shift 1;done )

Or interactively in csh/tcsh:

% jot - 1 10 | /bin/sh -c 'while read ARG1 REST; do sh -c '\''echo "$*"; exit
1'\'' worker $ARG1 || exit $?; shift 1; done'

-- 
Devin

_____________
The information contained in this message is proprietary and/or confidential. If you are not the intended recipient, please: (i) delete the message and all copies; (ii) do not disclose, distribute or use the message in any manner; and (iii) notify the sender immediately. In addition, please be aware that any message addressed to our domain is subject to archiving and review by persons other than the intended recipient. Thank you.


More information about the freebsd-hackers mailing list