4

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?

Atomiklan
  • 5,164
  • 11
  • 40
  • 62

2 Answers2

6

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
$ 
Digital Trauma
  • 15,475
  • 3
  • 51
  • 83
6

The correct syntax would be

FUNCTION > /dev/null 2>&1 &

Since & is a command terminator just like ;, you need to include the output redirections in the command that runs FUNCTION, not the following command.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Awww DigitalTrauma beat you too it. Thank you though. This is correct as well for anyone out there searching for a similar solution. – Atomiklan Apr 29 '14 at 18:45
  • I spent too much time trying to picture how your command worked, and trying to think why a command that consists of *nothing* but output redirections is accepted by `bash` :) – chepner Apr 29 '14 at 18:47