This is a follow-up question to

Execute a line of commands with one sudo

If you want to redo the same command with sudo !! after doing a command like this:

echo "something">/path/file

You can use the global replace syntax to recall the command:

!!:gs/>/|sudo tee -a /

Use a space after the -a parameter.

This is the equivalent to sudo !! but helps you bypass sudo restrictions for the < and >. Because sudo does not allow you to use [<, >].

How can I put this into an alias on my .bashrc so I can use it simple?

I tried

alias redo='!!:gs/>/|sudo tee -a /'

But this doesn't work, I get the error:

$ echo "sdfdsf">/path/file
bash: /path/file: no permissions

$ redo
bash: /: Is a directory
tee: /: Is a directory
  • Did you try escaping the '/'? I believe \/ will work. Jun 20, 2014 at 14:54
  • I tried, but no change
    – rubo77
    Jun 20, 2014 at 14:57

2 Answers 2


I think that what you are looking for is:

sudo sh -c "!!"

This will translate !! to your last command and keep the shell redirections/pipes/variables functional:

➜  ~  ping
--- ping statistics ---
6 packets transmitted, 3 received, 50% packet loss, time 5001ms
rtt min/avg/max/mdev = 1.736/1.951/2.182/0.185 ms
➜  ~  sudo sh -c "!!" ## And becomes like this:
➜  ~  sudo sh -c "ping"
  • 1
    If the command used quotes, this isn't necessarily equivalent. Consider echo "foo bar" which would become sh -c "echo "foo bar"" which would just print foo instead of foo bar.
    – godlygeek
    Jun 20, 2014 at 15:13
  • This is perfect! but not the answer here, but to the question before: Execute a line of commands with one sudo I see, someone was faster there, so your answer here is a duplicate of this answer
    – rubo77
    Jun 20, 2014 at 15:26

Not exactly an answer to your question, but: don't do this.

The idea behind this alias (assuming that it worked) is that transforming > into |tee -a foo is a good idea. First off, even in the best of cases, they're not equivalent. > will overwrite a file, tee -a will append.

Secondly, this doesn't handle common constructs like echo >>foo (which would be transformed into echo |sudo tee -a |sudo tee -a foo and fail) or echo 2>&1 (which would be transformed into echo 2|sudo tee -a &1 and fail).

Now, you may be able to write a much more complicated substitution that could handle all of these cases reasonably, but that brings me to my third point:

This would run a command as root without you having a chance to review the command that's about to be executed, which strikes me as an extremely bad idea - especially given the fact that, by the time you have something that works for even all of the most common cases it's likely going to be fairly complex.

So, all in all, I'd recommend you not attempt anything of this sort.

Not the answer you're looking for? Browse other questions tagged .