如何解决shell执行派生子shell问题?

Bash

笔者今天写了一个shell script,希望简化登录代理服务器的问题,可是script写好之后,却发现没有按照预想的情况下得到环境变量。
为了让大家好理解,贴出script的内容给各位参阅:

vim proxy_http.sh

加入如下配置:

#!/bin/bash

default_domain=cmdschool
default_username=will

read -p "Please enter you domain(default value is cmdschool): " domain
read -p "Please enter your username(default value is will): " username
read -s -p "Please enter your password: " password

if [ domain=="" ]; then
  domain=$default_domain
fi

if [ username=="" ]; then
  username=$default_username
fi

export http_proxy="http://$domain\\$username:$password@10.168.2.147:8080"
export https_proxy="http://$domain\\$username:$password@10.168.2.147:8080"

按照平时的执行方法,我们通常是:

chmod 770 proxy_http.sh
./proxy_http.sh

等同于以下执行效果

sh ./proxy_http.sh

等同于以下执行效果

bash ./proxy_http.sh

然后你检查环境变量,

echo $http_proxy
echo $https_proxy

结果发现输出的都是空值,
于是乎一顿百度,结果发现类似的帖子也有,但帖子上也没有找到答案(帖子的问法是export如何在当前console生效),
http://bbs.chinaunix.net/thread-3777848-1-1.html
然后联系了一位开源界的前辈(我也不知道对方是否愿意我透露他的大名,在此暂时不透露),并得到对方热情指点,解决方法极其简单,

source proxy_http.sh

所以,source指令和sh(bash)指令的区别显而易见,就是一个不会派生子shell和一个会派生子shell,我们平时使用source来导入环境变量,但却没有注意到source其实他的本质是用来执行脚本。O(∩_∩)O哈哈~。

没有评论

发表回复

Bash
如何熟悉Base Shell的变量的间接引用?

1 前言 一个问题,一篇文章,一出故事。 笔者希望以一个变量名称去引用另一个变量,于是整理此文。 2 …

Bash
如何实现文件夹路径转纯数字符串?

1 前言 一个问题,一篇文章,一出故事。 由于由于需要设置某目录的配额,配额要求为每个目录指定一个项 …

Bash
如何统计Linux打开文件前10进程?

1 前言 一个问题,一篇文章,一出故事。 笔者生产环境有台服务最近压力比较大,打开的文件数量不断地往 …