Bash 명령어 백그라운드 실행

When working with Bash on a Linux system, you may come across situations where you want to execute a command in the background. This means that the command will run independently of your current terminal session, allowing you to continue working without waiting for it to complete.

In this article, we will explore how to run commands in the background using various methods in Bash.

Using the & symbol

The simplest way to run a command in the background is by appending the & symbol at the end of the command. For example, let’s say you want to run a script called myscript.sh in the background:

$ ./myscript.sh &

By adding the & symbol, the script will start running in the background, and the system will return the control of the terminal immediately. You can continue using the terminal while the script runs in the background.

Using nohup

If you want to run a command in the background and ensure that it continues running even after you log out or close the terminal, you can use the nohup command. This is useful for long-running tasks or processes that you want to keep running even if the terminal session is terminated.

Simply prepend nohup before your command like this:

$ nohup ./myscript.sh &

The nohup command will detach the command from the terminal and prevent it from receiving the SIGHUP (hangup) signal, which is sent when the terminal session is closed. The output of the command will be redirected to a file named nohup.out by default.

Using disown

If you have already started a command in the foreground and forgot to append the & symbol to run it in the background, you can use the disown command to detach it from the terminal.

First, suspend the running command by pressing Ctrl + Z, and then use the bg command to bring it to the background:

$ ^Z
$ bg

Finally, use the disown command to detach the background process from the terminal:

$ disown

Conclusion

Running commands in the background in Bash allows you to multitask and continue working on your Linux system without waiting for a command to complete. By utilizing the & symbol, nohup command, or disown command, you can easily run processes or scripts in the background and free up your terminal for other tasks.

Remember to use the appropriate method based on your specific needs. Use the & symbol for simple background execution, nohup for long-running tasks, and disown for detaching already running foreground processes.

Happy multitasking!