我有两个shell脚本,a.sh和b.sh。
我如何从shell脚本a.sh调用b.sh ?
我有两个shell脚本,a.sh和b.sh。
我如何从shell脚本a.sh调用b.sh ?
当前回答
首先,你必须包含你调用的文件:
#!/bin/bash
. includes/included_file.sh
然后像这样调用函数:
#!/bin/bash
my_called_function
其他回答
取决于。 短暂的…… 如果你想在当前控制台加载变量并执行,你可以在你的代码中使用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
使用引号。
$ ./script-that-consumes-argument.sh `sh script-that-produces-argument.sh`
然后获取生产者脚本的输出,作为消费者脚本的参数。
有几种不同的方法可以做到这一点:
使用chmod a+x /path/to/file(Nathan Lilienthal的注释)使另一个脚本可执行,添加#!/bin/bash行(称为shebang),以及文件到$ path环境变量的路径。然后你可以调用它作为一个普通的命令; 或者用source命令(它是.的别名)调用它,就像这样: 源/道路/ /脚本 或者使用bash命令来执行它,比如: /bin/bash /道路/ /脚本
第一种和第三种方法将脚本作为另一个进程执行,因此另一个脚本中的变量和函数将不可访问。 第二种方法在第一个脚本的进程中执行脚本,并从另一个脚本中引入变量和函数(因此它们可以从调用脚本中使用)。
在第二种方法中,如果你在第二个脚本中使用exit,它也会退出第一个脚本。这在第一种和第三种方法中是不会发生的。
看看这个。
#!/bin/bash
echo "This script is about to run another script."
sh ./script.sh
echo "This script has just run another script."
pathToShell="/home/praveen/"
chmod a+x $pathToShell"myShell.sh"
sh $pathToShell"myShell.sh"