I have RHEL 7 and I want to set environment variable for sudo.

I have run sudo su in order toswitch to root user and added export to its .bashrc file. Then I have reloaded them with source.

Now when I run env in root mode it has environment variable. However, when I exit and run sudo env it does not.

Why this is happening?

  • 2
    Why would it? You're tell it to just run env. There isn't going to be an interactive bash login that would trigger the bashrc file. – Seth Sep 28 '17 at 9:47

sudo runs programs in its own, limited environment (see the ENVIRONMENT section of the manual man sudo). It does not implicitly use bash to run programs, so ~/.bashrc is not run, though you can invoke it explicitly:

sudo bash --rcfile=~root/.bashrc -c ProgramAndParameters

You can set an environment variable in the run string:

sudo variable=value ProgramAndParameters

You can use an alias or function to do either of these by default.

You can alternatively add an environment file to /etc/sudoers (see man sudoers for more information).


sudoers entry as below

%DBTEAM     ALL = (oracle) NOPASSWD: ALL

DBTEAM --> Group Name

oracle --> oracle user name

switch to Target user Without environment variable sudo -s -u oracle

switch to Target user With environment variable sudo -i -u oracle

  • Welcome to Super User! Please make sure your answer directly answers the question as stated. Your answer does not answer the question and does not relate to what the question is asking. – Sam Forbis Feb 14 '20 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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