Shell Programming Basics: Functions

Source: Internet
Author: User
Tags function definition

Directory index of this blog post

[TOC]

First, the Cognition function (a) What is a function?

1, the function, the English called: function
2. A function is a block of statements made up of several shell commands

(b) Why should I use a function?

1. Implement code reuse, save a lot of duplicated blocks of code
2, the implementation of modular programming, different functional modules are relatively independent, conducive to shell statement block bug debugging and feature updates

(iii) Relationship of functions to shell scripts

1. Functions are typically placed in shell scripts and are part of the shell script
2. Function cannot run independently, need to call run in shell script
3. When the shell script runs, a bash subprocess is created, and the called function is run in this sub-process

(iv) Misconceptions about functional comprehension

1. Function cannot run alone, must be called to run
2, function is called runtime, can not open child process, only run in the current bash process
3. When the function is called run, the normal and global variables of the current bash process can be used, and they can be re-assigned or unassigned

Two, the definition function (a) function of the composition structure

Functions consist of two parts: function name and function body

1. Name of function

(1) The name of the function, the general wording is: Func_name
(2) Use of function names when calling functions in shell scripts
(3) The naming of function names must follow the naming conventions!

2. Function body

(1) The body of a function, which is a block of statements made up of several shell commands
(2) The statement block is enclosed with a pair of curly braces {}, which must be separated by a space between the statement block and the curly braces!

(b) Function name naming specification

1, the proposed function name naming standard: Func_ + Hump method

    • Small Hump: Func_namingnotation
    • Big HUMP: Func_namingnotation

2, Warning: in order to avoid the function name and command name conflict, it is not recommended that the internal command name, external command name, command alias as a function name of the name!!!

(c) syntax format for function definition 1, first syntax format
func_name(){    ...函数体...}
2. Second syntax format
function func_name{    ...函数体...}
3. Third syntax format
function func_name(){    ...函数体...}
Three, function use (a) function of three ways to use

1. function can be defined in interactive environment
2. Functions can be placed in a script file as part of a script file
3. Can be placed in a separate file containing only functions

(ii) Interactive environment definition and use functions
[[email protected] ~]#  #在交互式环境下定义函数[[email protected] ~]#func_dir(){[[email protected] ~]> ls -l[[email protected] ~]>}[[email protected] ~]#  #在交互式环境下调用函数[[email protected] ~]#func_dir

1. In an interactive environment, you can define the Func_dir function by entering the left curly brace {trigger multi-line redirection, entering a code block in a multiline redirect, and then ending the multiline redirection with the closing curly brace}
2, after the function is defined, in the interactive environment, you can run this function by means of function name Func_dir call, execution effect is equivalent to directly executing ls-l
3, after defining the function, the function will remain until the current bash process exits
4, the current bash process exits, the function immediately expires
5. You can also run the unset command in the current bash process to invalidate the function immediately

[[email protected] ~]#  #在交互式环境下取消函数[[email protected] ~]#unset func_dir
(iii) defining and using functions in scripts
#!/bin/bash#fileName:func_test.sh#在脚本中定义函数func_helloWorld(){    echo"Hello World!";    echo"Today is `date +%F`";}#在脚本中调用函数func_helloWorld;

Execution Effect: Print the following two lines of information in standard output
Hello world!
Today is 2018-05-10

1, note: The function must be defined first, then call!
2. Function definition code block must be placed at the beginning of script, function call must be after function definition code block
3. Use only that function name when calling
4, the validity of the function is the lifetime of the bash child process created for this script, and once the bash subprocess exits, the function immediately fails

(iv) Using function file 1, why use a function file?

(1) You can store frequently used functions in a function file and then use the function file to load the shell to implement the function reuse
(2) Function file name suggested some kind of connection with related tasks

Example: The IPV4 address used to obtain the native eth0 NIC
Functions.showip

2. Create a function file
#!/bin/bash#fileName:functions.showIP#在函数文件中定义函数showIP(){    #用来获取本机eth0网卡的IPv4地址,CentOS6和CentOS7通用!    ip|grep"^2:"|tail|sed‘s/.* ([1-9].*)\/.*/\1/‘;}

Note: The function file name is FUNCTIONS.SHOWIP, and the function name is SHOWIP

(1) The writing format of the function file is the same as that of the shell script, but the function file is mainly stored in the function definition
(2) function file is generally a normal text file, without the executable property

3. Load the function file into the shell process (1) Load the function file into the current bash process in an interactive environment
[[email protected] ~]#  #在交互式环境下将函数文件载入当前Bash进程[[email protected] ~]#source ./functions.showIP[[email protected] ~]#  #在交互式环境下调用函数文件中的函数showIP[[email protected] ~]#showIP

Execution effect: Print the IPV4 address of the native eth0 NIC in standard output
172.20.43.100

(2) Loading the function file into the bash subprocess created by the current script in the script
#!/bin/bash#fileName:test_showIP.sh#在脚本中将函数文件载入当前脚本创建的Bash子进程source ./functions.showIP;#在当前脚本创建的Bash子进程中调用函数文件中的函数showIPshowIP;

Execution effect: Print the IPV4 address of the native eth0 NIC in standard output
172.20.43.100

(3) syntax format for loading function files

The first syntax format:
source /PATH/fileName
<source><空格><文件名>

The second syntax format:
. /PATH/fileName
<点><空格><文件名>

(4) Precautions

The file name here takes the correct path, you can use an absolute path or a relative path

4. Check if the function is loaded into the current bash process
[[email protected] ~]#在交互式环境下查看当前Bash进程已经载入的所有函数[[email protected] ~]#set

Execution effect: Prints all functions that are already loaded by the current bash process in standard output
[Omit output information here]

5. Delete functions that have been loaded into the current bash process

Once the function definition has been modified, it is necessary to delete the currently loaded bash process so that it is not available for the current bash process

[[email protected] ~]#  #删除已经载入当前Bash进程的函数showIP[[email protected] ~]#unset showIP

Command format:
unset func_name

6. Environment function

(1) The function defined by default is only valid in the current bash process and cannot be passed to the child process of the current bash process, which is called the normal function
(2) export allows the function to be valid in the current bash process and its child processes, which are called environment functions
(3) Note: The function must be defined before it can be declared as an environment function by export! The definition and declaration of an environment function cannot be merged!!!

[[email protected] ~]#  #声明环境函数[[email protected] ~]#export -f showIP

Command format:
export -f func_name

[[email protected] ~]#  #只查看当前Bash进程已经声明的环境函数[[email protected] ~]#export -f[[email protected] ~]#declare -xf

Attention:
Set is a view of all functions in effect for the current bash process
Export-f or DECLARE-XF only view the environment functions that are already declared by the current bash process

function member (i) function parameter 1, review: Common parameters and special variables in shell
parameter name/special variable name meaning of the expression
$ First positional parameter
$ Second positional parameter
[Email protected] Position parameter list as a whole
$* Positional parameter list members are independent of each other
$# Number of positional parameters
2. Passing parameters to functions

When a function is called, the given argument list is split with whitespace after the function name

#!/bin/bash#fileName:test_argsList4Func.sh#在脚本中定义函数func_argsList4Func(){    #获取位置参数列表    echo$#;}#在脚本中调用函数func_argsList4Func;
[[email protected] ~]#  #把参数列表传递给脚本中的函数[[email protected] ~]#bash ./test_argsList4Func.sh a b c;

Execution effect: The number of print position parameters in the standard output
3

(b) Function variable 1, three kinds of variables inside the function

(1) Common variables
(2) Environment variables
(3) Local variables

2. Common variables

(1) Variables defined in the function body by default, are normal variables
(2) The scope of the normal variable is only valid for the current shell process
(3) When the current shell process exits, normal variables are automatically destroyed

3. Environment variables

(1) Use the export declared variable in the function body, which is the environment variable
命令格式:
export NAME=VALUE

(2) The scope of the environment variable is the current shell process and its shell child process
(3) Environment variables are destroyed only when the current shell process and its shell subprocess have all finished exiting

4. Local Variables

(1) A variable that is declared in the function body is a local variable
命令格式:
local NAME=VALUE

(2) Local variables are valid only in the body of the function and cannot be passed over the body of the function to affect the current shell process
(3) When the function call ends, the local variable is automatically destroyed

(c) Function return value 1, two return values of function

(1) Return value of function execution result
(2) Exit Status code for function

2, the function of the result of the return value (1) function inside the body using Echo and other commands, execution results as a return value output
#!/bin/bash#fileName:test_echoReturnValue.sh#在脚本中定义普通函数func_echoReturnValue(){    #使用echo命令    echo Hello World!;}#在脚本中调用普通函数func_echoReturnValue;
[[email protected] ~]#  #在当前Bash进程的Bash子进程中运行脚本[[email protected] ~]#bash ./test_echoReturnValue.sh

Execution effect: Print one line of information in standard output
Hello world!

(2) Function body Call command, execution result as return value output
#!/bin/bash#fileName:test_showIPReturnValue.sh#在脚本中定义普通函数func_showIPReturnValue(){    #调用ip命令    ip|grep"^2:"|tail|sed‘s/.* ([1-9].*)\/.*/\1/‘;}#在脚本中调用普通函数func_showIPReturnValue;
[[email protected] ~]#  #在当前Bash进程的Bash子进程中运行脚本[[email protected] ~]#bash ./test_showIPReturnValue.sh

Execution effect: Print the IPV4 address of the native eth0 NIC in standard output
172.20.43.100

3. The exit status code of the function (1) is determined by default depending on the exit status code of the last command executed in the function
#!/bin/bash#fileName:test_defaultReturnValue.sh#在脚本中定义普通函数func_defaultReturnValue(){    #调用true命令,没有任何标准输出,只有退出状态码为0    true;}#在脚本中调用普通函数func_defaultReturnValue;#查看函数中执行的最后一条命令的退出状态码echo$?;
[[email protected] ~]#  #开启Bash子进程运行包含函数调用的脚本[[email protected] ~]#bash ./test_defaultReturnValue.sh

Execution effect: Print one line of information in standard output
0

(2) Custom exit status code
#!/bin/bash#fileName:test_assignReturnValue.sh#在脚本中定义普通函数func_assignReturnValue(){    #指定退出状态码为255    return 255;}#在脚本中调用普通函数func_assignReturnValue;#查看函数中的自定义退出状态码echo$?;
[[email protected] ~]#  #开启Bash子进程运行包含函数调用的脚本[[email protected] ~]#bash ./test_assignReturnValue.sh

Execution effect: Print one line of information in standard output
255

-eof-

Shell Programming Basics: Functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.