Variables are cleared after using a sudo command in shell script

Viewed 32

I am writing a script for deployment.For that i need to login and then do the procedure.I have logged in successfully and trying to become sudo user.But after doing that , all the variables stored in the script are cleared, if i use them after sudo command.If i use them before sudo command , i am able to see its value.

# ! /bin/bash
proj=$1 #getting from other script , value is lvtools
echo varibles are :"${proj}" #proj is having value
sudo -Hiu lvadmin
ls
path=/home/lvadmin/lvsvnprojects/QAUat/"${proj}" #path formed in correctly as proj value is empty
echo path after admin is : "${proj}" #value is EMPTY
cd $path
ls

enter image description here If code works correctly, it should change directory to specified location.

1 Answers

Firstly, you need to export your var:

export proj=$1

Then you can use -E flag for sudo command, if it is allowed for you:

-E, --preserve-env
             Indicates to the security policy that the user wishes to preserve their
             existing environment variables.  The security policy may return an error
             if the user does not have permission to preserve the environment.

Your code should looks like

# ! /bin/bash
export PROJ=$1 #getting from other script , value is lvtools
echo varibles are :"${PROJ}" #PROJ is having value
sudo -EHiu lvadmin
ls
path=/home/lvadmin/lvsvnprojects/QAUat/"${PROJ}" #path formed in correctly as proj value is empty
echo path after admin is : "${PROJ}" #value is not EMPTY
cd $path
ls
Related