Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shield the kill output [duplicate]

Tags:

bash

shell

I run a script like:

sleep 20 &
PID=$!
kill -9 $PID >/dev/null 2>&1

I dont want the script show the output like:

line 51: 22943 Killed  sleep

I have no idea why this happen, I have redirect the output to /dev/null

like image 778
chemila Avatar asked Nov 10 '11 04:11

chemila


People also ask

What is the killall command in Linux?

The killall command is used to kill processes by name. By default, it will send a SIGTERM signal. The killall command can kill multiple processes with a single command.

What does the kill-9 command do?

The kill -9 command sends a SIGKILL signal indicating to a service to shut down immediately. An unresponsive program will ignore a kill command, but it will shut down whenever a kill -9 command is issued.

How do I Kill a process in Xkill?

If a server has opened a number of unwanted processes, xkill will abort these processes. If xkill is run without specifying a resource, then an interface will open up that lets the user select a window to close. When a process cannot be closed any other way, it can be manually killed via command line.

What is the difference between killall-O 15m and pkill?

The killall -o 15m command will kill all processes that are older than 15 minutes, while the killall -y 15m command will kill all processes that are less than 15 minutes. The pkill command is similar to the pgrep command, in that it will kill a process based on the process name, in addition to other qualifying factors.


2 Answers

The message isn't coming from either kill or the background command, it's coming from bash when it discovers that one of its background jobs has been killed. To avoid the message, use disown to remove it from bash's job control:

sleep 20 &
PID=$!
disown $PID
kill -9 $PID
like image 86
Gordon Davisson Avatar answered Oct 21 '22 09:10

Gordon Davisson


This can be done using 'wait' + redirection of wait to /dev/null :

sleep 2 &
PID=$!
kill -9 $PID
wait $PID 2>/dev/null
sleep 2
sleep 2
sleep 2

This script will not give the "killed" message:

-bash-4.1$ ./test
-bash-4.1$ 

While, if you try to use something like:

sleep 2 &
PID=$!
kill -9 $PID 2>/dev/null
sleep 2
sleep 2
sleep 2

It will output the message:

-bash-4.1$ ./test
./test: line 4:  5520 Killed                  sleep 2
-bash-4.1$

I like this solution much more than using 'disown' which may have other implications.

Idea source: https://stackoverflow.com/a/5722850/1208218

like image 44
Roel Van de Paar Avatar answered Oct 21 '22 08:10

Roel Van de Paar