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

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


当前回答

假设新文件为“/home/satya/app/app_specific_env”,文件内容如下

#!bin/bash

export FAV_NUMBER="2211"

将该文件引用附加到~/。bashrc文件(

source /home/satya/app/app_specific_env

当您重新启动机器或重新登录时,尝试在终端中echo $FAV_NUMBER。它将输出该值。

以防万一,如果您想立即看到效果,请使用source ~/。在命令行中使用Bashrc。

其他回答

上面的答案建议添加#!/bin/bash行到被调用的下标脚本的第一行。但是即使你添加了shebang,在子shell中运行脚本并捕获输出也要快得多:

$(源SCRIPT_NAME)

当你想要继续运行同一个解释器(例如,从bash到另一个bash脚本)并确保子脚本的shebang行不被执行时,这是有效的。

例如:

#!/bin/bash
SUB_SCRIPT=$(mktemp)
echo "#!/bin/bash" > $SUB_SCRIPT
echo 'echo $1' >> $SUB_SCRIPT
chmod +x $SUB_SCRIPT
if [[ $1 == "--source" ]]; then
  for X in $(seq 100); do
    MODE=$(source $SUB_SCRIPT "source on")
  done
else
  for X in $(seq 100); do
    MODE=$($SUB_SCRIPT "source off")
  done
fi
echo $MODE
rm $SUB_SCRIPT

输出:

~ ❯❯❯ time ./test.sh
source off
./test.sh  0.15s user 0.16s system 87% cpu 0.360 total

~ ❯❯❯ time ./test.sh --source
source on
./test.sh --source  0.05s user 0.06s system 95% cpu 0.114 total

*例如,当病毒或安全工具在设备上运行时,可能需要额外的100ms来执行一个新进程。

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

然后像这样调用函数:

#!/bin/bash
my_called_function
 #!/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=$?

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

bash another_script.sh

or

source another_script.sh

or

. another_script.sh

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