目录
译文
译自source or dot operator Man Page - Linux - SS64.com
source/.的作用都是读取文件内容,然后依照内容执行指令。
语法:
source 文件名 参数
. 文件名 参数
在bash中source是.的同义词。但是POSIX不认source。所以为了兼容性,建议任何场合都使用.
使用source运行某文件,文件的指令都在当前shell下执行,且该文件中创建的变量,或者对变量做的改变,在文件运行结束后,仍然对当前shell有效。假如不使用source或者.,只运行文件名,那么文件内的命令将在一个子shell里运行(子shell的变量也是独立的)。
示例1
.与文件名之间留空格和不留空格的效果是有细微区别的。.文件名 . 文件名
留空格的话,即使文件不具备运行权限,也可以执行。
示例2
#!/bin/bash
echo c
除非我们在执行脚本文件时,明确了脚本文件的路径,否则shell首先要搜索PATH环境变量。假如PATH的某个路径下有此名称的文件,则shell将执行之;否则将搜索shell的当前路径。
原文
. (source or dot operator)
Read and execute commands from the filename argument in the current shell context.
Syntax . filename [arguments] source filename [arguments]source is a synonym for dot/period '.' in bash, but not in POSIX sh, so for maximum compatibility use the period.
When a script is run using source it runs within the existing shell, any variables created or modified by the script will remain available after the script completes. In contrast if the script is run just as filename, then a separate subshell (with a completely separate set of variables) would be spawned to run the script.
There is a subtle difference between executing a script by running .ss64script (dot ss64script) and . ss64script (dot space ss64script)
the first is running a file thats been hidden from the 'ls' command, (although ls -a will show hidden files) the second option will execute ss64script even if it has not been set as an executable with chmod.Unless you provide an exact path to filename then bash will look first via the
PATH
variable and then in the current directory (only if filename is not found in$PATH
.)