Running bash commands in the background without printing job and process ids

前端 未结 8 1342
余生分开走
余生分开走 2020-12-07 22:09

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             


        
8条回答
  •  既然无缘
    2020-12-07 22:26

    The subshell solution works, but I also wanted to be able to wait on the background jobs (and not have the "Done" message at the end). $! from a subshell is not "waitable" in the current interactive shell. The only solution that worked for me was to use my own wait function, which is very simple:

    myWait() {
      while true; do
        sleep 1; STOP=1
        for p in $*; do
          ps -p $p >/dev/null && STOP=0 && break
        done
        ((STOP==1)) && return 0
      done
    }
    
    i=0
    ((i++)); p[$i]=$(do_whatever1 & echo $!)
    ((i++)); p[$i]=$(do_whatever2 & echo $!)
    ..
    myWait ${p[*]}
    

    Easy enough.

提交回复
热议问题