如何解决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
如何使用expect自动输入密码?

1 前言 一个问题,一篇文章,一出故事。 笔者最近在一个脚本中使用“adcli passwd-use …

Bash
如何实现SFTP自动上传下载?

1 前言 一个问题,一篇文章,一出故事。 笔者最近需要实现sftp自动上传下载,于是整理此文。 以下 …

Bash
如何实现Base Shell根据关键字获取数组?

1 前言 一个问题,一篇文章,一出故事。 笔者最近写一个Shell发现同一个脚本需要引用两个以上AD …