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

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


当前回答

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

. 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行到被调用的下标脚本的第一行。但是即使你添加了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来执行一个新进程。

pathToShell="/home/praveen/"   
chmod a+x $pathToShell"myShell.sh"
sh $pathToShell"myShell.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

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

bash another_script.sh

or

source another_script.sh

or

. another_script.sh

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

我一直在寻找的答案:

( exec "path/to/script" )

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

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