Original version:
How to run sudo sh -c "command" in back ground
In a terminal
sudo sh -c "command" & starts in background but as soon as I press enter, the process exits
[test@localhost app]$ sudo sh -c 'app start' &
[3] 31725
[test@locahost app]$
[3]+ Stopped sudo sh -c 'app start'
Rewrite:
I want to run some long-running command
in the background, as root.
The “obvious” way to do this is
sudo some long-running command &
For unspecified reasons I also tried
sudo sh -c 'some long-running command' &
Both of these fail the same way: I get a shell prompt, but then, as soon as I hit Enter, I get an error message:
$ sudo sh -c 'some long-running command' & [3] 31725 $ [3]+ Stopped sudo sh -c 'some long-running command' $
It’s been pointed out to me that, when I put the sudo
command
into the background like this, it loses access to the standard input.
Therefore, it cannot read the password, and it is stopped when it tries.
Another approach is to use the -b
option to tell sudo
to put the long-running command
into the background,
rather than putting sudo
into the background:
sudo -b some long-running command
or
sudo -b sh -c 'some long-running command'
Oh! I almost forgot to mention! My requirements include
- Must be able to redirect the output of the
long-running command
to a file. - Must be able to capture the exit status of the
long-running command
, presumably writing it to a file. - Must be able to get the PID of the background process in some reliable way
(without needing to
grep
through the output ofps
).
How can I do this?