在 bash 脚本中,一个点后跟一个空格然后是一个路径是什么意思?

Den*_*lly 92 command-line bash openvz

我在尝试在 openvz 容器内安装 USB 设备时遇到了这个例子,我以前从未在第二行中看到过这个构造。你能解释一下它的含义吗?

#!/bin/bash
. /etc/vz/vz.conf
Run Code Online (Sandbox Code Playgroud)

gni*_*urf 107

它是 builtin 的同义词source。它将从当前 shell 中的文件执行命令,如从help source或读取的help .

在您的情况下,该文件/etc/vz/vz.conf将被执行(很可能,它只包含稍后将在脚本中使用的变量赋值)。它不同于仅仅执行文件,例如,/etc/vz/vz.conf在很多方面:最明显的是文件不需要是可执行的;那么你会考虑运行它,bash /etc/vz/vz.conf但这只会在子进程中执行它,并且父脚本不会看到子进程所做的任何修改(例如,变量)。

例子:

$ # Create a file testfile that contains a variable assignment:
$ echo "a=hello" > testfile
$ # Check that the variable expands to nothing:
$ echo "$a"

$ # Good. Now execute the file testfile with bash
$ bash testfile
$ # Check that the variable a still expands to nothing:
$ echo "$a"

$ # Now _source_ the file testfile:
$ . testfile
$ # Now check the value of the variable a:
$ echo "$a"
hello
$
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

  • 请注意:`.` 适用于大多数 shell(sh、ash、ksh 等),`source` 特定于 bash。 (16认同)
  • @EarlGray `source` 不*只是* bash——它是在 C 风格的外壳中 ([`csh`](http://manpages.ubuntu.com/manpages/trusty/en/man1/bsd-csh.1 .html), [`tcsh`](http://manpages.ubuntu.com/manpages/trusty/en/man1/tcsh.1.html))--还有 zsh。`.` 适用于 Bourne 风格的 shell,包括 [列出的那些](http://askubuntu.com/q/232932#comment288304_232938)。考虑到 bash 是 Bourne 风格的 shell,并且几乎没有任何非平凡复杂的 bash 脚本可能在 C 风格的 shell 中运行,的确,`.` 应该被认为更具可移植性。但是 bash 的 `source` 同义词 `.` 的存在部分是为了可移植性。 (4认同)

小智 5

当脚本使用 `source' 运行时,它在现有的 shell 中运行,脚本创建或修改的任何变量在脚本完成后仍然可用。

句法 。文件名 [参数]

  source filename [arguments]
Run Code Online (Sandbox Code Playgroud)