---
title: "我使用过的Linux命令之source - 在当前shell环境中执行指定文件中的命令"
author: "codingstandards"
date: "2010-12-09T19:41:53Z"
tags: ["Ant", "Apache", "Bash", "CMS", "Linux"]
categories: ["操作系统"]
slug: "linux-source-shell"
draft: false
lastmod: "2010-12-09T19:42:21Z"
id: 837935
url: "https://codingstandards.iteye.com/blog/837935"
---

# 我使用过的Linux命令之source - 在当前shell环境中执行指定文件中的命令

本文链接：[http://codingstandards.iteye.com/blog/837935](/blog/837935)   （转载请注明出处）

## 用途说明

source命令是bash中的内建命令，它等同于点命令（.），用于读取和在当前shell环境中执行指定文件中的命令，执行完毕之后退出码为该文件中的最后一个命令的退出码（Read  and  execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.）。指定的文件可以没有执行权限。

在当前shell中执行和在子shell中执行的区别是，后者定义的变量和函数在执行结束后就消失了，而前者却可以保留下来。有时候我们修改了/etc/profile里面的内容，如增加了环境变量，那么要立即生效的话，就必须使用source命令或者点命令在当前shell中执行一下。

 

## 常用参数

格式： .  filename \[arguments]  
格式： source filename \[arguments]

 

在后面的示例中会分别对各种情况举例演示。

 

## 使用示例

### 示例一

\[root@web imx\_web3q]# help source  
source: source filename \[arguments]  
    Read and execute commands from FILENAME and return.  The pathnames  
    in $PATH are used to find the directory containing FILENAME.  If any  
    ARGUMENTS are supplied, they become the positional parameters when  
    FILENAME is executed.  
\[root@web imx\_web3q]#

 

### 示例二 修改/etc/profile之后使之立即生效

\[root@web imx\_web3q]# vi /etc/profile

\[root@web imx\_web3q]# . /etc/profile  
\[root@web imx\_web3q]#

 

### 示例三 在PATH中搜索命令

man source中说道：如果filename不包含斜杠（/），那么从PATH环境变量指定的那些路径搜索filename，这个文件不必是可执行 的。（If filename does not contain a slash, file names in  PATH  are used  to  find the directory containing filename.  The file searched for in PATH need not be executable.）如果在PATH中找不到指定文件，当bash不是posix模式时，将在当前目录下搜索该文件。（When bash is not in posix mode, the current directory is searched if no file is found in PATH.）如果shopt里的sourcepath关闭，则不在PATH中搜索指定文件。（If  the sourcepath  option  to  the shopt builtin command is turned off, the PATH is not searched.）

\[root@new55 ~]# shopt

cdable\_vars     off  
cdspell         off  
checkhash       off  
checkwinsize    on  
cmdhist         on  
dotglob         off  
execfail        off  
expand\_aliases  on  
extdebug        off  
extglob         on  
extquote        on  
failglob        off  
force\_fignore   on  
gnu\_errfmt      off  
histappend      off  
histreedit      off  
histverify      off  
hostcomplete    off  
huponexit       off  
interactive\_comments    on  
lithist         off  
login\_shell     on  
mailwarn        off  
no\_empty\_cmd\_completion off  
nocaseglob      off  
nocasematch     off  
nullglob        off  
progcomp        on  
promptvars      on  
restricted\_shell        off  
shift\_verbose   off  
sourcepath      on  
xpg\_echo        off  
\[root@new55 ~]# echo $PATH  
/usr/kerberos/sbin:/usr/kerberos/bin:/opt/apache/apache-ant-1.8.1/bin:/usr/java/jdk1.6.0\_21/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin :/root/bin  
\[root@new55 ~]# ls -l /usr/bin/sj.sh  
\-rwxr-xr-x 1 root root 453 09-15 04:46 /usr/bin/sj.sh

\[root@new55 ~]# cat /usr/bin/sj.sh  
#!/bin/sh

listpids()  
{  
        #ps -ef|grep java|grep -v grep  
        COLUMNS=1024 ps h -C java -f  
}

showpids()  
{  
        while read u p pp t1 t2 tty cpu cmd;  
        do  
                ls -l /proc/$p/cwd  
                echo $p $cwd $cmd  
                echo  
        done  
}

showpidof()  
{  
        while read u p pp t1 t2 tty cpu cmd;  
        do  
                if ls -l /proc/$p/cwd | grep -q $1; then  
                        echo $p  
                elif echo $cmd | grep -q $1; then  
                        echo $p  
                fi  
        done  
}

if \[ "$1" ]; then  
        listpids | showpidof $1 | xargs  
else  
        listpids | showpids  
fi

\[root@new55 ~]# sj.sh  
lrwxrwxrwx 1 root root 0 12-09 19:11 /proc/6832/cwd -&gt; /root/work55/cms\_server  
6832 0:02 /usr/java/jdk1.6.0\_21/jre/bin/java -classpath /opt/apache/apache-ant-1.8.1/lib/ant-launcher.jar -Dant.home=/opt/apache/apache-ant-1.8.1 -Dant.library.dir=/opt/apache/apache-ant-1.8.1/lib org.apache.tools.ant.launch.Launcher -cp start

\[root@new55 ~]# listpids  
\-bash: listpids: command not found

\[root@new55 ~]# chmod -x /usr/bin/sj.sh  
\[root@new55 ~]# source sj.sh  
lrwxrwxrwx 1 root root 0 12-09 19:11 /proc/6832/cwd -&gt; /root/work55/cms\_server  
6832 0:02 /usr/java/jdk1.6.0\_21/jre/bin/java -classpath /opt/apache/apache-ant-1.8.1/lib/ant-launcher.jar -Dant.home=/opt/apache/apache-ant-1.8.1 -Dant.library.dir=/opt/apache/apache-ant-1.8.1/lib org.apache.tools.ant.launch.Launcher -cp start

\[root@new55 ~]# listpids  
root      6832  5994  0 19:11 pts/2    Sl+    0:02 /usr/java/jdk1.6.0\_21/jre/bin/java -classpath /opt/apache/apache-ant-1.8.1/lib/ant-launcher.jar -Dant.home=/opt/apache/apache-ant-1.8.1 -Dant.library.dir=/opt/apache/apache-ant-1.8.1/lib org.apache.tools.ant.launch.Launcher -cp  start

\[root@new55 ~]# chmod +x /usr/bin/sj.sh   
root@new55 ~]#

 

### 示例四 位置参数

If any arguments are supplied, they become the positional parameters when  filename  is  executed.   Otherwise  the positional  parameters are unchanged.

\[root@new55 ~]# cat &gt;source.sh  
XYZ=123  
echo "args: $@"

Ctrl+D

\[root@new55 ~]# ./source.sh  
\-bash: ./source.sh: 权限不够  
\[root@new55 ~]# . source.sh  
args:  
\[root@new55 ~]# echo $XYZ  
123  
\[root@new55 ~]# . source.sh hello world  
args: hello world  
\[root@new55 ~]#

 

### 示例五 退出码

The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.

\[root@new55 ~]# ls x.sh  
ls: x.sh: 没有那个文件或目录  
\[root@new55 ~]# . ./x.sh  
\-bash: ./x.sh: 没有那个文件或目录  
\[root@new55 ~]# echo $?  
1  
\[root@new55 ~]# cat &gt;x.sh  
return 13

Ctrl+D  
\[root@new55 ~]# . ./x.sh  
\[root@new55 ~]# echo $?  
13  
\[root@new55 ~]#

 

## 问题思考

## 相关资料

【1】笑遍世界的测试技术     [Linux Source命令及脚本的执行方式解析](http://www.51testing.com/?uid-225738-action-viewspace-itemid-206878)      
【2】Simon的专栏      [Linux中source命令的用法](http://blog.csdn.net/simon_dong618/archive/2007/04/24/1581132.aspx)       
【3】LinuxSense      [linux的source命令](http://www.linuxsense.org/archives/137.html)      
【4】jiakechong       [linux source命令](http://jiakechong.iteye.com/blog/396413)

 

返回 [我使用过的Linux命令系列总目录](/blog/786653)