可以使用“.”吗?在 Ubuntu 和 OS X 中的 .bashrc 中运行文件而不是源代码?

Mic*_*ant 11 osx posix bashrc

好的,所以source在当前 shell 中.单独运行脚本,例如使用“.”和“源”运行脚本中的详细说明,但是,特别是在我的.bashrc文件中,我有:

[ -f ~/.bash_aliases ] && source ~/.bash_aliases
[ -f ~/.git-completion.bash ] && source ~/.git-completion.bash
[ -s ~/.autojump/etc/profile.d/autojump.sh ] && source ~/.autojump/etc/profile.d/autojump.sh
Run Code Online (Sandbox Code Playgroud)

我可以将其替换为:

[ -f ~/.bash_aliases ] && . ~/.bash_aliases
[ -f ~/.git-completion.bash ] && . ~/.git-completion.bash
[ -s ~/.autojump/etc/profile.d/autojump.sh ] && . ~/.autojump/etc/profile.d/autojump.sh
Run Code Online (Sandbox Code Playgroud)

这会在 OS X 上工作吗 - 那是“POSIX”问题吗?

我试过了,上面的内容似乎仍然适用于 Ubuntu(所以它们实际上可以同时使用source.,也就是说,它们在 shell 中为我提供了所需的功能)。我应该选择一个而不是另一个,还是我错过了什么?

FWIW,在 OS X 上,我.bashrc从我的.bash_profile.

cuo*_*glm 19

bash.source是同义词。查看bash源代码文件builtin/source.def,您可以看到.source使用相同的内部函数source_builtin

$BUILTIN source
$FUNCTION source_builtin
$SHORT_DOC 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.
$END

$BUILTIN .
$DOCNAME dot
$FUNCTION source_builtin
$SHORT_DOC . filename [arguments]
Execute commands from a file in the current shell.
Run Code Online (Sandbox Code Playgroud)

source不兼容POSIX,因此,如果您的脚本调用POSIX /bin/sh,你应该使用.代替source。由于 POSIX 不限制 shell,你上面的所有脚本都可以工作。

就个人而言,我总是使用.而不是source. (我编写的许多脚本都在 下运行cron)。


mik*_*erv 11

这是POSIX的定义.dot

shell 应从当前环境中的文件执行命令。

如果文件不包含/<slash>,shell 将使用 指定的搜索路径$PATH来查找包含文件的目录。不同于一般的命令搜索,但搜索的文件由.dot 程序需要执行的。如果没有找到可读文件,非交互式 shell 将中止;交互式 shell 应将诊断消息写入标准错误,但这种情况不应被视为语法错误。

考虑到上述情况,您不妨将您[ -f ./file ] && source ./file. ./file完全替换为。如果文件不存在,最糟糕的情况是您会在登录时收到通知 - 我认为这可能是您想要的信息。

当然,如果你宁愿保留测试,你可以这样做:

test -f ./file && . $_
Run Code Online (Sandbox Code Playgroud)

  • @mikeserv 不,`$_` 没有被 POSIX 标准化。[8个特殊参数](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02)是`$@`、`$*`、`$#`、`$$`、 `$!`、`$?`、`$-` 和 `$0`。`$_` 是 [明确省略](http://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xcu_chap02.html#tag_23_02_05_03)。您的错误评论引发了 [问题](http://unix.stackexchange.com/questions/129272/where-is-defined-by-posix)。 (6认同)
  • 哦,人们知道`$_`,我喜欢这样。:) (2认同)