bash: silently kill background function process

kill $foo_pid
wait $foo_pid 2>/dev/null

BTW, I don't know about your massively cool progress bar, but have you seen Pipe Viewer (pv)? http://www.ivarch.com/programs/pv.shtml


Just came across this myself, and realised "disown" is what we are looking for.

foo &
foo_pid=$!
disown

boring_and_long_command
kill $foo_pid
sleep 10

The death message is being printed because the process is still in the shells list of watched "jobs". The disown command will remove the most recently spawned process from this list so that no debug message will be generated when it is killed, even with SIGKILL (-9).


Try to replace your line kill $foo_pid >/dev/null 2>&1 with the line:

(kill $foo_pid 2>&1) >/dev/null

Update:

This answer is not correct for the reason explained by @mklement0 in his comment:

The reason this answer isn't effective with background jobs is that Bash itself asynchronously, after the kill command has completed, outputs a status message about the killed job, which you cannot suppress directly - unless you use wait, as in the accepted answer.


This "hack" seems to work:

# Some trickery to hide killed message
exec 3>&2          # 3 is now a copy of 2
exec 2> /dev/null  # 2 now points to /dev/null
kill $foo_pid >/dev/null 2>&1
sleep 1            # sleep to wait for process to die
exec 2>&3          # restore stderr to saved
exec 3>&-          # close saved version

and it was inspired from here. World order has been restored.