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 $VARBut of course that does not work either. How to do this?
2 Answers
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 $numThe variables in "a" do not need to be exported.
3Environment 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.shb.sh:
echo In b.sh...
echo $VAR 1