Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'm curious if there's a way to get my .bash_profile to work when I sudo a program.

For example, I have it set to alias emerge='emerge -av' so that I can install software, and it will always ask me if I want to proceed before downloading and installing. However I just noticed when I sudo emerge foo, it defaults to just the plain command emerge foo instead of emerge -av foo.

Only thing that comes to mind to fix this is to also put the alias in root's .bash_profile, but I don't want to have to resort to that since I will always have to make changes in two places when I want to add stuff to my own profile.

Is there another way around this that I'm unfamiliar with?

share|improve this question
    
I tried putting aliases in root's profile, and they don't work. –  Oscar Goldman Jul 27 '13 at 11:59

2 Answers 2

up vote 5 down vote accepted

In bash,

alias sudo='sudo '

will cause bash to expand any aliases that come after sudo.

share|improve this answer
    
Thank you very much! –  agent154 Jun 26 '12 at 0:32
1  
Please can you explain why this works? –  criziot Jun 26 '12 at 0:35
4  
It's simply part of how bash expands aliases. From the bash manpage: "If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion." –  Gordon Davisson Jun 26 '12 at 2:17
    
Any idea why this doesn't work in combination with: stackoverflow.com/a/19739018/520061 or how to make it work? –  Sebastian Blask Jul 24 at 13:20
    
@SebastianBlask: Because you basically end up running sudo function _foo() { ...; }; _foo – that is, trying to invoke bash built-in syntax via sudo. Regarding how to make it work, all I can say about that answer by osirisgothra is: 1) themonolith.com/wp-content/uploads/why-would-you-do-that.jpg 2) no, seriously, what is the damn point in defining a function inside an alias, rather than just using a function? 3) unfortunately, you can't call functions with sudo, so I recommend putting their content in a shell script. –  grawity Jul 24 at 15:20

The other way to do it (although in this particular instance I recommend Grawity's answer) would be to use the -E flag to sudo to inherit the environment.

   -E          The -E (preserve environment) option will override the
               env_reset option in sudoers(5)).  It is only available when
               either the matching command has the SETENV tag or the
               setenv option is set in sudoers(5).
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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