Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell export variable not come into effect

I (on mac osx) often use

export http_proxy=http://192.168.0.205:1099

to proxy http connection to get a highed download speed. To make things easy, I wrote a shell file named proxy.sh to do this:

#!/bin/sh
export http_proxy=http://192.168.0.205:1099

Before I downlaod, I execute proxy.sh shell command, but I found it did't not come into effect.It lost http_proxy variable in current commnad window(terminal). I must type export command in current terminal,it will come into effect.

So I want to know what's reason for this and a solution? thanks.

like image 552
qichunren Avatar asked Dec 03 '22 00:12

qichunren


1 Answers

Running a shell script "normally" (with proxy.sh for example) results in that running in a sub-process so that it cannot affect the environment of the parent process.

Using . or source will run the shell script in the context of the current shell, so it will be able to affect the environment, using one of the following:

. proxy.sh
source proxy.sh

Another possibility (if you're using bash at least) is to create an alias to do the work for you. You can use something like:

alias faster='export http_proxy=http://192.168.0.205:1099'

so that you can then simply type faster on the command line and it will export that variable (in the context of the current shell).

You could also allow for one-shot settings such as:

alias faster='http_proxy=http://192.168.0.205:1099'

and then use:

faster your_program

which would translate into:

http_proxy=http://192.168.0.205:1099 your_program

That's a bash way to set a variable for just the one invocation of a command.

like image 88
paxdiablo Avatar answered Dec 13 '22 21:12

paxdiablo