- How do I use the nohup command without getting nohup.out?
- 9 Answers 9
- Команды Linux: как работает nohup
- Синтаксис команды nohup
- Проверка версии nohup
- Запуск процесса с помощью Nohup
- Запуск процесса в фоновом режиме
- Заключение
- nohup Command in Linux with Examples
- Working with nohup command
- Nohup Command in Linux
- Nohup Command
- Nohup Command Syntax
- Checking the version of Nohup
- Starting a process using Nohup
- Starting a process in the background using Nohup
- Summary
How do I use the nohup command without getting nohup.out?
I have a problem with the nohup command. When I run my job, I have a lot of data. The output nohup.out becomes too large and my process slows down. How can I run this command without getting nohup.out?
9 Answers 9
The nohup command only writes to nohup.out if the output would otherwise go to the terminal. If you have redirected the output of the command somewhere else — including /dev/null — that’s where it goes instead.
nohup command >/dev/null 2>&1 # doesn't create nohup.out
Note that the >/dev/null 2>&1 sequence can be abbreviated to just >&/dev/null in most (but not all) shells.
If you’re using nohup , that probably means you want to run the command in the background by putting another & on the end of the whole thing:
nohup command >/dev/null 2>&1 & # runs in background, still doesn't create nohup.out
On Linux, running a job with nohup automatically closes its input as well. On other systems, notably BSD and macOS, that is not the case, so when running in the background, you might want to close input manually. While closing input has no effect on the creation or not of nohup.out , it avoids another problem: if a background process tries to read anything from standard input, it will pause, waiting for you to bring it back to the foreground and type something. So the extra-safe version looks like this:
nohup command /dev/null 2>&1 & # completely detached from terminal
Note, however, that this does not prevent the command from accessing the terminal directly, nor does it remove it from your shell’s process group. If you want to do the latter, and you are running bash, ksh, or zsh, you can do so by running disown with no argument as the next command. That will mean the background process is no longer associated with a shell «job» and will not have any signals forwarded to it from the shell. (A disown ed process gets no signals forwarded to it automatically by its parent shell — but without nohup , it will still receive a HUP signal sent via other means, such as a manual kill command. A nohup ‘ed process ignores any and all HUP signals, no matter how they are sent.)
In Unixy systems, every source of input or target of output has a number associated with it called a «file descriptor», or «fd» for short. Every running program («process») has its own set of these, and when a new process starts up it has three of them already open: «standard input», which is fd 0, is open for the process to read from, while «standard output» (fd 1) and «standard error» (fd 2) are open for it to write to. If you just run a command in a terminal window, then by default, anything you type goes to its standard input, while both its standard output and standard error get sent to that window.
But you can ask the shell to change where any or all of those file descriptors point before launching the command; that’s what the redirection ( < , , >> ) and pipe ( | ) operators do.
The pipe is the simplest of these. command1 | command2 arranges for the standard output of command1 to feed directly into the standard input of command2 . This is a very handy arrangement that has led to a particular design pattern in UNIX tools (and explains the existence of standard error, which allows a program to send messages to the user even though its output is going into the next program in the pipeline). But you can only pipe standard output to standard input; you can’t send any other file descriptors to a pipe without some juggling.
The redirection operators are friendlier in that they let you specify which file descriptor to redirect. So 0>logfile appends standard error to the end of the file named logfile . If you don’t specify a number, then input redirection defaults to fd 0 ( < is the same as 0< ), while output redirection defaults to fd 1 ( >is the same as 1> ).
Also, you can combine file descriptors together: 2>&1 means «send standard error wherever standard output is going». That means that you get a single stream of output that includes both standard out and standard error intermixed with no way to separate them anymore, but it also means that you can include standard error in a pipe.
So the sequence >/dev/null 2>&1 means «send standard output to /dev/null » (which is a special device that just throws away whatever you write to it) «and then send standard error to wherever standard output is going» (which we just made sure was /dev/null ). Basically, «throw away whatever this command writes to either file descriptor».
When nohup detects that neither its standard error nor output is attached to a terminal, it doesn’t bother to create nohup.out , but assumes that the output is already redirected where the user wants it to go.
Команды Linux: как работает nohup
При выходе из оболочки системы Linux все запущенные процессы обычно завершаются или зависают. Но что делать, если вы хотите, чтобы процессы работали даже при выходе из оболочки/терминала? В этом вам поможет команда nohup.
Nohup — это сокращение от no hangup. Эта команда поддерживает в системах Linux работу процессов даже после выхода из оболочки или терминала. Она предотвращает получение процессами или заданиями сигнала SIGHUP ( Signal Hang UP ). Это сигнал, который отправляется процессу при закрытии или выходе из терминала. В этом руководстве мы рассмотрим команду nohup и покажем, как ее можно использовать.
Синтаксис команды nohup
Синтаксис команды выглядит следующим образом:
Давайте же посмотрим, как работает данная команда.
Проверка версии nohup
Вы можете начать с проверки версии Nohup, используя приведенный ниже синтаксис.
Запуск процесса с помощью Nohup
Если вы хотите, чтобы ваши процессы/задания работали даже после закрытия терминала, укажите необходимую команду в nohup, как показано ниже. Задания будут по-прежнему выполняться и не будут уничтожены при выходе из оболочки или терминала.
Согласно приведенному выше выводу результат команды был сохранен в nohup.out. Чтобы убедиться в этом, запустите:
Кроме того, вы можете перенаправить вывод в другой файл, как показано ниже.
Чтобы просмотреть этот файл, введите:
Чтобы перенаправить в файл и стандартную ошибку, и вывод, используйте атрибут > filename 2>&1 , как показано ниже.
nohup ./hello.sh > myoutput.txt >2&1
Запуск процесса в фоновом режиме
Чтобы запустить процесс в фоновом режиме, используйте символ & в конце команды. В этом примере мы пингуем google.com и отправляем этот процесс в фоновый режим.
Чтобы проверить процесс при возобновлении работы оболочки, используйте команду pgrep, как показано ниже.
Если вы хотите остановить или убить запущенный процесс, используйте команду kill, за которой укажите идентификатор процесса, как показано ниже.
Заключение
Все процессы, запущенные с помощью команды nohup, будут игнорировать сигнал SIGHUP даже после выхода из оболочки.
Как только задание запущено с помощью команды nohup, стандартный ввод будет недоступен для пользователя.
По умолчанию nohup.out используется как стандартный файл для stdout и stderr.
nohup Command in Linux with Examples
Every command in Linux starts a process at the time of its execution, which automatically gets terminated upon exiting the terminal. Suppose, you are executing programs over SSH and if the connection drops, the session will be terminated, all the executed processes will stop, and you may face a huge accidental crisis. In such cases, running commands in the background can be very helpful to the user and this is where nohup command comes into the picture. nohup (No Hang Up) is a command in Linux systems that runs the process even after logging out from the shell/terminal.
Usually, every process in Linux systems is sent a SIGHUP (Signal Hang UP) which is responsible for terminating the process after closing/exiting the terminal. Nohup command prevents the process from receiving this signal upon closing or exiting the terminal/shell. Once a job is started or executed using the nohup command, stdin will not be available to the user and nohup.out file is used as the default file for stdout and stderr. If the output of the nohup command is redirected to some other file, nohup.out file is not generated.
nohup command [command-argument . ]
Working with nohup command
1. Checking the version of Nohup:
The version of nohup command can be checked by using the following command.
2. To run a command in the foreground:
Runs the command in the foreground and redirects the command output to the nohup.out file if any redirecting filename is not mentioned.
To redirect the output to the output.txt file:
$ nohup bash geekfile.sh > output.txt
3. To run a command in the background (with ‘&’):
To run the command in the background, the ‘&’ symbol is appended at the end of the command. After executing, it doesn’t return to the shell command prompt after running the command in the background. It can be brought back to the foreground with the fg command.
$ nohup bash geekfile.sh & fg
Note: The number within square brackets represents the job id and the number next to it is the process id.
4. To run multiple commands in the background:
nohup command can be used to run multiple commands in the background.
Here, the output will be by default stored in nohup.out. To redirect it, type:
$ nohup bash -c 'commands' > filename.txt
$ nohup bash -c 'cal && ls' > output.txt
Nohup Command in Linux
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
When exiting the shell of a Linux System, all running processes are usually terminated or hang up. So what do you do If you still want to keep the processes running even exiting the shell/terminal? This is where the nohup command comes in.
Nohup Command
Nohup, short for no hang up is a command in Linux systems that keep processes running even after exiting the shell or terminal. Nohup prevents the processes or jobs from receiving the SIGHUP (Signal Hang UP) signal. This is a signal that is sent to a process upon closing or exiting the terminal. In this guide, we take a look at the nohup command and demonstrate how it can be used.
Nohup Command Syntax
Checking the version of Nohup
Output
Starting a process using Nohup
If you want to keep your processes/jobs running, precede the command with nohup as shown below. The jobs will still continue running in the shell and will not get killed upon exiting the shell or terminal.
Output From the output above, the output of the command has been saved to nohup.out to verify this run,
Output Additionally, you can opt to redirect the output to a different file as shown
Output To redirect to a file and to standard error and output use the > filename 2>&1 attribute as shown
nohup ./hello.sh > myoutput.txt >2&1
Output
Starting a process in the background using Nohup
To start a process in the background use the & symbol at the end of the command. In this example, we are pinging google.com and sending it to the background.
Output To check the process when resuming the shell use the pgrep command as shown
Output If you want to stop or kill the running process, use the kill command followed by the process ID as shown
Output
Summary
- All processes that are run using the nohup command will ignore the SIGHUP signal even upon exiting the shell.
- Once a job is started or executed using the nohup command, stdin will not be available to the user.
- By default, the nohup.out is used as the default file for stdout and stderr.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.