Shell Script-functions (function)

Source: Internet
Author: User
Tags addgroup variable scope

As a regular script operators, can find a problem, many times we are in different scripts to repeat the same piece of code. For example, we are going to use regular expressions to determine the legality of IP address, if each time to write the expression of the matching IP, the entire expression written down old elders, 0-9 of the number combination of the eyes are spent, is not very tired. Of course someone will say, after saving a correct code, need to use this code, the time to paste directly into the script you are writing is not OK! Yes, but that's not true. Many scripts contain the same piece of code, adding extra code to the script. There is no one of the best of both worlds, so that our script code is small, but also eliminates the repeated paste of the same piece of code each time the operation, while the perfect call to this code. The appearance of the Shell function is a perfect solution to our vision.

function Introduction
function is a block of statements consisting of several shell commands for code reuse and modular programming
It is similar to the shell program, but it is not a separate process, it cannot run independently, but is part of the shell program.

The difference between a function and a shell program:
Shell program runs in child shell
The Shell function runs in the current shell. So in the current shell, the function can modify the variables in the shell

Defines the syntax format for a function:
Functions consist of two parts: function name and function body
Syntax One:
function F_name {
... function Body ...
}
Syntax Two:
function F_name () {
... function Body ...
}
Syntax Three:
F_name () {
... function Body ...
}

How functions are defined:
1, the function can be defined directly in the interactive environment, the current shell environment can call
2, the function can be defined in the script file as part of it, you can only call
3, can be written in a separate function library file, any script can call

How to undo a function: unset functions Name

How the function is called:
1, when you call a function in the library, you first need to load the function library file with the source or, and then specify the name of the function to invoke.
Note:< points > < spaces > < function library file name > file name with correct path
2, the command line definition, the script itself is defined, directly specify the function name to be called to

Where the function name appears, it is automatically replaced with the function code
The life cycle of a function: created when invoked, terminated on return

To modify a function that has already been defined:
1, use the SET command to view all defined functions, whose output list includes all functions that have been loaded into the shell
2. Remove the function from the shell with the unset command, and reload the function or library file after the change is complete

function return value
The function has two return values:
1, the result of the execution of the function returns the value:
(1) Output with the Echo or printf command
(2) output of the call command in the function body

2, exit status code for the function:
(1) Return: The default depends on the exit status code of the last command executed in the function
(2) Return #: Custom exit status code, in the form of:
Return 0 No error returned
Return 1-255 has error returned

Defining and using functions in an interactive environment

Example code:
Dir () {
> ls-l
>}
After defining the function, if you type dir at the command line, its display results are the same as Ls-l
The Dir function will persist until the user exits from the system, or executes the unset command: unset dir

Defining and using functions in scripts
A function must be defined before it is used, so the function definition should be placed at the beginning of the script until the shell first discovers it before it can be used
The calling function uses only the name of its functions to

Example code:
#!/bin/bash

Maxnum () {
if [[$1-gt $]];then
Max=$1
Min=$2
elif [[$1-lt $]];then
Min=$1
Max=$2
Fi
Echo Maxnum is: $max
Echo Minnum is: $min
}

Maxnum 100 200

Create a function inventory file
Example code:
#!/bin/bash

#Author: Wangjun
#Contact qq:183530300
#Version: 1.0
#Create time:2016-08-18 14:58:52
#Description: Founction Lib

#maxnum and Minnum
Maxnum () {
if [[$1-gt $]];then
Max=$1
Min=$2
elif [[$1-lt $]];then
Min=$1
Max=$2
Fi
echo Maxnum: $max
echo Minnum: $min
}

#operation
Operation () {
Let Sum=$[$1+$2]
echo "$ sum is: $sum"
Let Reduce=$[$1-$2]
echo "$ reduce is: $reduce"
Let Product=$[$1*$2]
echo "$ product is: $product"
Let Quotient=$[$1/$2]
echo "$ quotient is: $quotient"
}

function arguments (functions can accept parameters):
Pass parameters to the function: when calling a function, separate the given argument list with whitespace after the function name, for example "TestFunc arg1 arg2 ..."
In the body of the function, $1,$2 can be used,... These positional variables can also be used [email protected], $*,$# and other special variables

function variables
Variable scope:
Environment variables: current shell and child shell are valid
Local variable: Only valid for the current shell process, the dedicated child shell process is started when the script is executed, so the local variable is scoped to the current shell script, including the function in the script
Local variables: Valid for the life cycle of a function; The variable is automatically invalidated at the end of the function
Note: If there is a local variable in the function whose name is the same as the local variable, the local variable is overwritten

Methods for defining local variables in a function: local name=value

Function recursion: function calls itself directly or indirectly

Recursive instances:
Factorial is an operational symbol invented by Kiston Kaman in 1808, which is the factorial of a positive integer in mathematical terms (factorial) is the product of all positive integers less than and equal to that number, and has a 0 factorial of 1, and the factorial writing of natural number n n!
N!=1x2x3x...xn
Factorial can also be defined recursively: 0!=1,n!= (n-1)!xn.
N!=n (n-1) (n-2) ... 1
N (n-1)! = N (n-1) (n-2)!

To define a standard recursive function:
Example code:
Recursive () {
If [$1-eq 0-o $1-eq 1];then
Echo 1
Else
Echo $[$1*$ (recursive $[$1-1])
Fi
}

650) this.width=650; "title=" Recursive.png "alt=" Wkiom1e5wbbqpahfaabnh5uivfe002.png "src=" http://s1.51cto.com/ Wyfs02/m01/86/3a/wkiom1e5wbbqpahfaabnh5uivfe002.png "/>

Note the number of recursive layers: the shell environment recursive maximum support 25, more than 25 of the recursive shell can not be calculated and expressed.

Call the function application instance in the script:

User-managed function library files that need to be called

[[email protected] fun]# cat function
#!/bin/bash

#Author: Wangjun
#Contact qq:183530300
#Version: 1.0
#Create time:2016-08-18 14:58:52
#Description: Founction Lib

AddUser () {
Read-p "Please input a new username:" User
! ID $user &>/dev/null && useradd $user &>/dev/null && echo "$user user add Success" | | echo "$user User exists"
}

Deluser () {
Read-p "Please input a exists username:" User
ID $user &>/dev/null && userdel-r $user &>/dev/null && echo "$user user delet success" | | echo "$user user doesn ' t exist"
}

AddGroup () {
Read-p "Please input a new groupname:" Group
! (Getent Group | grep "^ $group \>") &>/dev/null && groupadd $group &>/dev/null && echo "$ Group group Add Success "| | echo "$group Group exists"
}

Delgroup () {
Read-p "Please input a exists groupname:" Group
Getent Group | grep "^ $group \>" &>/dev/null && groupdel $group &>/dev/null && echo "$group group Delet Success "| | echo "$group group doesn ' t exist"
}

Invoking a library to implement user-managed scripts
[email protected] fun]# cat useradmin.sh
#!/bin/bash

#Author: Wangjun
#Contact qq:183530300
#Version: 1.0
#Create time:2016-08-18 19:29:03
#Description: User admin function test

. function
ps3= "Please choice:"
Select Choose in "Add User" "Delet user" "Add Group" "Delet Group" "Exit"
Do
Case $choose in
"Add User")
AddUser
;;
"Delet user")
Deluser
;;
"Add Group")
AddGroup
;;
"Delet Group")
Delgroup
;;
Exit
Exit
;;
Esac
Done
[Email protected] fun]#

Execution effect:

650) this.width=650; "title=" Funuseradmin.png "alt=" Wkiol1e5y9dsjohiaabisn9qcr8129.png "src=" http://s4.51cto.com/ Wyfs02/m01/86/3a/wkiol1e5y9dsjohiaabisn9qcr8129.png "/>

Through this example, it is not difficult to find that the calling function writes out the script code is small, looks quite clear, the pre-defined functions are stored in their own library, and later calls are not very convenient. About the function is to share here, the simple application should be no problem. Of course, follow-up is always updated.

This article is from the "Love Firewall" blog, be sure to keep this source http://183530300.blog.51cto.com/894387/1840837

Shell Script-functions (function)

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.