Reputation: 869
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?
Upvotes: 24
Views: 41400
Reputation: 189739
There are multiple steps here which you need to understand.
PROJ_HOME=~/Projects/stable
creates a variable in the current shell with the expanded value of the path. In other words, if you are logged in as user luser
, the variable will contain something like /home/luser/Projects/stable
.
If the intent is for su
to get the value /home/kenneth/Projects/stable
you either need to evaluate this expression as that user, or rewrite it to contain the expected value for kenneth
before running sudo
.
In the first instance, if the assignment is in a file /etc/project.rc
you can simply
su -l kenneth -c '. /etc/project.rc; echo "$PROJECT_HOME"`
In the second case, maybe try something like
PROJECT_HOME=~kenneth/Projects/stable su -m -l kenneth -c 'echo "$PROJECT_HOME"'
though of course that unattractively hardcodes the value for Kenneth (and your shell might not actually have the facility to expand ~kenneth
to the home directory of kenneth
, in which case maybe use getent
etc).
Upvotes: 0
Reputation: 672
I also fixed this issue and I fixed by exporting env variable into profile. Below is my sample code:
echo export runner_token=$(echo $resp_json | jq -r '.token') >> /etc/profile
su -p - ubuntu -c '$HOME/actions-runner/config.sh --url https://github.com/${gh_repo_user}/${gh_repo_name} --token "$runner_token" --name MAC-AWS-RUNNER --labels ${gh_runner_labels}'
Upvotes: -1
Reputation: 1714
Try with su -m -l kenneth -c 'echo $PROJ_HOME'
. -m should preserve the environment.
EDIT
Reading your question one more time, I think I might understood it reversed.
You might also try this: su -l kenneth -c '. /home/kenneth/.bashrc; echo $PROJ_HOME'
.
Upvotes: 7
Reputation: 360395
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
Upvotes: 9
Reputation: 1590
Use single quotes around the command:
$ su -l kenneth -c 'echo $PROJ_PATH'
Double quotes interprets the value of $PROJ_PATH
as seen by root (empty string), then executes the command "echo (empty string)"
as the user kenneth.
Single quotes will pass 'echo $PROJ_PATH'
as the command, and the value of $PROJ_PATH
in kenneth's environment is what will be echoed.
Upvotes: -3
Reputation: 393
Have you tried the option su -m ?
-m, --preserve-environment
do not reset environment variables
For example: su -m kenneth -c 'echo $PROJ_HOME'
Upvotes: 20