I have set my environment variable using /etc/profile:
export VAR=/home/userhome
Then if I do echo $VAR it shows /home/userhome
But when I put reference to this variable into the /etc/init.d/servicename file, it cannot find this variable. When I run service servicename status using /etc/init.d/servicename file with following content:
case "$1" in
status)
cd $VAR/dir
;;
esac
it says /dir: No such file or directory
But it works if I run /etc/init.d/servicename status instead of service servicename status
How can I make unix service see environment variables?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The problem is service strips all environment variables but TERM, PATH and LANG which is a good thing. If you are executing the script directly nothing removes the environment variables so everything works.
You don’t want to rely on external environment variables because at startup the environment variable probably isn’t present and your init system probably won’t set it anyway.
If you still want to rely on such variables, source a file and read the variables from it, e.g. create /etc/default/servicename with the content:
VAR=value
and source it from your init script, e.g:
[ -f /etc/default/service-name ] && . /etc/default/service-name
if [ -z "$VAR" ] ; then
echo "VAR is not set, please set it in /etc/default/service-name" >&2
exit 1
fi
case "$1" in
status)
cd "$VAR"/dir
;;
esac
Method 2
In my case, I needed a RAILS_ENV that was set in /etc/bash.bashrc: export RAILS_ENV=staging. I added $(grep RAILS_ENV /etc/bash.bashrc) and that made the variable available to the script. I did it this way so i didn’t have to include the rest of the file.
Method 3
One ugly solution that will also work:
function exec() {
args=( <a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85a1c5">[email protected]</a> )
command=${args[0]}
dummy=${args[1]}
whoami=`whoami`
if [ -z "$dummy" ]; then
me=`basename $0`
runuser -l ${whoami} -c "bash /etc/init.d/${me} ${command} dummy"
else
printenv
fi
}
case $1 in
status)
status
;;
start|stop|kill|restart)
exec $*
;;
*)
usage
esac
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0