0

I wanted to create a .bashrc function that would simplify passing data to a write-protected file.

function pipe {
      sudo bash -c "$1"
}

Unfortunately the command

pipe echo something > /etc/importantfile

still shows me that permission is denied. How should I fix it?

adam767667
  • 361
  • 2
  • 5
  • Assuming `/etc/importantfile` is the "restricted" one, you get the error because the shell tries to write to it when calling `pipe echo something > /etc/importantfile` (and not inside the function). Also note that you are passing two arguments to your function, but are only using the first one. – Janis Mar 15 '15 at 14:24
  • possible duplicate of [Why can’t `sudo` redirect stdout …?](http://unix.stackexchange.com/q/19707/80216); also [How do I use redirection with `sudo`?](http://unix.stackexchange.com/q/4830/80216), [Redirecting stdout to a file you don’t have write permission on](http://unix.stackexchange.com/q/1416/80216), and/or [Why do I get “Permission denied” when redirecting the output of `sudo`?](http://unix.stackexchange.com/q/148592/80216). – G-Man Says 'Reinstate Monica' Mar 15 '15 at 16:23

2 Answers2

1

You probably wanted to pass all as one argument:

function pipe {
  sudo bash -c "$@"
}

pipe 'echo something > /etc/importantfile'
Janis
  • 14,014
  • 3
  • 25
  • 42
  • Thanks, as bash beginnr i wasnt aware of this syntax. Unfortunetly it still dont work without quottion marks (i wanted to simplify this command as much as possible). – adam767667 Mar 15 '15 at 14:46
  • Please explain "it dont work". Any why did you try "**without** quotation marks", where the proposal was to add them, so that the arguments are not interpreted by the calling shell and passed to the function as one single argument. – Janis Mar 15 '15 at 14:55
  • I was just wondering if it was possible to write function that coudl be called using pipe echo something > /etc/importantfile - without quotation marks. That woudl simplify that a little bit. – adam767667 Mar 15 '15 at 15:14
  • Well, you could, of course, omit quoting of some pieces. But the redirection operator would require quoting (or escaping) anyway; so better quote all you want to be executed in the dedicated shell. – Janis Mar 15 '15 at 15:39
-1

This is due to > being interpreted by the outer shell. The command being run does not know of the redirection, and thus it cannot pass that as an argument to the function. In other words: The > is already executed before sudo is run.

What you can do is to have a command called save:

save() {
  sudo tee "$@" >/dev/null
}
echo something | save /etc/importantfile
Ole Tange
  • 33,591
  • 31
  • 102
  • 198