【linux】source命令有个"坑"
时间:2015-10-15 03:10:27 作者:beebol 标签: Linux source 分类: Linux基础 Shell
source命令有个"坑",这个坑是带引号的,原因是我不知道source还有这么个点。什么点?就是source filename时,查找filename的问题。
看如下例子:
[root@localhost osc]# sh a.sh a.sh: line 4: source: 1.sh: file not found [root@localhost osc]# cat a.sh #!/bin/bash cd /data/osc/bin/ if [ -f 1.sh ];then source 1.shfi fi
哎,为什么1.sh文件not found?不是前面if判断都没有问题啊。
刚开始,还以为权限问题,一阵给权限,但结果还是一样。还把PATH变量打印出来了。
于是,把cd给去了,直接source ,结果ok了。到这里的时候,刚开始还无语,难道是cd后环境变量有问题?一值在猜.....
[root@localhost osc]# sh a.sh aaa [root@localhost osc]# cat a.sh #!/bin/bash #cd /data/osc/bin/ if [ -f bin/1.sh ];then source bin/1.shfi fi
把前后环境变量输出看了,一样啊。这时把注意力放到了source这个命令上,准备用strace source 1.sh来看看,但找不到source命令。没有办法看了...
还是看看手册吧,man source ,果然,找到原因了。就是source时找filename的问题。
这个source 命令找filename是在当前的shell环境下找的,如果没有反斜线,就在path中找,如果没有就没有。
source filename [arguments] Read and execute commands from filename in the current shell environment and return the exit status of the last command exe- cuted from filename. If filename does not contain a slash, file names in PATH are used to find the directory containing file- name. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if nocommands are executed), and false if filename is not found or cannot be read. commands are executed), and false if filename is not found or cannot be read.
如下方式都可以:
1、将脚本所在的目录加到PATH中
2、加上相对路径或绝对路径
3、就算是当前目录也得加./