在 bash 中使用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19262313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:14:22  来源:igfitidea点击:

Using functions in bash

bashfunctionshell

提问by codepk

Is this the correct syntax for parameterized functions?

这是参数化函数的正确语法吗?

#!/bin/bash

twoPow()
{
    prod=1
    for((i=0;i<;i++)); 
    do
        prod=$prod*2
    done
    return prod
}

echo "Enter a number"
read num
echo `twoPow $num`

Output:

输出:

bash sample.sh

bash 示例.sh

Enter a number

输入一个数字

3

3

sample.sh: line 10: return: prod: numeric argument required

sample.sh:第 10 行:返回:prod:需要数字参数

Part 2:I removed the return but what should I do if I want to run multiple times and store results like below. How can I make this work?

第 2 部分:我删除了返回但如果我想多次运行并存储如下结果该怎么办。我怎样才能使这项工作?

#!/bin/bash

tp1=1
tp2=1

twoPow()
{
    for((i=0;i<;i++)); 
    do
        =$(($prod*2))
    done
}

twoPow 3 tp1
twoPow 2 tp2
echo $tp1+$tp2

回答by Govind Parmar

In bash scripts you can't return values to the calling code.

在 bash 脚本中,您不能将值返回给调用代码。

The simplest way to emulate "returning" a value as you would in other languages is to set a global variable to the intended result.

像在其他语言中一样模拟“返回”值的最简单方法是将全局变量设置为预期结果。

Fortunately in bash all variables are global by default. Just try outputting the value of prodafter calling that function.

幸运的是,在 bash 中,默认情况下所有变量都是全局的。只需尝试prod在调用该函数后输出 的值。

回答by Mandar Pande

Sample Bash function defination and call with few parameters and return values, It may be useful and it works.

示例 Bash 函数定义和调用,参数和返回值很少,它可能很有用并且可以工作。

 #!/bin/sh

##Define fiunction 
function sum()
{

 val1=

 val2=

 val3=`expr $val1 + $val2`

 echo $val3

}

#Call function with 2 parameters and it return 1 parameter.
ret_val=$(sum 10 20)
echo $ret_val