如何在 Bash 中将参数传递给函数并获取返回值?

Sno*_*opy 3 parameters bash arguments return

我的代码很简单。

variable=$( createTable $table_name )
Run Code Online (Sandbox Code Playgroud)

或者

returnedVariable=$( function $argument )
Run Code Online (Sandbox Code Playgroud)

我的代码在这一行中断。我无法在互联网上的任何地方找到如何在 Bash 中传递参数并获取返回值。

更新:我现在明白了。我的函数中不能有多个 echo。另外,echo 永远不应该被视为返回,而是可以捕获的打印语句或标准输出。感谢您的反馈!

kar*_*kfa 6

这就是你想做的吗?

$ function createTable() { echo "this is the table: $1"; }    
$ var=$(createTable "$table_name")
$ echo "$var"
this is the table: New Table
Run Code Online (Sandbox Code Playgroud)

请注意,该函数没有返回任何内容,而是为成功/错误状态保留的。这里将默认为零。概念上的“函数返回值”是通过标准输出实现的。这些不是数学意义上的“函数”。