6

I use nohup quite often for important long running processes under linux/bash, so much so that nohup time my command with arguments && mv nohup.out my.log is almost an idiom for me.

The problem is that nohup puts both stdout and stderr into nohup.out, and I cannot control the name of the file. This means that if I accidentally start two nohups in the same directory, their output will be interleaved in nohup.out.

The questions are:

  1. How do I deal with this problem? Always running nohups in separate directories and writing a shell function which will first check for ./nohup.out are two sucky options I see.

  2. How come I cannot tell nohup where to redirect the output? GNU tools tend to have so many options, why not nohup?

sds
  • 1,960
  • 2
  • 22
  • 33

3 Answers3

9

You can redirect both stdout and stderr to one file. With Bash 4 (or others such as Zsh), as easy as:

nohup <some-command> &> output.log

I can't tell you why there's no separate option for nohup to set the output, but if your shell can take care of that, you don't really need an option.

slhck
  • 223,558
  • 70
  • 607
  • 592
  • Will it prevent `nohup` from performing its own redirection? – u1686_grawity Feb 14 '13 at 15:45
  • 1
    GNU `nohup` says that it'll redirect stdout to a file if you specify `nohup command > file`. BSD `nohup` doesn't mention this at all, but it worked for me. – slhck Feb 14 '13 at 15:50
  • *GNU nohup says that it'll redirect stdout to a file if you specify `nohup command > file`* Isn't redirection in case of `nohup command > file` being handled by shell and not `nohup`? If so then how can `nohup` take any action based on weather redirection is present or not? – Piotr Dobrogost Jan 21 '15 at 08:29
  • The file `nohup.out` will be created in the case of error output, too; but if you redirect both stdout and stderr, there cannot be any output, so the file will not be created. But the `&>` syntax is not POSIX-compliant; you're better off with the answer by Irshad Khan elsewhere on this page. – tripleee Apr 20 '18 at 07:14
6

To Append output in user defined file you can use >> in nohup command.

nohup php your_command >> filename.out 2>&1 &

This command will append all output in your file without removing old data.

Irshad Khan
  • 161
  • 1
  • 4
  • 1
    And if you want to overwrite the output file using POSIX `sh` syntax, that's simply `nohup your_command >filename.out 2>&1 &` – tripleee Apr 20 '18 at 07:15
3

There are more ways than just nohup to start a process so that it would ignore SIGHUP; for example: (written as shell functions)

nohup() {
    setsid "$@"
}

nohup() {
    ("$@" &)
}

nohup() {
    "$@" & disown
}

(setsid, or even (setsid "$@" &), might be the best choice.)

All of them allow you to specify your own redirections with >, 2>, and &>/>&.

u1686_grawity
  • 426,297
  • 64
  • 894
  • 966