tadasajon
tadasajon

Reputation: 14836

invoking a Bash script indirectly - and a puzzle about how to use `source` appropriately

I have a script called greeting_script as follows:

GREETING='Top O the Morning to Ya!'
export GREETING
echo $GREETING

If I run this script from the command line, I see the following result:

> export GREETING='hello'
> echo $GREETING
hello
> source greeting_script
Top O the Morning to Ya!
> echo $GREETING
Top O the Morning to Ya!

This is what I expect. I have another script called 'indirect_greeting_script' as follows:

#!/bin/bash
source greeting_script

If I run this script from the command line, I see the following:

> export GREETING='hello'
> echo $GREETING
hello
> indirect_greeting_script
Top O the Morning to Ya!
> echo $GREETING
hello

Note that I have the permissions set on indirect_greeting_script in order to enable it to be executed directly at the command line. I also have the first line that #!/bin/bash

Obviously when I invoke greeting_script indirectly the results are not being stored in my current environment properly. I would like for the indirect_greeting_script to be an executable at the command line and not a file that I have to source. What is it that I don't understand?

NOTE: it works as expected if I make indirect_greeting_script a normal file (i.e., not executable), remove the leading line that reads #!/bin/bash and invoke it with the source command.

Upvotes: 0

Views: 110

Answers (1)

chepner
chepner

Reputation: 530823

A child process cannot modify the environment of its parent. export simply marks a parameter to be included in the environment of any children processes. When you call it in your script, it does not cause the value to be sent back to the parent.

Upvotes: 2

Related Questions