我有两个shell脚本,a.sh和b.sh。
我如何从shell脚本a.sh调用b.sh ?
我有两个shell脚本,a.sh和b.sh。
我如何从shell脚本a.sh调用b.sh ?
当前回答
取决于。 短暂的…… 如果你想在当前控制台加载变量并执行,你可以在你的代码中使用myshell .sh源代码。例子:
#!/bin/bash
set -x
echo "This is an example of run another INTO this session."
source my_lib_of_variables_and_functions.sh
echo "The function internal_function() is defined into my lib."
returned_value=internal_function()
echo $this_is_an_internal_variable
set +x
如果你只想执行一个文件,你唯一感兴趣的是结果,你可以这样做:
#!/bin/bash
set -x
./executing_only.sh
bash i_can_execute_this_way_too.sh
bash or_this_way.sh
set +x
其他回答
chmod a+x /path/to/file-to-be-executed
那是我唯一需要的东西。一旦要执行的脚本像这样可执行,您(至少在我的情况下)在调用脚本时不需要任何其他额外的操作,如sh或./。
感谢@Nathan Lilienthal的评论
简单的源代码将帮助你。 前女友。
#!/bin/bash
echo "My shell_1"
source my_script1.sh
echo "Back in shell_1"
如果你在同一个目录下有另一个文件,你可以这样做:
bash another_script.sh
or
source another_script.sh
or
. another_script.sh
当使用bash而不是source时,脚本不能改变父脚本的环境。的。命令是POSIX标准的,而源命令是更易于阅读的bash同义词。(我更喜欢来源而不是。)如果您的脚本驻留在其他地方,只需提供该脚本的路径。相对路径和全路径都可以工作。
我一直在寻找的答案:
( exec "path/to/script" )
如前所述,exec替换shell而不创建新进程。但是,我们可以把它放在一个子壳层中,这是用副函数完成的。
编辑: 实际上("path/to/script")就足够了。
首先,你必须包含你调用的文件:
#!/bin/bash
. includes/included_file.sh
然后像这样调用函数:
#!/bin/bash
my_called_function