我有两个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
其他回答
从其他文件导入函数会有一些问题。 首先:您不需要执行此文件。最好不要这样做! 只需添加
. 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.
有几种方法可以做到这一点。执行脚本的终端:
#!/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")
所有这些都是正确的路径与空格!!
只需在一行中添加您在终端中输入的任何内容来执行脚本! 例如:
#!bin/bash
./myscript.sh &
如果要执行的脚本不在同一目录下,请使用脚本的完整路径。 例如:“/ home / user /脚本目录/。/ myscript.sh &
取决于。 短暂的…… 如果你想在当前控制台加载变量并执行,你可以在你的代码中使用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
#!/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=$?