我有两个shell脚本,a.sh和b.sh。

我如何从shell脚本a.sh调用b.sh ?


当前回答

首先,你必须包含你调用的文件:

#!/bin/bash
. includes/included_file.sh

然后像这样调用函数:

#!/bin/bash
my_called_function

其他回答

 #!/bin/bash

 # Here you define the absolute path of your script

 scriptPath="/home/user/pathScript/"

 # Name of your script

 scriptName="myscript.sh"

 # Here you execute your script

 $scriptPath/$scriptName

 # Result of script execution

 result=$?

有几种不同的方法可以做到这一点:

使用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."

如果你在同一个目录下有另一个文件,你可以这样做:

bash another_script.sh

or

source another_script.sh

or

. another_script.sh

当使用bash而不是source时,脚本不能改变父脚本的环境。的。命令是POSIX标准的,而源命令是更易于阅读的bash同义词。(我更喜欢来源而不是。)如果您的脚本驻留在其他地方,只需提供该脚本的路径。相对路径和全路径都可以工作。

pathToShell="/home/praveen/"   
chmod a+x $pathToShell"myShell.sh"
sh $pathToShell"myShell.sh"