Linux 中 source 命令的使用
Linux 中的 source 命令是在当前 bash 环境下读取并执行文件中的命令,该命令通常用命令"."来替代。如:执行命令 # source .bash_rc 与 # . .bash_rc 是等效的。
一、命令格式
语法格式:
. filename [arguments]
source filename [arguments]
功能:读取并在当前 shell 环境中执行 filename 中的命令,返回 filename 中最后一个命令的返回状态。如果 filename 中不包含斜杠 (slash),系统将在 PATH 中查找包含 filename 的目录。在 PATH 中搜索的文件不必是可执行的。如果 bash 不是运行于 posix mode,当 PATH 中找不到文件时会在当前目录搜索。如果 shopt 内建命令的 sourcepath 选项被关闭, PATH 将不会被搜索。如果有任何 arguments ,它们成为 filename 的位置参数 (positional parameters),否则位置参数不发生变化。返回状态是脚本中最后一个命令退出时的状态。没有执行命令则返回0,没有找到或不能读取 filename 时返回false。
二、应用
source命令多用于:刷新当前的shell环境、在当前环境使用source执行Shell脚本、从脚本中导入环境中一个Shell函数、从另一个Shell脚本中读取变量等。
注意:
- source filename 与 sh filename 及./filename执行脚本的区别
- 当 shell 脚本具有可执行权限时,用 sh filename 与 ./filename 执行脚本是没有区别得。./filename 是因为当前目录没有在PATH中,所有”.”是用来表示当前目录的。
- sh filename 重新建立一个子shell,在子shell中执行脚本里面的语句,该子shell继承父shell的环境变量,但子shell新建的、改变的变量不会被带回父shell,除非使用export。
- source filename:这个命令其实只是简单地读取脚本里面的语句依次在当前 shell 里面执行,没有建立新的子 shell。那么脚本里面所有新建、改变变量的语句都会保存在当前shell里面。
最后,关于 exec 和 source:source 命令在当前 shell 中执行脚本,而 exec 命令在新的 shell 中运行。
三、实例
1、刷新当前shell环境
# source ~/.bash_profile
或
# . ~/.bash_profile
Home 目录下的 .bash_profile 是一个隐藏文件,主要是用来配置 bash shell 的。source ~/.bash_profile 则可让这个配置文件在修改后立即生效。
2、在当前环境使用source执行Shell脚本
Shell 脚本不知道你在当前 Shell 环境中定义的变量。source 命令可解决这个问题,从而在当前的会话中使用定义的变量并执行你的 Shell 脚本。
# 定义一个变量
$ url=www.baidu.com
写测试脚本source.sh
$ vi source.sh
$ cat source.sh
#!/bin/sh
echo $url
#此时用sh执行脚本
$ sh source.sh
输出为空
用source执行脚本时,找不到环境中定义的变量
$ source source.sh
www.baidu.com
用.执行脚本
$ . source.sh
www.baidu.com
注意和./source.sh方式的区别
$ ./source.sh
-bash: ./source.sh:Permission denied
加可执行权限
$ chmod +x source.sh
$ ./ source.sh
输出为空
3、从脚本中导入一个shell功能函数
写脚本定义函数tool
$ vi func.sh
#!/bin/bash
tool(){
echo "function test!"
}
在当前shell中导入脚本func.sh中定义的功能
$ source func.sh
$ tool
function test!
4、从另一个Shell脚本中读取变量
#创建一个带有变量的脚本var.sh
$ vi var.sh
#!/bin/bash
a=1
b=2
c=3
创建脚本read.sh,脚本内读取var.sh的变量
$ vi read.sh
#!/bin/bash
source ~/var.sh
echo $a
echo $b
echo $c
执行read.sh查看是否成功获取
$ sh read.sh
5、 读取并执行命令
source 命令可以从文件读取和执行命令。创建一个文件cmd.txt,保存两个命令:
$ cat cmd.txt
ip ad
date
$ source cmd.txt
可以看到 txt 文件中的两个命令执行成功了。