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?

1

You probably wanted to pass all as one argument:

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

pipe 'echo something > /etc/importantfile'
  • 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.