How can I alias a command for sudo?

5

0

I have an alias that I would like to use both as a regular user and as root, via sudo. Specifically, it is this:

alias rm=trash

This works fine as a normal user, and it works fine when I use sudo -i to get a root shell prompt, but if I use sudo rm, the alias does not apply. So where do I need to put my alias so that it works in one-off sudo commands?

Ryan C. Thompson

Posted 2010-09-25T18:06:08.927

Reputation: 10 085

http://serverfault.com/questions/61321/how-to-pass-alias-through-sudo – Ciro Santilli 新疆改造中心法轮功六四事件 – 2015-08-09T19:42:01.057

1

You don't specify if you are on OS X, but if so, check out the osx-trash command. Very useful: http://www.dribin.org/dave/osx-trash/ But as others have said, don't alias rm. Just get in the habit of typing "trash" instead.

– None – 2010-09-25T20:18:52.533

Answers

10

Create an alias for sudo with a space at the end:

alias sudo='sudo '

Then all other aliases will work with sudo.

But like mentioned in the other answer, aliasing rm to execute trash is probably a bad idea. What I like to do is "disable" rm like this:

alias rm='echo "rm is disabled, use trash or /bin/rm instead."'

With this you will soon get into the habit of typing trash instead of rm.

Dario Seidl

Posted 2010-09-25T18:06:08.927

Reputation: 2 409

1

That won't work, but if you use a function and export it, it will.

dl () { trash "$@"; }
export -f dl

It's a bad idea to alias rm because if you get in the habit of the alias or function protecting you and at some point the alias isn't available for some reason then you use rm and it deletes a bunch of stuff that will be difficult to get back.

Paused until further notice.

Posted 2010-09-25T18:06:08.927

Reputation: 86 075

That doesn't seem to work with either bash or zsh. – Ryan C. Thompson – 2010-09-25T20:10:31.037