How do I run multiple background commands in bash in a single line?

前端 未结 8 1834
栀梦
栀梦 2020-11-28 19:11

I normally run multiple commands with something like this:

sleep 2 && sleep 3

or

sleep 2 ; sleep 3
<
8条回答
  •  伪装坚强ぢ
    2020-11-28 19:48

    You can use the bash command substitution $(command) like this:

    $(command1 ; command2) &
    

    Note that stdin and stdout are still linked to the parent process and redirecting at least the stdout can be tricky. So alternatively you can chain the commands in a single line then pass the string to the bash command to spawn a new process which will handle the execution.

    bash -c "command1 ; command2" & 
    

    This is especially useful in a bash script when you need to run multiple commands in background.

    This two statements should be equivalent. A bash process is spawn in both cases to handle the command (chain of commands) and the & at the end detaches the execution.

    This time you can add &>/dev/null before the & at the end of the command to redirect at least the stdout and avoid the output on the stdout of the parent process. Something like:

    bash -c "command1 ; command2" &>/dev/null &
    

提交回复
热议问题