bash 从另一个 shell 脚本调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27704736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call function from another shell script
提问by Merianos Nikos
I have write a script, and I like to now to make it better readable, by moving parts of my main script in other files, but unfortunately I cannot.
我已经写了一个脚本,现在我喜欢通过将我的主脚本的一部分移动到其他文件中来使其更具可读性,但不幸的是我不能。
Let's say now I have the following code in file utils.sh
:
假设现在我在文件中有以下代码utils.sh
:
#!/bin/bash
sayHello ()
{
echo "Hello World"
}
Them from my main script I try the following, but doesn't work:
他们从我的主脚本中尝试以下操作,但不起作用:
#!/bin/bash
./utils.sh
sayHello
So, the question is, how to call the functions from within the utils.sh ?
所以,问题是,如何从 utils.sh 中调用函数?
回答by fredtantini
You have to source it, with .
or source
:
您必须使用.
或来获取它source
:
~$ cat >main.sh
#!/bin/bash
. ./utils.sh #or source ./utils.sh
sayHello
And then
进而
~$ ./main.sh
Hello World
回答by Arjun Mathew Dan
Your main script should be something like this:
你的主脚本应该是这样的:
#!/bin/bash
source utils.sh
echo "Main"
sayHello