How to redirect io of a command executed by sudo

Solution Verified - Updated -

Environment

  • Red Hat Enterprise Linux (RHEL) 6,7
  • sudo

Issue

When using e.g. following command

$ sudo nohup mycommand </dev/null 1>/dev/null 2>&1 &

output of mycommand is not redirected to /dev/null and is processed by sudo, e.g. logged via sudo-io.

Resolution

Specify the redirection for the command itself e.g. via encapsulating it in a subshell

$ sudo sh -c 'nohup mycommand </dev/null 1>/dev/null 2>&1 &'

or in a script:

$ cat mycommand_to_dev_null
nohup mycommand </dev/null 1>/dev/null 2>&1 &
$ sudo ./mycommand_to_dev_null

Root Cause

When executing

$ sudo nohup mycommand 1>/dev/null 2>&1 &

shell applies all the redirection to sudo command i.e. not to the mycommand itself, therefore the mycommand still writes to stdout and sudo applies the sudo-io logging if configured. This is expected behaviour.

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.

Comments