嵌套函数调用的Bash [英] Nested function calls in Bash
问题描述
现在,我试图巢1 bash函数调用内的另一个函数调用(以便于一个函数的输出被用作输入其他功能)。是否有可能巢函数调用在bash,因为我想在这里做什么?
首先,我定义这两个函数:
returnSomething()
{
返回5;
}时髦的()
{
回声$ 1;
}
然后,我试图使用一个函数的输出作为输入的其他功能。
然而,这下面的语句不打印 returnSomething
的输出。相反,它什么都不会打印。
时髦$ returnSomething; #Now我试图用returnSomething的输出作为输入时髦。
您有两个问题。其中之一是,收益
不设置的输出的一个功能,而是它的退出状态的(零成功,非零失败)。例如,回声富
将输出的富
(外加一个换行符),但有一个的退出状态的 0
的。要控制输出,使用回声
或的printf
:
函数returnSomething()#实际上应outputSomething
{
5呼应
}
另一个问题是, $ returnSomething
(或 $ {returnSomething}
)给出命名变量的值 returnSomething
:
X = 5#设置变量x
回声$ X#输出5
要捕获一个命令的输出,使用符号 $(...)
(或``...
,但后者是棘手)。所以:
函数时髦()
{
回声$($ 1)
}
时髦returnSomething#5打印
或者只是:
函数时髦()
{
$ 1#运行参数作为一个命令
}
时髦returnSomething#5打印
相反,如果你想拍摄一个命令的退出状态,使用特殊的shell参数?
(它被设置为命令时的退出状态它完成):
函数returnSomething()
{
返回5
}
功能时髦()
{
$ 1#运行参数作为一个命令
回声$? #打印其退出状态
}
时髦returnSomething#5打印
Right now, I'm trying to nest one bash function call inside another function call (so that the output of one function is used as the input for another function). Is it possible to nest function calls in bash, as I'm trying to do here?
First, I defined these two functions:
returnSomething()
{
return 5;
}
funky ()
{
echo $1;
}
Then, I tried to use the output of one function as the input for the other function.
However, this next statement doesn't print the output of returnSomething
. Instead, it prints nothing at all.
funky $returnSomething; #Now I'm trying to use the output of returnSomething as the input for funky.
You have two problems. One is that return
does not set the output of a function, but rather its exit status (zero for success, nonzero for failure). For example, echo foo
will output foo
(plus a newline), but has an exit status of 0
. To control output, use echo
or printf
:
function returnSomething () # should actually be outputSomething
{
echo 5
}
The other problem is that $returnSomething
(or ${returnSomething}
) gives the value of a variable named returnSomething
:
x=5 # sets the variable x
echo "$x" # outputs 5
To capture the output of a command, use the notation $(...)
(or `...`
, but the latter is trickier). So:
function funky ()
{
echo "$( "$1" )"
}
funky returnSomething # prints 5
or just:
function funky ()
{
"$1" # runs argument as a command
}
funky returnSomething # prints 5
By contrast, if you do want to capture the exit status of a command, use the special shell parameter ?
(which is set to the exit status of a command when it completes):
function returnSomething ()
{
return 5
}
function funky ()
{
"$1" # runs argument as a command
echo "$?" # prints its exit status
}
funky returnSomething # prints 5
这篇关于嵌套函数调用的Bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!