10

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

Tad Donaghe
  • 6,625
  • 1
  • 29
  • 64
chemila
  • 4,231
  • 4
  • 22
  • 18
  • The only way works for me is here https://stackoverflow.com/a/14152313/6706875, `kill -13 pid`, which will not generate any default `kill` output – Lampard Dec 21 '19 at 00:00

4 Answers4

19

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
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
  • disown has implication of shell not sending `SIGHUP` to the child when it terminates, see [this question](http://unix.stackexchange.com/questions/3886/difference-between-nohup-disown-and). Here is the [answer](http://stackoverflow.com/a/5722850/52499). – x-yuri May 24 '13 at 15:14
6

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

Community
  • 1
  • 1
Roel Van de Paar
  • 2,111
  • 1
  • 24
  • 38
  • This can be slightly improved by changing the kill -9 statement to: kill -9 $PID 2>/dev/null This is because the kill may also output other messages like: line 3: kill: (3968) - No such process Depending on what the script is doing – Roel Van de Paar Apr 18 '12 at 00:02
0

Another way to disable job notifications is to put your command to be backgrounded in a sh -c 'cmd &' construct.

#!/bin/bash

# ...

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

# ...
phily
  • 11
-2

I was able to accomplish this by redirecting the output of the command that I am running in the background. In your case it would look like:

sleep 20 >>${LOG_FILE} 2>&1 &

... or if you do not want a log file:

sleep 20 &> /dev/null &

Then, when you want to kill that background process' PID, it will not show on standard out.

Joey Cote
  • 342
  • 5
  • 13