3

There's .bashrc, .profile, and .bash_profile. I know they are used in different situations.

I want to prepend ~/bin to PATH always, e.g. regardless of whether it's an interactive session. I want it to work also when someone sudos as me.

How can I do that? When someone sudos as me, I see that none of those above 3 files are used. I want to always reliably prepend ~/bin to the PATH when my user account gets used, including when someone sudos as me.

EDIT: Clarification: No, contrary to certain duplicate question suspicion, this is not about making alice's PATH/environment carry over to bob when alice runs "sudo bob some-program". This is about making bob always have a PATH that has /home/bob/bin in front whenever bob is newly used to run a process including, but not necessarily limited to interactive sessions, non-interactive sessions, and being sudo'ed, but especially when being sudo'ed because that seems the most problematic case.

Joshua Chia
  • 1,760
  • 2
  • 16
  • 27
  • `sudo -i -u username` runs the user's shell as a login shell which would invoke `.bash_profile`. Seems like there is no way to enforce this behavior in a plain `sudo`. – codeforester Jun 12 '19 at 07:06
  • Possible duplicate of [How to keep environment variables when using sudo](https://stackoverflow.com/questions/8633461/how-to-keep-environment-variables-when-using-sudo) – Nic3500 Jun 12 '19 at 23:13
  • @Nic3500 Not a duplicate, see later note. – Joshua Chia Jun 13 '19 at 01:11
  • `sudo -i` has the undesirable side-effect of changing the current directory. If not for that, it's what I need. – Joshua Chia Jun 13 '19 at 01:14

1 Answers1

0

I've been using the following script (canonical copy), which includes a list of paths. Admittedly, I don't use sudo.

# Significant care is taken to be sh-compatible; if bash or zsh could be
# required, it could be made simpler or more generic.

# Known source'rs:
# ~/.profile
# ~/.zshrc
# ~/.xprofile
# ~/.xsessionrc
# ~/.bashrc
# ~/.config/plasma-workspace/env/*.sh

has_PATH () {
    local tmp=":$PATH:"
    [ "${tmp}" != "${tmp#*:$1:}" ]
}

prepend_PATH () {
    has_PATH "$1" || PATH="$1:$PATH"
}

append_PATH () {
    has_PATH "$1" || PATH="$PATH:$1"
}

prepend_PATH /usr/local/bin
prepend_PATH ~/.local/bin
prepend_PATH ~/bin
prepend_PATH /usr/lib/ccache
append_PATH /usr/sbin
append_PATH /sbin
append_PATH /usr/local/games
append_PATH /usr/games
export PATH
o11c
  • 15,265
  • 4
  • 50
  • 75