Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent output from called bash function in subshell

If I call a function in bash, and that function itself is designed to output messages to the terminal using printf, how can I suppress that functionality. Allow me to explain further.

Normally I would have a main script. This script calls a function. That function does its normal stuff and outputs to the terminal using printf.

I am trying to create an alternative option where you can say, run that function in the background and don't output anything.

Normally I would think to do the following:

FUNCTION & > /dev/null 2>&1

This will run the normal function in the background and discard all output.

It seems to work at first. Where the messages usually appear is blank and the main script finishes running. Once back to a prompt though, the function(s) (which is looped for lots of different things) complete and start outputting to the terminal below the prompt.

Thoughts?

like image 364
Atomiklan Avatar asked Oct 14 '25 14:10

Atomiklan


1 Answers

If you need to put the function in the background, the & control operator needs to go right at the end of the command, after all redirection specifications:

$ function myfunc() {
> printf "%s\n" "normal message"
> printf "%s\n" "error message" 1>&2
> }
$ myfunc
normal message
error message
$ myfunc > /dev/null 2>&1 &
[2] 12081
$ 
[2]+  Done                    myfunc > /dev/null 2>&1
$ 
like image 50
Digital Trauma Avatar answered Oct 17 '25 02:10

Digital Trauma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!