嵌套函数调用Bash

And*_*een 6 bash function

现在,我正在尝试在另一个函数调用中嵌套一个bash函数调用(以便将一个函数的输出用作另一个函数的输入).是否有可能在bash中嵌套函数调用,我正试图在这里做?

首先,我定义了这两个函数:

returnSomething()
{
    return 5;
}

funky ()
{
  echo $1;
}
Run Code Online (Sandbox Code Playgroud)

然后,我尝试使用一个函数的输出作为另一个函数的输入.但是,下一个语句不会打印输出returnSomething.相反,它根本不打印任何东西.

funky $returnSomething; #Now I'm trying to use the output of returnSomething as the input for funky.
Run Code Online (Sandbox Code Playgroud)

rua*_*akh 10

你有两个问题.一个是return不设置函数的输出,而是设置其退出状态(成功为零,失败为非零).例如,echo foo输出 foo(加上换行符),但退出状态0.要控制输出,请使用echoprintf:

function returnSomething ()     # should actually be outputSomething
{
    echo 5
}
Run Code Online (Sandbox Code Playgroud)

另一个问题是$returnSomething(或${returnSomething})给出一个名为的变量的值returnSomething:

x=5          # sets the variable x
echo "$x"    # outputs 5
Run Code Online (Sandbox Code Playgroud)

要捕获命令的输出,请使用符号$(...)(或者`...`,但后者更棘手).所以:

function funky ()
{
    echo "$( "$1" )"
}
funky returnSomething    # prints 5
Run Code Online (Sandbox Code Playgroud)

要不就:

function funky ()
{
    "$1"          # runs argument as a command
}
funky returnSomething    # prints 5
Run Code Online (Sandbox Code Playgroud)

相反,如果您确实要捕获命令的退出状态,请使用特殊的shell参数?(在完成时将其设置为命令的退出状态):

function returnSomething ()
{
    return 5
}
function funky ()
{
    "$1"          # runs argument as a command
    echo "$?"     # prints its exit status
}
funky returnSomething    # prints 5
Run Code Online (Sandbox Code Playgroud)