[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: exporting a variable to global shells



Jan-Florian Hilgenberg wrote:
Hi guy's, first I am german, so ignore my bad english please ;-)

i want to get a variable out of a child shell in it parent shell, the sense is, that I want to use the ProxyServer of my school automaticly if it is pingable, the script isn't hard but the variable isn't fully global after exporting it


my script:
#!/bin/bash
ping -c 1 192.168.4.4 <http://192.168.4.4> && export http_proxy="192.168.4.4:8080 <http://192.168.4.4:8080>"
echo $http_proxy #for debugging

When the script is exiting the echo stdout's the proxy adress, but if I am back in my parent shell, the http_proxy variable is empty. The script should be run by the command post-up in the /etc/network/interfaces.


---deleted network stuff answered in other posts---

bye

As others have noted, exporting variables is a one way process, children get what the parent sees, not the reverse.

However, you can get data from a 'child' back to the parent in cases like this using what's called 'command line substitution' (big words to describe a fairly simple process ;) or by using functions which run in the "parent" context.

First, using substitution:

Assume your script file is called 'getproxyip', do these things:

  1.  remove the 'export' command but *leave* the variable in place.
2. leave the debugging line in place (it's no longer debugging but is the "return" value.
  3.  in the parent script, where you use your script, change it to be:

      HTTP_proxy=$(getproxyip)

You can also use 'backticks' (accent grave), but they make things much harder to read:

      HTTP_proxy=`getproxyip`

The advantage of using the backticks is that they are more 'portable', but I don't think that's an issue here.

Second, using a function:

This is written in the parent file, or is 'sourced' by the parent file. In either case, the function runs in the same process environment, so anything that is not 'local' to the function can be seen by the parent as well.

function getproxyip
{
  # your code here
  # Simple assignment works find, so your code drops in, no changes.
}

If you write this in a separate file, the main script *must* access it by 'sourcing' the getproxyip file:

  # setup function to determine proxy address:
  . getproxyip
  # The 'dot' command is also called 'source', so this also works:
  source getproxyip
  # Use one or the other.  Using both won't break anything, just uses
  # extra resources.

I hope this helps.  Have fun!-)

Bob

Attachment: smime.p7s
Description: S/MIME Cryptographic Signature


Reply to: