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](https://i-blog.csdnimg.cn/blog_migrate/3fd9df78bcf77a9e788922025eb9be2c.png)