简体   繁体   中英

Exporting variable?

I have two scripts. One script which creates some variables I need, and another script which uses those variables created in the first (I know this might not be the most efficient way of programming, but let's assume it is).

In script 1, it looks something like:

export MYVAR=/path/blah/blah

In script 2, it looks something like:

bash script_1.sh

But for some reason, in script 2, MYVAR is empty. Any thoughts?

Rather than executing script_1.sh, script_2.sh should source it:

. script_1.sh

That will cause the variable assignment to occur in script_2.

The problem is script 1 exits before script 2 attempts to use the exported environment or you are not calling script 2 from within script 1 . Remember, in bash, a script may not effect the parent environment, only its own environment . So to do what you want, script 1 must call script 2 . Example:

script1.sh:

#!/bin/bash

export MYVAR=/path/to/blah
bash script2.sh

script2.sh:

#!/bin/bash

printf "\nMYVAR: %s\n\n" "$MYVAR"

output:

$ bash script1.sh

MYVAR: /path/to/blah

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM