Passing Environment Variables to Sudo Command
By Pete Freitag
Suppose you have a bash script that sets an environment variable, and then invokes something with sudo:
#!/bin/bash export MY_VAR=test sudo /do/something
You will quickly notice that the environment variable you set using export
is not available to the /do/something
command when it is invoked by sudo
.
When you run sudo, you are actually starting a new environment as the root user (or whatever user you have instructed sudo to run as), so any environment variables that exist in your current shell will not be passed to the sudo command. There are two ways to get around this.
Tell sudo to preserve environment
The sudo
command has a handy argument -E
or --preserve-env
which will pass all your environment variables into the sudo environment.
Passing only select environment variables to sudo
A better approach is to just pass the environment variables you want to preserve, instead of passing everything. There are two ways to accomplish this, first you can supply a list of environment variable names to the --preserve-env
argument. For example:
sudo --preserve-env=HOME /usr/bin/env
Finally you can also set environment variables directly in the sudo
command, like this:
sudo ZEBRA=true /usr/bin/env
Passing multiple environment variables to sudo
If you don't want to pass all environment variables to sudo, but do want to pass more than one, you can simply comma separate them, for example:
sudo --preserve-env=HOME,PATH /usr/bin/env
The above passes both the HOME
and the PATH
environment variables to sudo.
Testing if an environment variable is passed to sudo
Sometimes you need to test that an environment variable was really passed though sudo. A great way to test this is with the /usr/bin/env
command. This command will simply echo's all the environment variables available to the process. For example if I ran the following command on my mac running as user pete
:
sudo --preserve-env=HOME /usr/bin/env
The above command outputs something like the following:
HOME=/Users/pete USER=root SUDO_COMMAND=/usr/bin/env SUDO_USER=pete ...
We can see in the output above that the --preserve-env=HOME
argument in sudo did indeed pass the HOME=/Users/pete
environment variable, even though USER=root
. This trick works great on both linux and macs.
Passing Environment Variables to Sudo Command was first published on September 23, 2019.
If you like reading about bash, linux, sudo, or environment then you might also like:
- Creating a Symbolic Link with ln -s What Comes First?
- Bash Loop To Wait for Server to Start
- Counting IP Addresses in a Log File
- Recursively Counting files by Extension on Mac or Linux
Weekly Security Advisories Email
Advisory Week is a new weekly email containing security advisories published by major software vendors (Adobe, Apple, Microsoft, etc).