bash - 从另一个 shell 脚本调用函数

标签 bash shell

这个问题在这里已经有了答案:





Shell: How to call one shell script from another shell script?

(18 个回答)



Importing shell script function

(3 个回答)


6年前关闭。




我已经写了一个脚本,现在我喜欢通过将我的主脚本的一部分移动到其他文件中来使其更具可读性,但不幸的是我不能。

假设现在我在文件 utils.sh 中有以下代码:

#!/bin/bash

sayHello ()
{
   echo "Hello World"
}

他们从我的主脚本中尝试以下操作,但不起作用:
#!/bin/bash

./utils.sh

sayHello

所以,问题是,如何从 utils.sh 中调用函数?

最佳答案

您必须使用 . 来获取它或 source :

~$ cat >main.sh
#!/bin/bash
. ./utils.sh #or source ./utils.sh
sayHello

进而
~$ ./main.sh
Hello World

关于bash - 从另一个 shell 脚本调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27704736/

相关文章:

bash - 自动创建证书 OpenVPN

linux - 使用别名来缩短我的命令?

linux - 如何打印目录中所有文件的特定行?

bash - 喂 awk 位置参数

bash - 针对 bash 单维数组限制的更简洁的解决方法

shell - 使用 pod 获取 kubernetes 节点上的设备挂载信息

bash - 如何在 Makefile 目标中使用 Bash 语法?

linux - bash - 脚本的命令行参数

bash - 如何增加属性文件中的数值

bash - Tmux 重新加载 Bash .profile