Using bash process substitution for sudo command

I would like to use a bash process replacement for the sudo command.

For example, the non-sudo command is used here, which works for me:

$ cat <(echo "installed.txt") installed.txt 

And here is a sudo version of a command that does not work:

 $ sudo cat <(echo "installed.txt") cat: /dev/fd/63: Bad file descriptor 

Reading the sudo man page, it seems that sudo closes all the descriptors of the stdin / stdout / stderr file before running the command as root. This makes me think that bash creates a handle (and does a process replacement) before running the sudo command.

I changed the root shell to bash (instead of sh by default). I tested that the command works fine when you log in as root. It only works with the sudo command.

What is the right technique to achieve what I'm trying to do here? Eval, quoting, sudo flag, sudoers file mod, other?

+7
source share
4 answers

Try to do this in your shell:

 $ sudo bash -c 'cat <(echo "installed.txt for UID=$UID")' installed.txt for UID=0 
+6
source

The behavior described in the question is related to the design of sudo .

 $ sudo cat <(echo "installed.txt") cat: /dev/fd/63: Bad file descriptor 

The error occurs because sudo has a default behavior that closes file descriptors, with the exception of standard input, output, and error. As described on the manual page:

By default, sudo closes all open file descriptors other than standard input, standard output, and standard error when executing a command.

You can override this behavior with the -C (or --close-from ) option to specify the file descriptor number below which files should not be closed. However, the use of this option must be authorized by the administrator: to /etc/sudoers

The following should be added:
  Defaults closefrom_override 

In this case, the command will work if -C used:

 $ sudo -C64 cat <(echo "installed.txt") installed.txt 

(the number 64 was indicated here, since it was greater than 63 in the error message).

+4
source
 sudo bash -c 'cat <(echo "installed.txt")' 
+3
source

The best approach is perhaps to put everything in a script and run the script with sudo .

0
source

All Articles