码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2017-11-28 11:56:42      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:shell   subshell   子shell   source   

笔者今天写了一个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哈哈~。

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

标签:shell   subshell   子shell   source   

原文地址:http://blog.51cto.com/cmdschool/2045014

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!