14

I want to get a variable from another script, as demonstrated in this question on Stack Overflow:

How to reference a file for variables in a bash script

However, the answer uses the source command which is only available in bash. I want to do this in a portable way.

I have also tried

a.sh

export VAR="foo"
echo "executing a"

b.sh

#!/bin/sh
./a.sh
echo $VAR

But of course that does not work either. How to do this?

2 Answers 2

22

First of all, be aware that var and VAR are different variables.

To answer your question the . command is not bash-specific:

# a.sh
num=42
# b.sh
. ./a.sh
echo $num

The variables in "a" do not need to be exported.

http://www.gnu.org/software/bash/manual/bashref.html#Bourne-Shell-Builtins

3
  • Thank you and excuse my typo. I was pretty surprised with the difference between ./a.sh and . ./a.sh. Care to explain the difference? Jun 12, 2013 at 7:29
  • 2
    The dot command (. or source) evaluates the script in your current shell. Executing the script first spawns a subshell, and any environment changes in the subshell are lost when the subshell exits -- a child process cannot alter the environment of its parent. Jun 12, 2013 at 9:01
  • bash has a handy help builtin to access the manual for a specific command -- see help . Jun 12, 2013 at 9:02
1

Environment variables are only inherited from parent to child and not the other way round. In your example, b.sh calls a.sh, so a runs as a child of b. When a.sh exports var, it won't be seen by b.sh. Amend the logic so that the parent process exports the variable, e.g.

a.sh:

echo In a.sh...
VAR="test"
export VAR
./b.sh

b.sh:

echo In b.sh...
echo $VAR
1
  • Thank you, but I actually have sharedDefs.sh and two separate targets depending on it, so I need to have the dependencies this way. Jun 12, 2013 at 7:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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