如何在BASH中的变量中保存函数的结果? [重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

这是我的第一个问题。我只想知道如何将函数'square'的结果保存到变量'sqr'中:

!/bin/bash

function square()
{
    let y=$x*$x
    return $y
}

x=3
**sqr=square**
echo "The square of $x is $sqr"
bash function
1个回答
2
投票

bash中的函数实际上是过程(它不返回任何内容)。因此,您有两个选择:在goblal变量中保存结果,或保存输出:

function myfunc(){
    myresult='anything'
}

myfunc
echo $myresult

要么

function myfunc(){
    local   myresult='anything'
    echo "$myresult"
}

result=$(myfunc)
echo $result
© www.soinside.com 2019 - 2024. All rights reserved.