Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you give su the current user environment variables

Tags:

linux

bash

ubuntu

I have a variable that is set through .bashrc.

In ~/.bashrc:

PROJ_HOME=~/Projects/stable

From a bash shell, I'd like to do something like this:

$ su -l kenneth -c 'echo $PROJ_HOME'

However, when I do this, the expected /home/kenneth/Projects/stable is not printed out.

Any ideas on how I can do this?

like image 552
kenneth koontz Avatar asked May 07 '12 20:05

kenneth koontz


People also ask

How can I see my current environment variables?

To display your current environment variables, use the env command. An environment variable that is accessible to all your processes is called a global variable.

How do I set an environment variable for a specific user in Linux?

You can set your own variables at the command line per session, or make them permanent by placing them into the ~/. bashrc file, ~/. profile , or whichever startup file you use for your default shell. On the command line, enter your environment variable and its value as you did earlier when changing the PATH variable.

How do I pass an environment variable to sudo?

There are two ways to get around this. The sudo has a handy argument -E or --preserve-env which will pass all your environment variables into the sudo environment. Note, we are using the /usr/bin/env command above, which simply echo's all the environment variables.


2 Answers

Have you tried the option su -m ?

-m, --preserve-environment
              do not reset environment variables

For example: su -m kenneth -c 'echo $PROJ_HOME'

like image 142
Dan V Avatar answered Oct 20 '22 08:10

Dan V


You need to export the variable. You may not need to use the -m option to su to preserve the environment.

export PROJ_HOME=~/Projects/stable
like image 31
Dennis Williamson Avatar answered Oct 20 '22 07:10

Dennis Williamson