1

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?

1
  • I tried putting aliases in root's profile, and they don't work. Jul 27, 2013 at 11:59

2 Answers 2

5

In bash,

alias sudo='sudo '

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

9
  • 1
    Please can you explain why this works?
    – fmanco
    Jun 26, 2012 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." Jun 26, 2012 at 2:17
  • Any idea why this doesn't work in combination with: stackoverflow.com/a/19739018/520061 or how to make it work? Jul 24, 2014 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. Jul 24, 2014 at 15:20
  • @grawity so just like sudo cd doesn't work? The point is being able to use sudo with the same commands I can use as a normal user. I figured I could make it a shell script, but then I have to type the whole path with sudo, which I don't have to do with my normal user, but well, if it's just not possible... Jul 24, 2014 at 15:25
2

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).

You must log in to answer this question.

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