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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With