bash通过$(functionname)调用函数不起作用

时间:2015-03-09 14:45:26

标签: bash function

我在列表#7的http://www.ibm.com/developerworks/library/l-bash-parameters/index.html上找到了以下对函数的调用:

iNewValue=$(testthis)

在我看来比调用函数和获取返回值更优雅:

testthis 4
echo "Now we have a result: $?"

测试时,它不起作用 - 试试这段代码

#!/bin/bash
#==============================================================
function testthis(){
   echo "In testthis with Param: $1"
   iResult=42
   return $iResult
}
#==============================================================
echo "Starting first run"
iNewValue=$(testthis 1 )
echo "First run ended with: $iNewValue"
echo "Starting second run"
testthis 2
echo "Second run ended with: $?"

我得到了:

Starting first run
First run ended with: In testthis with Param: 1
Starting second run
In testthis with Param: 2
Second run ended with: 42

我希望:

Starting first run
In testthis with Param: 1
First run ended with: 42
Starting second run
In testthis with Param: 2
Second run ended with: 42

请注意,实际输出首先打印调用函数后的行,然后打印函数的输出。出了什么问题? 提前谢谢。

1 个答案:

答案 0 :(得分:3)

$()捕获函数的输出而不是返回码。要捕获返回代码,您需要检查$?