有没有一种方法可以在脚本中包含另一个Shell脚本,以便能够访问其函数?
就像在PHP中,您可以使用include
指令来包含其他PHP文件,以便通过调用函数名来运行其中包含的函数。
只需在您的脚本中添加以下内容:
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.
.
符合POSIX标准,而source
则不是。 - Mathieu_DuC
语言中所做的包含相同。这里的源代码将子脚本执行到主脚本中。如果我只想从子脚本中调用特定的函数怎么办? - Paresh Mayani. script.sh
和 ./script.sh
。我浪费了好几个小时才想明白到底发生了什么。 - Tihomir Mitkov. other.sh
等同于将另一个脚本复制并粘贴到父脚本中吗?还是存在一些微妙的差异? - Silicomancer以上答案是正确的,但如果你在另一个文件夹中运行脚本,会出现一些问题。
例如,a.sh
和 b.sh
在同一个文件夹中,a 使用 . ./b.sh
来包含 b。
当你在文件夹外运行脚本时,例如 xx/xx/xx/a.sh
,文件 b.sh
将找不到:./b.sh: No such file or directory
。
因此我使用了:
. $(dirname "$0")/b.sh
$0
是当前shell本身,并且迄今为止我不知道任何方法可以找出'b.sh'的目录。 - Rads可以使用 source 或者简写形式 .
:
. other_script.sh
sh
和Bash上工作。 "source"版本仅适用于Bash。 - Sridhar Sarnobatsource <file-name>
例如:source config.sh
脚本 - config.shUSERNAME="satish"
EMAIL="satish@linuxconcept.com"
调用脚本 -
#!/bin/bash
source config.sh
echo Welcome ${USERNAME}!
echo Your email is ${EMAIL}.
init.sh
中包含color.sh
,我需要进行如下操作。. ./color.sh
不确定为什么要使用./
而不是直接使用color.sh
。 color.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
source
命令,但问题本身是在询问如何确定source
文件的位置。 - Anthony Miller