Monday, March 30, 2015

bash: run su passing parameters

if you decide to switch to another user to run some commands, remember that whatever variable you have defined so far will NOT be passed to the other user.

echo $message
su - wls
echo $message
(nothing will be displayed, as "message" is not defined for wls)

This of course is a HPITA (aka RPITA) for someone who writes shell scripts.

You can use the "su -p" to pass the whole environment, but then there are some side effects:
su -p - wls
su: ignore --preserve-environment, it's mutually exclusive to --login.

(the "-" options is same as "--login")

su -p wls
bash: /root/.bashrc: Permission denied

I found it cleaner and easier to simply run the command I have to run with the "-c" option, so that variable substitution takes place in the "right" (root) context:


su - wls -c "export JAVA_VENDOR=Sun;export JAVA_HOME=/usr/java/jdk1.7.0_55/;java -d64 -Xmx1024m -jar ${softwareFolder}/wls1036_generic.jar -mode=silent -silent_xml=${scriptFolder}/weblogic_silent_install.xml"

this way softwareFolder and scriptFolder are both defined and I don't have to reinitialize them for the wls user...

No comments: