Pete Freitag Pete Freitag

Passing Environment Variables to Sudo Command

Updated on September 05, 2023
By Pete Freitag
linux

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 find that the environment variable you set using export is not available to the /do/something command.

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. There are two ways to get around this.

Tell sudo to preserve environment

The sudo has a handy argument -E or --preserve-env which will pass all your environment variables into the sudo environment.

Passing only the variables you need

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

Note, we are using the /usr/bin/env command above, which simply echo's all the environment variables. That is just a handy way to test which variables are in the current environment.



bash linux sudo environment

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:

Weekly Security Advisories Email

Advisory Week is a new weekly email containing security advisories published by major software vendors (Adobe, Apple, Microsoft, etc).

Comments

Nice. Thanks, Pete.
by Charlie Arehart on 09/23/2019 at 8:42:44 PM UTC
Nice, thanks, what is the syntax for passing more than one environment variable?
by Ceri I Davies on 02/13/2020 at 4:17:26 PM UTC
From the man page:

--preserve-env=list

Indicates to the security policy that the user wishes to add the comma-separated list of environment variables to those preserved from the user's environment.
by Daniel on 06/05/2020 at 7:51:49 PM UTC
This was exactly what i was looking for. Thank you so much for posting this. sudo -E was exactly what i was looking for
by lad on 01/18/2022 at 9:02:55 PM UTC