source和export区别

背景:当我们启动linux后,将启动一个用户shell,在这个shell中,可以使用shell命令或声明变量,也可以创建并运行shell脚本程序,运行shell脚本时,系统将创建一个子shell用来执行,每个shell都是由某个shell(称为父shell)派生的

#a.sh

#! /bin/sh
echo “hello world!”
echo "PID of this script: $$"
echo "PPID of this script: $PPID"
ubuntu@test-ubuntu:~$ ./a.sh 
hello world!
PID of this script: 23875
PPID of this script: 20654

从上面的输出可以看到进程号不同。

假如有一个脚本:

#test.sh

#!/bin/sh

export TEST_DIR=/home/test

直接执行./test.sh

ubuntu@test-ubuntu:~$ ./test.sh
ubuntu@test-ubuntu:~$ echo $TEST_DIR   

ubuntu@test-ubuntu:~$

发现没有值,因为子shell中并不会影响到父shell
 

但是假如变成这样

ubuntu@test-ubuntu:~$ source ./test.sh
ubuntu@test-ubuntu:~$ echo $TEST_DIR   
/home/test


发现可以输出了.source(或点)命令通常用于重新执行刚修改的初始化文档,sh_profile和 .profile 等等.使它立即生效而不用去创建新的子shell。

小结:

1 export是将一个变量导出,以给其他shell程序使用,能影响子shell

2 source 作用在本shell程序中执行,不启动子shell,所以可以影响脚本的父shell

猜你喜欢

转载自blog.csdn.net/q2519008/article/details/83538577