Take the 2-minute tour ×
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

2 Answers 2

up vote 15 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
1  
Very helpful, thanks. For other Linux newbies, here's the cryptic Bash stuff. [ ... ] is a shorthand for a conditional test; see this answer. -f is an if argument to check if file exists. && is a short-circuit operator: only do the second command if the first exits with 0. . source or dot operator: read and execute commands from the filename argument. -z is an if argument to check for a zero-length string. >&2 send output to stderr. See also Introduction to if. –  Mark Berry Jun 12 at 20:06

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.

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.