Skip to content

Instantly share code, notes, and snippets.

@alces
Last active July 21, 2023 09:21
Show Gist options
  • Save alces/8888c2d621838c47ad21bda0ac852498 to your computer and use it in GitHub Desktop.
Save alces/8888c2d621838c47ad21bda0ac852498 to your computer and use it in GitHub Desktop.
How to change environment passed to sudo command

By default, sudo on the Linux systems executes commands into a minimal environment. So, if you for example has some non-standard directories (such as /opt/groovy/bin) added to your PATH, a command running via sudo won't see any executable in these directories.

Normally, this strict sudo behavior can be changed by removing env_reset (or changing env_keep) variables in /etc/sudoers. But what can you do in case when you have only restricted sudo without write access to this file?

The following command passes a current value of PATH under a command run with sudo privileges:

sudo bash -c "export $PATH; which groovy"

(make sure that you use double quotes instead of the single ones, becase PATH variable must be substituted before executing sudo)

Also you can express the same idea in a more concise form using env command:

sudo env PATH=$PATH which groovy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment