In a Bash script how to `nohup` multiple commands without using a string?
Feb 8, 12:40am

In a Bash script, if you want to run multiple commands with nohup without combining them into a single string, you can use one of these approaches:


1. Group Commands with Braces

Use { } to group commands and redirect output for the entire group:

bash
nohup { command1 command2 command3 } > output.log 2>&1 &
  • { } groups the commands, and the output of all commands is redirected to output.log.
  • The & at the end runs the group in the background.

Note: There must be a space after { and before }.


2. Use a Subshell

You can also use ( ) to run the commands in a subshell:

bash
nohup ( command1 command2 command3 ) > output.log 2>&1 &
  • This achieves the same result as braces but runs the commands in a subshell.

3. Separate nohup for Each Command

If you want each command to have its own nohup and output file:

bash
nohup command1 > output1.log 2>&1 & nohup command2 > output2.log 2>&1 & nohup command3 > output3.log 2>&1 &
  • Each command runs independently, with its own output file.

4. Use a Function

Define a function and call it with nohup:

bash
my_commands() { command1 command2 command3 } nohup my_commands > output.log 2>&1 &

Key Points:

  • > output.log 2>&1 redirects both stdout and stderr to output.log.
  • The trailing & runs the process in the background.
  • Avoid using a string (e.g., nohup "command1; command2") as it can cause parsing issues.
Feb 8, 12:40am

This Chat is read-only. Login to resume chatting.