Running bash commands in the background without pr

2019-01-16 15:54发布

To run a process in the background in bash is fairly easy.

$ echo "Hello I'm a background task" &
[1] 2076
Hello I'm a background task
[1]+  Done                    echo "Hello I'm a background task"

However the output is verbose. On the first line is printed the job id and process id of the background task, then we have the output of the command, finally we have the job id, its status and the command which triggered the job.

Is there a way to suppress the output of running a background task such that the output looks exactly as it would without the ampersand at the end? I.e:

$ echo "Hello I'm a background task" &
Hello I'm a background task

The reason I ask is that I want to run a background process as part of a tab-completion command so the output of that command must be uninterrupted to make any sense.

8条回答
beautiful°
2楼-- · 2019-01-16 16:28

Building off of @shellter's answer, this worked for me:

tyler@Tyler-Linux:~$ { echo "Hello I'm a background task" & disown; } 2>/dev/null; sleep .1;
Hello I'm a background task
tyler@Tyler-Linux:~$

I don't know the reasoning behind this, but I remembered from an old post that disown prevents bash from outputting the process ids.

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-16 16:30

You'll have to surround it with a sub-shell or process group (i.e. { ... }).

/home/shellter $ { echo "Hello I'm a background task" & } 2>/dev/null
Hello I'm a background task
/home/shellter $

IHTH

edit

as prompted by @Mark 's downvote, I have researched that this doesn't work correctly in bash. This does work as shown under ksh93.

Busy right now, but I'll update this answer with what I have included in comments to this and @Tizord 's answer, but I don't see an easy answer for how to redirect std-err from a backgrounded task. (It's probably possibly with exec manipulations)

查看更多
登录 后发表回答