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

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


当前回答

看看这个。

#!/bin/bash
echo "This script is about to run another script."
sh ./script.sh
echo "This script has just run another script."

其他回答

从其他文件导入函数会有一些问题。 首先:您不需要执行此文件。最好不要这样做! 只需添加

. file

导入所有函数。所有这些都是在文件中定义的。 第二:你可以定义同名的函数。它将被覆盖。它是坏的。你可以那样宣布

declare -f new_function_name=old_function_name 

and only after that do import. So you may call old function by new name. Third: You may import only full list of functions defined in file. If some not needed you may unset them. But if you rewrite your functions after unset they will be lost. But if you set reference to it as described above you may restore after unset with the same name. Finally In common procedure of import is dangerous and not so simple. Be careful! You may write script to do this more easier and safe. If you use only part of functions(not all) better split them in different files. Unfortunately this technique not made well in bash. In python for example and some other script languages it's easy and safe. Possible to make partial import only needed functions with its own names. We all want that in next bush versions will be done the same functionality. But now We must write many additional cod so as to do what you want.

我一直在寻找的答案:

( exec "path/to/script" )

如前所述,exec替换shell而不创建新进程。但是,我们可以把它放在一个子壳层中,这是用副函数完成的。

编辑: 实际上("path/to/script")就足够了。

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

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

只需在一行中添加您在终端中输入的任何内容来执行脚本! 例如:

#!bin/bash
./myscript.sh &

如果要执行的脚本不在同一目录下,请使用脚本的完整路径。 例如:“/ home / user /脚本目录/。/ myscript.sh &

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

bash another_script.sh

or

source another_script.sh

or

. another_script.sh

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