0

I did web search and have read several articles on using variables in bash, including wiki but could not understand why running in bash FOO_VARIABLE=foo;./test does not result in test having $FOO_VARIABLE being foo:

By default, when a process is created, it inherits a duplicate environment of its parent process, except for explicit changes made by the parent when it creates the child.

Also have read that: Exception of inheritance of environment variables

"except for explicit changes": FOO_VARIABLE=foo ./test - results in test script knowing FOO_VARIABLE, but why in first way it does not?

echo $0
-bash

cat ./test
echo $MY_TEST
MY_TEST=test$MY_TEST
echo $MY_TEST

MY_TEST=ret;./test

test

Tested on CentOS 7 and Mac OS.

ADDED: https://stackoverflow.com/questions/9772036/pass-all-variables-from-one-shell-script-to-another second way is to source (2nd script is called from 1st), then no export needed - why my case is different?

AMEND to above: it was my rush and not very attentiveness to details: I missed . (dot) in sourcing section, now I've read: https://superuser.com/questions/176783/what-is-the-difference-between-executing-a-bash-script-vs-sourcing-it and that part is all clear.

https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference Yes, mine is local, but why is it not passed via inheritance (fork call)?

Alex Martian
  • 1,035
  • I'm not sure why you state that your case is different. Which answer are you referring to? Your case seems equivalent. 2. It will be inherited in fact. But only by a subshell, not by arbitrary process. I.e. you can see it best here: TEST=ret; (echo "shell variable=$TEST"; env|grep TEST).
  • – 0xC0000022L Oct 24 '19 at 05:53
  • @0xC0000022L, so when script is run from other script it creates subshell, but when in interactive shell I run script - that script is NOT run in subshell? why is that? – Alex Martian Oct 24 '19 at 06:00
  • 1
    No, a subshell has its own settings (e.g. shell options and working directory) but technically runs in the same process. So there's no fork() involved. If there's a fork() command line arguments and environment variables would be the way to make the other script see the variable. For example if you used source ./test to bring all the statements from ./test into your current shell, the variable would also be visible, because you don't actually start another process (assuming ./test is written in the same shell dialect as the running shell). – 0xC0000022L Oct 24 '19 at 06:06
  • @0xC0000022L, thank you! would be good (IMHO) if you include that valuable comment in your answer. – Alex Martian Oct 24 '19 at 06:18