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

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


当前回答

 #!/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

 # 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-to-be-executed

那是我唯一需要的东西。一旦要执行的脚本像这样可执行,您(至少在我的情况下)在调用脚本时不需要任何其他额外的操作,如sh或./。

感谢@Nathan Lilienthal的评论

这是为我工作的,这是执行另一个主sh脚本的内容。

#!/bin/bash 
source /path/to/other.sh

简单的源代码将帮助你。 前女友。

#!/bin/bash
echo "My shell_1"
source my_script1.sh
echo "Back in shell_1"