在另一个函数中调用一个函数

art*_*lla 2 linux bash shell

我试图从另一个 bash 函数中调用一个 bash 函数,但它没有按预期工作:

#/bin/bash
function func1(){
    echo "func1 : arg = ${1}"
    return 1
}
function func2(){
    echo "func2 : arg = ${1}"
    local var=func1 "${1}"
    echo "func2 : value = $var"
}
func2 "xyz"
Run Code Online (Sandbox Code Playgroud)

和当前的输出是:

Current output :
func2 : arg = xyz
func2 : value = func1
Run Code Online (Sandbox Code Playgroud)

问题:如何修改上面的程序以获得以下输出?:

Desired output : 
func2 : arg = xyz
func1 : arg = xyz
func2 : value = 1
Run Code Online (Sandbox Code Playgroud)

cda*_*rke 5

Bash 中的函数与许多其他语言中的函数的工作方式不同,它们只能返回 0 到 255 之间的整数。这是$?在函数调用后使用的。如果您想获取其他值,例如字符串,请在子 shell 中调用它:

local var=$(func1 "${1}")
Run Code Online (Sandbox Code Playgroud)

将从echo函数中获取标准输出(来自语句)到$var.

顺便说一下,函数语法是:

function func1 { ... }
Run Code Online (Sandbox Code Playgroud)

或者

func1() { ... }
Run Code Online (Sandbox Code Playgroud)