问题
I used the following bash code:
for pid in `top -n 1 | awk '{if($8 == "R") print $1;}'`
do
kill $pid
done
It says:
./kill.sh: line 3: kill: 29162: arguments must be process or job IDs
./kill.sh: line 3: kill: 29165: arguments must be process or job IDs
./kill.sh: line 3: kill: 29166: arguments must be process or job IDs
./kill.sh: line 3: kill: 29169: arguments must be process or job IDs
What causes this error and how do I kill processes in Bash?
回答1:
Probably this awk
command is not returning any reliable data, in any case theres a much easier way:
kill `pidof R`
Or:
killall R
回答2:
It seems there may be a (possibly aliased) script kill.sh
in your current directory which is acting as an intermediary and calling the kill
builtin. However, the script is passing the wrong arguments to the builtin. (I can't give details without seeing the script.)
Solution.
Your command will work fine using the kill
builtin. The simplest solution is to ensure you use the bash builtin kill
. Execute:
chmod a-x kill.sh
unalias kill
unset -f kill
This will prevent the script from running and remove any alias or function that may interfere with your use of the kill
builtin.
Note.
You can also simplify your command:
kill `top -n 1 | awk '{if($8 == "R") print $1;}'`
Alternatively...
You can also use builtin
to bypass any functions and aliases:
builtin kill `top -n 1 | awk '{if($8 == "R") print $1;}'`
回答3:
Please try:
top -n 1 | awk '{print "(" $1 ") - (" $8 ")";}'
to understand how $1 and $8 are evaluated
Please also post the content of ./kill.sh and explain the purpose of this script
回答4:
I usuallly use:
pkill <process name>
In your case:
pkill R
Note that this will kill all the running instances of R
, which may or may not be what you want.
回答5:
top
issues a header you need to suppress or skip over.
Or maybe you can use ps
since its output is highly configurable.
Also note that kill
accepts multiple PIDs, so there's no reason to employ a loop.
kill $( ps h -o pid,state | awk '$2 == "R" { print $1 }' )
回答6:
In addition to awk
, sed
can provide pid
isolation in the list for kill
:
kill $(ps h -o pid,state | grep R | sed -e 's/\s.*$//')
Basically, the opposite side of the same coin.
来源:https://stackoverflow.com/questions/30542550/how-to-kill-processes-in-bash