Operating System - Linux
1752551 Members
4843 Online
108788 Solutions
New Discussion юеВ

export variables to outside of a script

 
SOLVED
Go to solution
Gemini_2
Regular Advisor

export variables to outside of a script

I have a script that defines fruit and I want other scripts to see it.

#!/bin/ksh
export fruit=orange

but, after running the script, other scripts still can not see it :-(

how do I make it happen?

thank you
15 REPLIES 15
James R. Ferguson
Acclaimed Contributor

Re: export variables to outside of a script

Hi Gemini:

Source (read) the script with the variable(s) you need. For example:

# cat /tmp/A
#!/usr/bin/sh
fruit=apple

# cat /tmp/B
#!/usr/bin/sh
fruit=apple

# /tmp/B
I want a(n) apple

...Note the dot, followed by a space, followed by the script to be sourced (read).

Regards!

...JRF...
Gemini_2
Regular Advisor

Re: export variables to outside of a script

I am confused..

you defined apple both in /tmp/A and /tmp/B......

am I missing something..
James R. Ferguson
Acclaimed Contributor
Solution

Re: export variables to outside of a script

Hi (again):

No, you're not missing something, I am! :-))

# cat /tmp/A
#!/usr/bin/sh
fruit=apple

# cat /tmp/B
#!/usr/bin/sh
. /tmp/A
echo "I want a(n) ${fruit}"

# /tmp/B
I want a(n) apple

Regards!

...JRF...
Gemini_2
Regular Advisor

Re: export variables to outside of a script

ah!

so easy, but I made it too complicated!!

thank you!!!

Kenan Erdey
Honored Contributor

Re: export variables to outside of a script

hi;

when you export a variable it's only be used by current and it's child shells. if you export it within a script, it doesn't pass to parent shell. so you can't get the value.
Computers have lots of memory but no imagination
Dennis Handly
Acclaimed Contributor

Re: export variables to outside of a script

Kenan Erdey said:
>when you export a variable it's only be used by current and its child shells.

Right. The only way to see it is to either source it as JRF said, or to return a string with the info. Similar to:
eval $(resize)
Gemini_2
Regular Advisor

Re: export variables to outside of a script

you are right.....now, other scripts can not use it..

what do you meant by "eval $(resize)"
Dennis Handly
Acclaimed Contributor

Re: export variables to outside of a script

>what do you meant by "eval $(resize)"

Basically resize (for X windows) wants to change the LINES and COLUMNS variables. Since it can't export those values (it's an executable), it outputs to stdout:
$ resize
COLUMNS=80;
LINES=36;
export COLUMNS LINES;

And then eval does the export, kind of like sourcing it, in the current shell.
Gemini_2
Regular Advisor

Re: export variables to outside of a script

so, I have to export the variables again...hmmmm...

go back to square 1....