如何在Bash Shell脚本中包含文件

175

有没有一种方法可以在脚本中包含另一个Shell脚本,以便能够访问其函数?

就像在PHP中,您可以使用include指令来包含其他PHP文件,以便通过调用函数名来运行其中包含的函数。


可能是重复的问题:Bash:如何最佳地包含其他脚本? - Troubadour
@Troubadour 感谢您提供的参考。尽管该帖子涉及到 source 命令,但问题本身是在询问如何确定 source 文件的位置。 - Anthony Miller
5个回答

258

只需在您的脚本中添加以下内容:

source FILE

或者

. FILE # POSIX compliant

$ LANG=C 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.

26
注意,.符合POSIX标准,而source则不是。 - Mathieu_Du
1
但是这里的源代码并不完全与我们在 C 语言中所做的包含相同。这里的源代码将子脚本执行到主脚本中。如果我只想从子脚本中调用特定的函数怎么办? - Paresh Mayani
12
不要混淆 . script.sh./script.sh。我浪费了好几个小时才想明白到底发生了什么。 - Tihomir Mitkov
1
虽然"."符号符合POSIX标准,这意味着它可以在sh、dash、zsh和其他POSIX shell上工作。但最好使用".",因为某些shell有它们自己的类似“source”的版本,可能会破坏您的应用程序。 - Misty
2
我们可以认为. other.sh等同于将另一个脚本复制并粘贴到父脚本中吗?还是存在一些微妙的差异? - Silicomancer

82

以上答案是正确的,但如果你在另一个文件夹中运行脚本,会出现一些问题。

例如,a.shb.sh 在同一个文件夹中,a 使用 . ./b.sh 来包含 b。

当你在文件夹外运行脚本时,例如 xx/xx/xx/a.sh,文件 b.sh 将找不到:./b.sh: No such file or directory

因此我使用了:

. $(dirname "$0")/b.sh

1
这仅适用于一个源文件/包含文件层级。如果'b.sh'进一步使用'. $(dirname "$0")/c.sh'包含'c.sh',那么它将失败,因为在包含'b'时,$0是当前shell本身,并且迄今为止我不知道任何方法可以找出'b.sh'的目录。 - Rads

38

可以使用 source 或者简写形式 .:

. other_script.sh

5
请注意,点号版本可在sh和Bash上工作。 "source"版本仅适用于Bash。 - Sridhar Sarnobat

9
语法为 source <file-name> 例如:source config.sh 脚本 - config.sh
USERNAME="satish"
EMAIL="satish@linuxconcept.com"

调用脚本 -

#!/bin/bash
source config.sh
echo Welcome ${USERNAME}!
echo Your email is ${EMAIL}.

你可以在这里学习如何将一个bash脚本包含到另一个bash脚本中。 (参考链接)

4
在我的情况下,为了从同一目录下的init.sh中包含color.sh,我需要进行如下操作。
. ./color.sh

不确定为什么要使用./而不是直接使用color.shcolor.sh的内容如下。

RED=`tput setaf 1`
GREEN=`tput setaf 2`
BLUE=`tput setaf 4`
BOLD=`tput bold`
RESET=`tput sgr0`

使用 File color.sh 没有发生错误,但是颜色没有显示。我已在 Ubuntu 18.04 上测试过,在该系统上运行的 Bash 版本为:GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)

这将只会在你的当前工作目录中提供该文件,而不是 init.sh 所在的目录(如果你首先使用 ./init.sh 启动它,则它们是重合的)。 - ricab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接