Linux Bash定义和调用函数

本文介绍了如何在Linux Bash中定义和调用函数,包括传递参数、返回值、变量作用域和局部变量的使用,以及如何通过源代码块导入函数。通过函数,可以简化复杂的命令执行,提高效率。
摘要由CSDN通过智能技术生成

Generally, bash commands are executed regularly. So running complex or multiple commands one by one is difficult. Or sometimes we just want to accomplish tasks with just one command without diving into it and distribute this command. Here are functions to make things very easy. Functions get parameters and execute functions code. A function has two ways to create. Here is syntax. Prefer the second one because portability is important.

通常,bash命令会定期执行。 因此,很难一一运行复杂或多个命令。 有时,我们只想只用一个命令来完成任务,而不必深入研究并分发此命令。 这是使事情变得很容易的函数。 函数获取参数并执行函数代码。 函数有两种创建方法。 这是语法。 最好选择第二个,因为可移植性很重要。

function function_name {
  function_body
}
function_name () {
  function_body
}

定义重击功能 (Define Bash Function)

Let’s create a function that creates a folder according to parameters.

让我们创建一个根据参数创建文件夹的函数。

function test {
        echo "Hello";
        echo "poftut.com";
}

As you see we used ; to make things more clear but omitting them do not hurts our code. Save this code as text file named test.sh .

如您所见,我们用过; 使事情更清楚,但省略它们不会损害我们的代码。 将此代码另存为名为test.sh的文本文件。

将参数或参数传递给函数 (Passing Arguments or Parameters To Function)

Sometimes functions need parameters to use inside. Using parameters in function is very easy just to put parameters between parenthesis and make a function call. Inside function block use $1, $2, $3, … which is the parameter row numbers.

有时函数需要在内部使用参数。 在函数中使用参数非常容易,只需将参数放在括号之间并进行函数调用即可。 在功能块内部使用$ 1,$ 2,$ 3,… ,这是参数行号。

function getParameters(){ 
        echo $1; 
        echo $2; 
        echo $3; 
}

And call the function named getParameters with parameters.

并使用参数调用名为getParameters的函数。

$ . ./bash_function.sh
$ getParameters p1 p2 p3
Passing Arguments or Parameters To Function
Passing Arguments or Parameters To Function
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值