how to stop bash from printing alerts?
When killing a process with kill -9 $PID &>/dev/null
in a script, a message is still printed to the terminal after the next command terminates. How do you stop this behaviour?
For example
while true; do
/usr/bin/dostuff -a -b -c
PID=$(pidof -o %PPID /usr/bin/dostuff)
sleep 1;
kill -KILL $PID &>/dev/null
echo "hello"
done
will print something like
hello
./my-cript.sh: line 12: 7134 Killed
/usr/bin/dostuff -a -b -c
When I only want it to print "hello"
EDIT: The clean solution is to either run the program in a subshell, or disown it.
#SOLUTION
while true; do
/usr/bin/dostuff -a -b -c &
disown
PID=$!
sleep 1;
kill -KILL $PID &>/dev/null
echo "hello"
done
Solution 1:
The output lines aren't redirected to /dev/null because they aren't STDOUT/STDERR from the kill process. They're output from the shell's job control mechanisms.
If you're using bash, you could run a disown immediately after the job invocation:
while true; do
/usr/bin/dostuff -a -b -c
### remove from shell job table
disown
PID=$(pidof -o %PPID /usr/bin/dostuff)
sleep 1;
kill -KILL $PID &>/dev/null
echo "hello"
done
I tested this in bash v3.2.39 on Debian Lenny, with /bin/sleep 10 &
in place of the above /usr/bin/dostuff
command:
./tmp.sh
hello
hello
hello
hello
^C
Solution 2:
The error redirection is ineffective because this message is not printed by kill; it is printed by the shell when the background job terminates (I assume a & was missing).
You can avoid this by running in a subshell, using parentheses (but be aware of other potential problems):
while true; do
(
/usr/bin/dostuff a b c &
PID=$!
sleep 1
kill -9 $PID
)
echo hello
done