bash 如何在 Shell Script 中的另一个函数中调用一个函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35617888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:18:27  来源:igfitidea点击:

How to call a function within another function in Shell Script?

bash

提问by leofelipe

Say I have this function:

说我有这个功能:

function run_sanity_check(){
   echo -e "This is test level 1\n"
   echo -e "This is test level 2\n"
}

and this other function:

和这个其他功能:

function run_test(){
  ... environment setup routine runs here
  echo -e "Running tests...\n"

  run_sanity_check --> this would be my call for the function above
}

When I call "run_test" I get this error: function: not found

当我调用“run_test”时出现此错误:函数:未找到

Any help is appreciated.

任何帮助表示赞赏。

回答by merlin2011

As Brian's comment mentions, you need to use either functionor ()but not both.

正如布赖恩的评论所提到的,您需要使用其中之一function()但不能同时使用两者。

Both of the following are valid, based on the documentation.

根据文档,以下两项均有效。

function run_sanity_check{
   echo -e "This is test level 1\n"
   echo -e "This is test level 2\n"
}


run_sanity_check(){
   echo -e "This is test level 1\n"
   echo -e "This is test level 2\n"
}

The following script prints expected output.

以下脚本打印预期的输出。

run_sanity_check(){
   echo -e "This is test level 1\n"
   echo -e "This is test level 2\n"
}

run_test(){
  echo -e "Running tests...\n"

  run_sanity_check 
}

run_test