在Unix Shell脚本中,将函数的返回值分配给一个变量

17
我尝试打印testfunction返回的值,但是没有显示任何内容。我使用./filename.sh来执行脚本,请帮忙。
#!/bin/ksh
testfunction()
{

k=5

return $k

}

val=$(testfunction)

echo  $val
3个回答

36

该函数返回的值存储在$?中,不会被$()捕获。

换句话说:

testFunction() 
{ 
    k=5
    echo 3
    return $k 
}

val=$(testFunction)
echo $? # prints 5
echo $val  # prints 3

0
您正在尝试的操作将在val变量中捕获函数中“回显”的最后一个值。
val=$(testFunction)

如果你想捕获函数的返回值,那么你应该使用$? [即echo $?],它是最后的退出状态。

-3

这个ksh函数是有效的:

IPADDRESS()     # get the IP address of this host
{
    # purpose: to get the IP address of this host
    #       and return it as a character string
    #
    typeset -l IPADDR
    IPADDR=$(ifconfig -a | grep inet | grep -v '127.0.0.1' | awk '{print $2}')
    print $IPADDR
}

IP_Address=$(IPADDRESS)
echo $IP_Address
exit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接