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

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


当前回答

你可以使用/bin/sh调用或执行另一个脚本(通过你的实际脚本):

 # cat showdate.sh
 #!/bin/bash
 echo "Date is: `date`"

 # cat mainscript.sh
 #!/bin/bash
 echo "You are login as: `whoami`"
 echo "`/bin/sh ./showdate.sh`" # exact path for the script file

输出将是:

 # ./mainscript.sh
 You are login as: root
 Date is: Thu Oct 17 02:56:36 EDT 2013

其他回答

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

#!/bin/bash
echo "My shell_1"
source my_script1.sh
echo "Back in shell_1"
chmod a+x /path/to/file-to-be-executed

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

感谢@Nathan Lilienthal的评论

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

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

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

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

然后像这样调用函数:

#!/bin/bash
my_called_function

取决于。 短暂的…… 如果你想在当前控制台加载变量并执行,你可以在你的代码中使用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