Tell me more ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

1 Answer

up vote 11 down vote accepted

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.