Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing POSIX xargs from attempting to run an empty command

I'm not that good with bash, but I'm trying to create a script to kill some java processes:

/usr/ucb/ps -auxww    \
  | grep 'XUnit'      \
  | grep -v 'grep'    \
  | cut -c -2000      \
  | awk '{print $2;}' \
  | xargs kill

cut is used here because awk can fail with excessively long lines (see references to LINE_MAX limit in the POSIX specification for awk).

The problem occurs when there are no such processes - xargs tries to run kill with no arguments, resulting in an error.

My xargs does not accept -r or --no-run-if-empty args, as suggested in answers to a related question that doesn't specify POSIX compliance.

like image 346
awfun Avatar asked Dec 23 '15 16:12

awfun


1 Answers

Addressing specifically the question at hand, ignoring whether the approach at hand is actually an appropriate way to kill a process:

xargs sh -c '[ $# -gt 0 ] && exec "$0" "$@"' kill

This approach has xargs launch a shell which looks at the length of its argument list (which will be 0 if only kill is passed, as arguments following -c 'script' start with $0, not included in the $# count); that shell only runs the command given if at least one argument is given.

like image 179
Charles Duffy Avatar answered Nov 15 '22 03:11

Charles Duffy