How to pass variables of one user to another user in Linux? - linux

I have a user myuser and an environment variable test
export var=test
Saved bashprofile and works fine.
When running a shell script, I like to pass above variable and echo it with different user like below.
sudo su - anotheruser -c 'echo ${var}'
I tried this and it did not work. How do I pass the variable in the shell script ?
Thanks in advance.

Use the -E flag of sudo to maintain environment variables:
sudo -E su anotheruser -c 'echo ${var}'

Related

variable in bash script not working as expected

I have this script:
#!/bin/bash
VAR="eric.sql"
sudo mysqldump -c -u username -p1234 dbname > $VAR
But if i run this script I get this error:
: Protocol error 3: mysql-export.sh: cannot create eric.sql
But if I don't use the variable, but just this:
#!/bin/bash
VAR="eric.sql"
sudo mysqldump -c -u username -p1234 dbname > eric.sql
... it is working well. What do I wrong?
The problem was that the script had Windows style line breaks (I used notepad). After I used Nano the write the script it was solved.
Thanks for the answers!
sudo can change $PATH variable, depend on your security policy.
-E The -E (preserve environment) option will override the env_reset
option in sudoers(5)). It is only available when either the match-
ing command has the SETENV tag or the setenv option is set in sudo-
ers(5).
You could add the full path of the file, or remove sudo in that script.
This should also work:
sudo PATH="$PATH" mysqldump -c -u username -p1234 dbname > $VAR

Passing shell variables to system user

Let's say I want to run some command as system user (no shell):
su -s /bin/bash -c "some_command $TEST" my_system_user
How di I pass $TEST variable to user?
I have the variable configured for all users in /etc/profile.d/my_vars.sh
export TEST=test_arg
But that doesn't get loaded for the above scenario...
I have tried with no luck:
-m (--preserve-environment)
First, I tried to create such a file as /etc/profile.d/my_vars.sh and I put a test variable in the file. I can see the value of the variable, no matter I run command as whoever. I've also tried to set a variable on-the-fly with the following code, it works on my centos:
unset A_VAR; export A_VAR=foo
su -s /bin/bash -c "echo val=$A_VAR" my_system_user
> val=foo
unset A_VAR
An alternative solution if it does not work for you, you can consider of playing a ssh trick.
unset A_VAR; export A_VAR=foo
ssh -o SendEnv my_system_user#localhost "echo val=$A_VAR"
> val=foo
unset A_VAR
That's weird. It seems to work for me. I can do:
$ export TEST="hello"
$ su -s /bin/bash -c "echo $TEST"
password:
hello
...I guess I'm missing something about the question.

Why this linux command can affect the environment variables?

When I changed my current user to admin using
sudo su admin
I found that the environment variable changed too. What I intend to do is to change my user to admin with the env not changed.
Then I found a command as follows:
sudo bash -c "su - admin"
This command does indeed what I want, but I googled about bash -c, with no clue to why this command can do that for me. Could anyone give me a clear explanation? Thanks a lot.
first you should read the sudo manpage and set theses options in the /etc/sudoers file or you can do it interactively (see second below).
default sudoers file may not preserve the existing $USER environment unless you set the config options to do so. You'll want to read up on env_reset because depending on your OS distribution the sudo config will be different in most cases.
I dont mean to be terse but I am on a mobile device..
I do not recommend using sudo su .. for anything. whomever is sharing sudo su with the public is a newb, and you can accomplish the same cleaner with just sudo.
with your example whats happining is you are starting a subshell owned by the original user ("not admin") . you are starting the subshell with -c "string" sudo has the equivelant of the shell's -c using -s which either reads the shell from the arg passed to -s or the shell defined in the passwd file.
second you should use:
$ sudo -u admin -E -s
much cleaner right ? :)
-u sets the user, obviously
-s we just explained
-E preserves the orig user env
see for yourself just
$ echo $HOME # should show the original users /home/orig_user
$ env
your original env is preserved with none of that sudo su ugliness.
if you were interested in simulating a users login without preserving the env..
$ sudo -u user -i
or for root:
Might require -E depending on distro sudoers file
$ sudo -s
or
$ sudo -i
-i simulates the login and uses the users env.
hopefully this helps and someone will kindly format it to be more readable since im on my mobile.
bash with -c argument defines below.
-c string
If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.
Thanks & Regards,
Alok

How do you give su the current user environment variables

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?
Have you tried the option su -m ?
-m, --preserve-environment
do not reset environment variables
For example: su -m kenneth -c 'echo $PROJ_HOME'
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
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'.
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).
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}'
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.

Adding or Modifying User in Bash Shell Script

As I am trying to learn bash shell, I want to have some idea how can I add or modify the user in Bash Shell script?
Quick Ex:
Adding an user:
createuser.sh
#!/bin/sh
user=$1 #first argument
apache="www-data"
passuser=$2 # second argument
newpasswd=$(perl -e 'print crypt($ARGV[0], "S#LtStR!Ng")' $passuser)
createuser='/usr/sbin/useradd' # PATH to `useradd` package
##create and update password, then assign the apache group to the user
$createuser -d /home/$user -g $apache -m -s /bin/bash -p $newpasswd $user
Calling:
root#ip-ad-2as2-ds:#./createuser.sh test test1234
This way you can control the modify-user script, just change the createuser variable to have the proper modify-user (usermod) package.
Use adduser(8).

Resources