1

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
rubo77
  • 28,966

2 Answers2

1

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 10.0.0.1
--- 10.0.0.1 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 10.0.0.1"
Braiam
  • 35,991
0

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.

godlygeek
  • 8,053