我有两个shell脚本,a.sh和b.sh。
我如何从shell脚本a.sh调用b.sh ?
我有两个shell脚本,a.sh和b.sh。
我如何从shell脚本a.sh调用b.sh ?
当前回答
有几种方法可以做到这一点。执行脚本的终端:
#!/bin/bash
SCRIPT_PATH="/path/to/script.sh"
# Here you execute your script
"$SCRIPT_PATH"
# or
. "$SCRIPT_PATH"
# or
source "$SCRIPT_PATH"
# or
bash "$SCRIPT_PATH"
# or
eval '"$SCRIPT_PATH"'
# or
OUTPUT=$("$SCRIPT_PATH")
echo $OUTPUT
# or
OUTPUT=`"$SCRIPT_PATH"`
echo $OUTPUT
# or
("$SCRIPT_PATH")
# or
(exec "$SCRIPT_PATH")
所有这些都是正确的路径与空格!!
其他回答
有几种不同的方法可以做到这一点:
使用chmod a+x /path/to/file(Nathan Lilienthal的注释)使另一个脚本可执行,添加#!/bin/bash行(称为shebang),以及文件到$ path环境变量的路径。然后你可以调用它作为一个普通的命令; 或者用source命令(它是.的别名)调用它,就像这样: 源/道路/ /脚本 或者使用bash命令来执行它,比如: /bin/bash /道路/ /脚本
第一种和第三种方法将脚本作为另一个进程执行,因此另一个脚本中的变量和函数将不可访问。 第二种方法在第一个脚本的进程中执行脚本,并从另一个脚本中引入变量和函数(因此它们可以从调用脚本中使用)。
在第二种方法中,如果你在第二个脚本中使用exit,它也会退出第一个脚本。这在第一种和第三种方法中是不会发生的。
我一直在寻找的答案:
( exec "path/to/script" )
如前所述,exec替换shell而不创建新进程。但是,我们可以把它放在一个子壳层中,这是用副函数完成的。
编辑: 实际上("path/to/script")就足够了。
看看这个。
#!/bin/bash
echo "This script is about to run another script."
sh ./script.sh
echo "This script has just run another script."
#!/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=$?
从其他文件导入函数会有一些问题。 首先:您不需要执行此文件。最好不要这样做! 只需添加
. 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.