About shell Script BASIC programming article Fourth

Source: Internet
Author: User
Tags function definition

Shell Script BASIC Programming fourth article
Main contents of this chapter: functions


Function
function
function name {command;} or name () {command;}
Defines the Shell function.
Create a shell function that is named name. When enabled as a simple command,
The NAME function executes the COMMANDs command in the context of the calling shell. When the NAME
When enabled, the parameter is passed to the function as a $ ... $n is stored in the variable as the name of the function
The $FUNCNAME.
Functional function is a block of statements consisting of several shell commands for code reuse and modular programming
and the shell program is similar in form, but the difference is that he is not a single process,

Cannot run independently, but is part of the shell program.

Functions consist of two parts: function name and function body
Grammar:
function F_name {
... function Body:
}
Grammar:
F_name () {
... function Body ...
}

Definition and use of functions:
Functions can be defined in an interactive environment
You can put a function in a script file as part of it
Can be placed in a separate file that contains only functions
Call: function will only be executed if called
Called: the given function name
Where the function name appears, it is automatically replaced with the function code
The life cycle of a function: when it is called, terminates when the creation returns

function return value:
The return value of the function's execution result:
Output using the Echo or printf command
The output of the call command in the function body
Exit status code for the function:
The default depends on the exit status code of the last command executed in the function

Custom Exit Status code:
Return returned from the function, with the last state command to determine the return value
Return 0 No error returned
Return 1-255 has error returned
==========================================================================

Example of command line, interactive environment
[[Email protected] ~]# function fun1 () {echo "Xiaomag";} Add in a line; semicolon
[Email protected] ~]# FUN1
Xiaomag
The function name is FUN1, the function body is output xiaomag, and then the FUN1 function name is entered directly, and the output is Xiaomag
==========================================================================

Simple example between shell scripts
[Email protected] ~]# vim fun2.sh
#!/bin/bash
#
#user: Compro
#简单定义函数名称, the function body can be a command, below a few simple commands

Fun2 () {This is considered to be a function embedded in the script
W.H.O.
The PWD function is usually in front of the file;
Ifconfig If you put the following echo in front, you will not be able to call this function;
Ls
The results of these commands are displayed after the hostname is executed. return value
echo "Execute function fun2 result" when all functions are executed, a new input is displayed, or it can be said to be a return value
}
echo "Execute function fun2 start" is displayed in the start output of this function body
Fun2
echo "Execute function fun2 End" executes when the above results are finished and last displayed

Functions must be defined before they are used, so the function definition should be placed at the beginning of the script,

The function body will not be used until the Shel is first discovered, and the function body can be used only with a defined function name.
Note: The functions defined in the script cannot be used alone under the command line, because not a shell process, both sides do not want to do

==========================================================================
Set can produce a variable that shows the definition. and functions;
The defined function is persisted until the user exits from the system, or the unset fun1 cancellation function definition is performed

Function Precedence:
Alias
Function
Internal
External

To use a function file:
You can store frequently used functions in a function file and then load the function file into the shell.
The file name can be arbitrarily selected, but it is best to have some kind of connection with the related task.
Example: Functions.main
==========================================================================[[email protected] ~]# Vim funs create function file
#/bin/bash
Fun3 () {Name of function
echo "Xiaomag" function body
}
Funn4 () {Name of function
Edho "Xiaomage" function body
You can define multiple functions
==========================================================================

When a function file is defined, it needs to be loaded into the current shell before it can be used, and the function is called in the command line or script.
You can use the SET command to view and examine all defined functions.
Its output list includes all functions that have been loaded into the shell.
Load the function file into the current shell:. FileName or source filename
Note: Click the space file name here to take the correct path

Execute Shell function:
[Email protected] ~]# FUN3
Xiaomag
[Email protected] ~]# FUN4
Xiaomage
==========================================================================

To change the function, first remove the function from the shell with the unset command, and then reload the file after the change is complete.
Now make some changes to the function. First remove the function so that it is not available to the shell. Use the unset command to complete this function
The command format is: unset function name
[[email protected] ~]# unset fun4 So there's no such thing as a set in the shell.
==========================================================================

Calling functions in a function file in a shell script
[[email protected] ~]# Vim testfuns.sh script
#/bin/bash
Source Funs calls the function in the Funs function file in the script, and if the function file is not in a path with the script, write the path clearly
Name of FUN3 function
Name of Fun4 function
==========================================================================

Function parameters:
Pass parameters to the function: When the function is called, the given argument list is separated by whitespace after the function name;
For example FUN1 variable 1 variable 2 ...
In the function body you can use $ ... Call these parameters; You can also use the [email protected],$*,$# and other special variables

function variables:
Environment variables: current shell and child shell are valid
Local variable: Only valid in the current shell process, a dedicated child shell process is started for script execution,
Therefore, the local variable is scoped to the current shell script file, including the function in the script
Local variables: The life cycle of a function, the automatic destruction of variables at the end of a function
Note: If there are local variables in the function, use local variables if their names are the same as local variables.

Methods for defining local variables in a function:
Local variable name = variable Value function is valid internally. The local variable is not added, plus the local variable


function recursion:
function calls itself directly or indirectly
Note the number of recursive layers
Example
Fun () {echo fun;fun;} Dead loop until a certain extent exits the current shell terminal
Fun () {let I++;echo $i; Increments the I loop. Exit current shell terminal until current system resource exhaustion

10! =10*9!=10*9*8!=10*9*8*7!= ...

N!=1*2*3....*n
(n-1)!=1*2*3....* (n-1) *n=n!
Fun
echo Fun n-1 * n
)

==========================================================================

vim fact.sh
#/bin/bash
#
#user: Compro
Fact () {     factorial function
If [$1-eq 0-o $1-eq 1];then call ' equals 0    0 ' factorial equals 1   or $1  1 's factorial is 1
&nbs p;       Echo 1 If the given value is 0 or 1, print 1
Else if it's not 0 or 0
         echo "$[$1* ' fact $[$1-1] '" $1* call functions themselves $1-1 values their factorial
fi
}
Fact by calling the value of the function '

Execution results
[[email protected] ~]# Bash fact.sh 1
1
[[email protected] ~]# Bash fact.sh 2
2
[[email protected] ~]# Bash fact.sh 3
6
[[email protected] ~]# Bash fact.sh 4
24
[Email protected] ~]# Bash-x fact.sh 4
+ Fact 4
+ ' [' 4-eq 0-o 4-eq 1 '] '
+ + fact 3
+ + ' [' 3-eq 0-o 3-eq 1 '] '
+ + + Fact 2
+ + + ' [' 2-eq 0-o 2-eq 1 '] '
++++ Fact 1
++++ ' [' 1-eq 0-o 1-eq 1 '] '
++++ Echo 1
+ + + Echo 2
+ + echo 6
+ Echo 24
24

·


This article from "Pony Brother Linux system operation and Maintenance" blog, reproduced please contact the author!

About shell Script BASIC programming article Fourth

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.