Merge pull request #9951 from LuuMing/translate-new

Translated
This commit is contained in:
pityonline 2018-08-26 00:07:15 +08:00 committed by GitHub
commit 6fca0d7332
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 259 additions and 255 deletions

View File

@ -1,255 +0,0 @@
LuuMing Translating
How to define and use functions in Linux Shell Script
======
Function is a reusable block of code. Often we put repeated code in a function and call that function from various places. Library is a collection of functions. We can define commonly used function in a library and other scripts can use them without duplicating code.
[![Functions-Linux-Shell-Script][1]![Functions-Linux-Shell-Script][2]][2]
In this article well discuss more about functions and recipes. For demonstration purpose Ill be using **Bourne Again SHell(Bash)** on Ubuntu machine.
#### Calling function
In Shell calling function is exactly same as calling any other command. For instance, if your function name is my_func then it can be execute as follows:
```
$ my_func
```
If any function accepts arguments then those can be provided from command line as follows:
```
$ my_func arg1 arg2 arg3
```
#### Defining function
We can use below syntax to define function:
```
 function function_name {
            Body of function
 }
```
Body of function can contain any valid command, loop constrain, other function or script. Now let us create simple function which displays message on screen.
```
 function print_msg {
       echo "Hello, World"
 }
```
Now let us execute this function:
```
 $ print_msg
 Hello, World
```
As expected, this function displays message on screen.
In above example we have created function directly on terminal. We can store this function in file as well. Below example demonstrates this.
```
 #! /bin/bash
 function print_msg {
       echo "Hello, World"
 }
 print_msg
```
We have defined this function inside **function.sh** file. Now let us execute this script:
```
 $ chmod +x function.sh
 $ ./function.sh
 Hello, World
```
If you observe, above output is exactly identical to previous one.
#### More about functions
In previous section we have defined very basic function. However during software development we need more advanced functions which can accept various parameters and return values. In this section well discuss such functions.
**Passing arguments to function**
We can provide arguments to function same as other commands. We can access these arguments from function using dollar($) symbol. For instance, $1 represents first argument, $2 represents second argument and so on.
Let us modify above function to accept message as an argument. Our modified function will look like this:
```
 function print_msg {
       echo "Hello $1"
 }
```
In above function we are accessing first argument using $1. Let us execute this function:
```
 $ print_msg "LinuxTechi"
```
When you execute this function, it will generate following output:
```
 Hello LinuxTechi
```
**Returning value from function**
Like other programming languages, Bash provides return statement using that we can return value to the caller. Let us understand this with example:
```
function func_return_value {
      return 10
 }
```
Above function returns value 10 to its caller. Let us execute this function:
```
 $ func_return_value
 $ echo "Value returned by function is: $?"
```
When you execute above function, it will generate following output:
```
 Value returned by function is: 10
```
**NOTE:** In bash we have to use $? to capture return value of function
#### Function recipes
So far we got fair idea about bash functions. Now let us create some useful bash functions which can be used to make our lives easier.
**Logger**
Let us create logger function which will print date and time along with log message.
Let us execute this function:
```
 $ log_msg "This is sample log message"
```
When you execute this function, it will generate following output:
```
 [ 2018-08-16 19:56:34 ]: This is sample log message
```
**Display system information**
Let us create a function to display information about GNU/Linux system
```
 function system_info {
       echo "### OS information ###"
       lsb_release -a
       echo
       echo "### Processor information ###"
       processor=`grep -wc "processor" /proc/cpuinfo`
       model=`grep -w "model name" /proc/cpuinfo  | awk -F: '{print $2}'`
       echo "Processor = $processor"
       echo "Model     = $model"
       echo
       echo "### Memory information ###"
       total=`grep -w "MemTotal" /proc/meminfo | awk '{print $2}'`
       free=`grep -w "MemFree" /proc/meminfo | awk '{print $2}'`
       echo "Total memory: $total kB"
       echo "Free memory : $free kB"
 }
```
When you execute above function it will generate following output:
```
### OS information ###
No LSB modules are available.
Distributor ID:           Ubuntu
Description:   Ubuntu 18.04.1 LTS
Release:         18.04
Codename:    bionic
### Processor information ###
Processor = 1
Model     =  Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
### Memory information ###
Total memory: 4015648 kB
Free memory : 2915428 kB
```
Find file or directory from current directory
Below function searches file or directory from current directory:
```
 function search {
      find . -name $1
 }
```
Let us search directory namely dir4 using below command:
```
 $ search dir4
```
When you execute above command, it will generate following output:
```
 ./dir1/dir2/dir3/dir4
```
**Digital clock**
Below function creates a simple digital clock on terminal
```
 function digital_clock {
            clear
            while [ 1 ]
            do
                 date +'%T'
                  sleep 1
                  clear
            done
 }
```
#### Creating library
Library is a collection of functions. To create library define functions in a file and import that file in current environment.
Let us suppose we have defined all functions in utils.sh file then use below command to import functions in current environment:
```
$ source utils.sh
```
Hereafter you can execute any function from library just like any other bash command.
##### Conclusion
In this article we discussed few useful recipes which will improve your productivity. I hope this articles inspires you to create your own recipes.
--------------------------------------------------------------------------------
via: https://www.linuxtechi.com/define-use-functions-linux-shell-script/
作者:[Pradeep Kumar][a]
选题:[lujun9972](https://github.com/lujun9972)
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://www.linuxtechi.com/author/pradeep/
[1]:https://www.linuxtechi.com/wp-content/plugins/lazy-load/images/1x1.trans.gif
[2]:https://www.linuxtechi.com/wp-content/uploads/2018/08/Functions-Linux-Shell-Script.jpg

View File

@ -0,0 +1,259 @@
如何在 Linux Shell 脚本中定义和使用函数
======
函数是一段可复用的代码。我们通常把重复的代码放进函数中并且在不同的地方去调用它。库是函数的集合。我们可以在库中定义经常使用的函数,这样其他脚本便可以不再重复代码而使用这些函数。
[![Functions-Linux-Shell-Script][1]![Functions-Linux-Shell-Script][2]][2]
本文我们将讨论诸多关于函数的内容和一些使用技巧。为了方便展示,我将在 Ubuntu 机器上使用**Bourne Again SHell (Bash)**。
### 调用函数
在 Shell 中调用函数和调用其他命令是一模一样的。例如,如果你的函数名称为 my_func你就可以像下面那样执行它
```
$ my_func
```
如果你的函数接收多个参数,那么它们可以像下面那样写:
```
$ my_func arg1 arg2 arg3
```
### 定义函数
我们可以用下面的语法去定义一个函数:
```
 function function_name {
            Body of function
 }
```
函数的主体可以包含任何有效的命令、循环语句和其他函数或脚本。现在让我们创建一个简单的函数,它向屏幕上显示一些消息。
```
 function print_msg {
       echo "Hello, World"
 }
```
现在,让我们执行这个函数:
```
 $ print_msg
 Hello, World
```
不出所料,这个函数在屏幕上显示了一些消息。
在上面的例子中,我们直接在终端上创建了一个函数。我们也可以将这个函数保存在文件中。如下面的例子所示。
```
 #! /bin/bash
 function print_msg {
       echo "Hello, World"
 }
 print_msg
```
我们已经在 **function.sh** 文件中定义了这个函数。现在让我们执行这个脚本:
```
 $ chmod +x function.sh
 $ ./function.sh
 Hello, World
```
你可以看到,上面的输出和之前的是一模一样的。
### 更多关于函数
在上一小节中我们定义了一个非常简单的函数。然而在软件开发的过程中,我们需要更多高级的函数,它可以接收多个参数并且带有返回值。在这一小节中,我们将讨论这种函数。
**向函数传递参数**
我们可以像调用其他命令那样给函数提供参数。我们可以在函数里使用美元($)符号访问到这些参数。例如,$1 表示第一个参数,$2 代表第二个参数,以此类推。
让我们修改之前的函数,并接收信息当作参数。修改后的函数就像这样:
```
 function print_msg {
       echo "Hello $1"
 }
```
在上面的函数中我们使用 $1 符号访问第一个参数。让我们执行这个函数:
```
 $ print_msg "LinuxTechi"
```
执行完后,生成如下信息:
```
 Hello LinuxTechi
```
**从函数中返回数值**
跟其他编程语言一样Bash 提供了返回语句让我们可以向调用处返回一些数值。让我们举例说明:
```
function func_return_value {
      return 10
 }
```
上面的函数向调用处返回 10。让我们执行这个函数
```
 $ func_return_value
 $ echo "Value returned by function is: $?"
```
当你执行完,将会产生如下的输出结果:
```
 Value returned by function is: 10
```
**NOTE** 在 bash 中使用 $? 去获取函数的返回值
### 函数秘诀
到目前为止我们已经对 bash 中的函数有了相当多的了解。现在让我们创建一些非常有用的 bash 函数,它们可以让我们生活变得更加轻松。
**Logger**
让我们创建一个 logger 函数,它可以输出带有日期和时间的 log 信息。
```
function log_msg {
echo "[`date '+ %F %T'` ]: $@"
}
```
让我们执行这个函数:
```
 $ log_msg "This is sample log message"
```
当你执行完,就会生成如下信息:
```
 [ 2018-08-16 19:56:34 ]: This is sample log message
```
**显示系统信息**
让我们创建一个显示 GNU/Linux 信息的函数
```
 function system_info {
       echo "### OS information ###"
       lsb_release -a
       echo
       echo "### Processor information ###"
       processor=`grep -wc "processor" /proc/cpuinfo`
       model=`grep -w "model name" /proc/cpuinfo  | awk -F: '{print $2}'`
       echo "Processor = $processor"
       echo "Model     = $model"
       echo
       echo "### Memory information ###"
       total=`grep -w "MemTotal" /proc/meminfo | awk '{print $2}'`
       free=`grep -w "MemFree" /proc/meminfo | awk '{print $2}'`
       echo "Total memory: $total kB"
       echo "Free memory : $free kB"
 }
```
当你执行完后将会生成以下信息:
```
### OS information ###
No LSB modules are available.
Distributor ID:           Ubuntu
Description:   Ubuntu 18.04.1 LTS
Release:         18.04
Codename:    bionic
### Processor information ###
Processor = 1
Model     =  Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
### Memory information ###
Total memory: 4015648 kB
Free memory : 2915428 kB
```
在当前目录下查找文件或者目录
下面的函数从当前目录下查找文件或者目录:
```
 function search {
      find . -name $1
 }
```
让我们使用下面的命令查找 dir4 这个目录:
```
 $ search dir4
```
当你执行完命令后,将会产生如下输出:
```
 ./dir1/dir2/dir3/dir4
```
**数字时钟**
下面的函数在终端里创建了一个简单的数字时钟
```
 function digital_clock {
            clear
            while [ 1 ]
            do
                 date +'%T'
                  sleep 1
                  clear
            done
 }
```
### 创建库
库是函数的集合。创建库 将函数定义在文件里并在当前环境中导入那个文件。
假设我们已经在 utils.sh 中定义好了所有函数,接着在当前的环境下使用下面的命令导入函数:
```
$ source utils.sh
```
之后你就可以像调用其他 bash 命令那样执行库中任何的函数了。
### 结论
本文我们讨论了诸多实用的妙招,它将会提高你的效率。我希望这篇文章能够启发到你去创造自己的妙招。
--------------------------------------------------------------------------------
via: https://www.linuxtechi.com/define-use-functions-linux-shell-script/
作者:[Pradeep Kumar][a]
选题:[lujun9972](https://github.com/lujun9972)
译者:[LuuMing](https://github.com/LuuMing)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:http://www.linuxtechi.com/author/pradeep/
[1]:https://www.linuxtechi.com/wp-content/plugins/lazy-load/images/1x1.trans.gif
[2]:https://www.linuxtechi.com/wp-content/uploads/2018/08/Functions-Linux-Shell-Script.jpg