Linux 中 source 命令

 

source 命令的作用:

a、刷新环境变量

b、执行shell脚本

c、加载函数(环境变量)

d、从另外的shell脚本中读取变量

 

001、 刷新环境变量

(base) [root@pc1 software]# source ~/.bashrc        ## 刷新环境变量
(base) [root@pc1 software]#

 

002、执行shell脚本(和bash的区别)

(base) [root@pc1 test02]# cat test.sh
#!/bin/bash

echo $aa
(base) [root@pc1 test02]# aa=100
(base) [root@pc1 test02]# bash test.sh       ## bash不能在子进程中读取外部变量

(base) [root@pc1 test02]# source test.sh     ## 自带 export功能
100

 

003、导入函数变量

(base) [root@pc1 test02]# ls
fun.sh
(base) [root@pc1 test02]# cat fun.sh         ## 测试函数
#!/bin/bash

function fun_001()
{
        echo "just a test"
}
(base) [root@pc1 test02]# fun_001           ## 直接调用函数,无法调用
bash: fun_001: command not found...
(base) [root@pc1 test02]# source fun.sh     ## source加载函数
(base) [root@pc1 test02]# fun_001           ## 可以直接调用
just a test

 

004、

(base) [root@pc1 test02]# ls                      ## 两个测试shell脚本
read.sh  var.sh
(base) [root@pc1 test02]# cat var.sh              ## 脚本中定义了三个变量
#!/bin/bash
a=1
b=2
c=3
(base) [root@pc1 test02]# cat read.sh             ## source 从var.sh中读取变量, 然后输出
#!/bin/bash

source ./var.sh
echo $a
echo $b
echo $c
(base) [root@pc1 test02]# bash read.sh            ## 测试效果,说明读取成功
1
2
3

 

posted @ 2023-11-12 17:30  小鲨鱼2018  阅读(106)  评论(0编辑  收藏  举报