Yar*_*nux 20 command-line shell bash
我对“只有一个点 - 空格 - shell 脚本名称”(如. myshellscript)和“shell 脚本路径”(如./myshellscript)命令感到困惑。
他们是什么?我注意到该命令. myshellscript即使使用 -rw-rw-r-- 也会执行 shell 脚本。但./myshellscript没有。所以我很困惑。
eri*_*rik 20
help source 说:
source: source filename [arguments]
Execute commands from a file in the current shell.
Read and execute commands from FILENAME in the current shell. The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.
Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.
Run Code Online (Sandbox Code Playgroud)
source是 的同义词.,这意味着你可以同时写
. myshellscript
Run Code Online (Sandbox Code Playgroud)
或者
source myshellscript
Run Code Online (Sandbox Code Playgroud)
他们做什么:source读取文件的每一行(逐行)并在当前 shell 中执行它。
但是如果它有权限./myshellscript 执行当前目录中的文件。这也可以
/tmp/foo/bar/myshellscript
Run Code Online (Sandbox Code Playgroud)
(执行myshellscript目录中的文件/tmp/foo/bar)或
/usr/local/bin/myshellscript
Run Code Online (Sandbox Code Playgroud)
这意味着,这里的点只是当前目录。因此./myshellscript执行myshellscript当前目录中调用的文件。
例如尝试
cd .
Run Code Online (Sandbox Code Playgroud)
更改为当前目录(没有实际更改;-))或
ls .
Run Code Online (Sandbox Code Playgroud)
它列出了当前目录的内容。
正如@Alvin Wong 评论的那样:你可以试试这个脚本
#!/bin/foobarNonExisting
echo "This is the Shell that executes me:"
echo $SHELL
Run Code Online (Sandbox Code Playgroud)
与.或source看到,它不读取shebang。它只使用您当前的外壳。执行脚本本身会导致错误。
在bash,.并且source在功能上完成同样的工作-运行的当前shell中的脚本。
./foo 在另一个 shell 中运行,因为您的 shell 在执行之前会分叉。
如果您的脚本应该是可移植的,请始终使用.. source是 bash 的同义词,但在 POSIX 中不存在。
其他人说区别在于采购与执行,但没有人概述功能差异。
最大的功能区别在于exit,cd如果您获取它,则 , 和 变量赋值将影响当前运行的 shell,但如果您执行它,则不会。要演示,请尝试以下操作:
$ cat test.sh
#!/bin/bash
mkdir -p test
cd test
pwd
foo=bar
echo script foo: $foo
$ ./test.sh
/Users/kevin/test
script foo: bar
$ echo $foo
$ pwd
/Users/kevin
$ . test.sh
/Users/kevin/test
script foo: bar
$ echo $foo
bar
$ pwd
/Users/kevin/test
$
Run Code Online (Sandbox Code Playgroud)
现在试试这个:
$ cat test.sh
#!/bin/bash
exit
$ ./test.sh
$ . test.sh
[Process completed]
Run Code Online (Sandbox Code Playgroud)
如您所见,exit在执行的脚本中将完成该脚本,但是如果您使用 来获取脚本exit,它将退出您当前的 shell!