Home > front end >  Chicken-And-Egg-Situation: Function for running commands in the background
Chicken-And-Egg-Situation: Function for running commands in the background

Time:12-12

I fear this might be a duplicate, but I couldn't find a matching question.

I mostly work on the command line. If i.e. I want to simply open a pdf-file, I want to keep my actual commandline working and not being flooded with whatsoever output.

In general

evince my_file.pdf </dev/null &>/dev/null &

does the job...but typing that is not very convenient. So I tried to add a function:

function exec_in_background_silent() {
    "$@" </dev/null &>/dev/null &
}

That kind of works for the purpose to run the passed command detached...but calling it like this:

exec_in_background_silent evince my_file.pdf

Makes me loose my commandline again, because I think now it waits for the function itself to finish :(

It works perfectly fine, if I add another ampersand:

exec_in_background_silent evince my_file.pdf &

But: Is there a way to get rid of it?

(evince is maybe a bad example, because it isn't very talkative anyway...but there are others ;))

Edit for more details:

I'm running Ubuntu

echo "${BASH_VERSION}"
5.0.17(1)-release
  1. After calling it the command line is locked
  2. Pressing Enter get's me new empty lines
  3. Pressing [strg] [c] gives the following output and terminates evince
exec_in_background_silent evince my_file.pdf
[1] 12234







^C
[1]   Fertig                   < /dev/null &> /dev/null

CodePudding user response:

In manpage of bash, it says:

When bash starts a job asynchronously (in the background), it prints a line that looks like:

[1] 25647  

indicating that this job is job number 1 and that the process ID of the last process in the pipeline associated with this job is 25647. All of the processes in a single pipeline are members of the same job. Bash uses the job abstraction as the basis for job control.

And @Dimitre Radoulov said in this other SO post:

you could supress that output by putting the call in a subshell:

(echo "Hello I'm a background task" &)

So, in order to avoid the job number and process ID output line, you should change your function like this:

function exec_in_background_silent() {
    ("$@" </dev/null &>/dev/null &)
}
  • Related