Home > Back-end >  Dot (source) command doesn't work in script, but works in terminal
Dot (source) command doesn't work in script, but works in terminal

Time:03-23

Script file simplified for experimenting:

#!/bin/sh 
if test -f /home/vl/docker-test/envvars; then . /home/vl/docker-test/envvars; fi

envvars file content:

export APACHE_RUN_USER=www-data

Nothing happens after running script, no output, no error. Checking if env contains variable from envvars, no, it doesn't:

$ env | grep -i apache

output is empty.

But:

$ if test -f /home/vl/docker-test/envvars; then . /home/vl/docker-test/envvars; fi
$ env | grep -i apache
APACHE_RUN_USER=www-data

What i'm doing wrong in my script?

CodePudding user response:

. applies within the current running environment. In the first case, that's the script (and goes away when the script is done). In the second case, it's the shell. If you want the script to influence the shell it runs in, then you need to . it into the shell, not run it as a script.

So if your script is bring-in-vars, you are currently doing something like this (running it as a child):

./bring-in-vars

And you need to be doing this (sourcing it into the current shell):

. ./bring-in-vars

Children cannot, by design, modify their parents.

  • Related