function--function
The code that repeats in the script and does not have any changes is encapsulated to invoke execution in the appropriate scenario;
The programmer calls this encapsulated code a functional body, or a module;
In shell scripting, a function is a block of statements consisting of several shell commands, often used for code reuse and modular encapsulation;
The content inside the function is consistent with the shell program, except that the shell code can be executed directly, and the contents of the function cannot be executed independently, only when it is called;
The function is run in the shell program's current shell;
Bash
Bash Script_file
function
To define a function:
A function is made up of two parts:
Function name + function body (Shell statement block capable of implementing standalone functions)
Syntax One:
function Func_name {
function body
}
Syntax Two:
Func_name () {
function body
}
Note: The function name and () can not be added white space characters;
Note: Functions can be defined in an interactive environment or in a script.
Use of functions
When the function is defined, all the commands contained in its function body are not executed, and the command statements are executed only when the function is called;
Invocation method: Called by giving the function name directly;
There are many functions that are stored in a file that is dedicated to saving functions, and if you want to invoke a function saved in such a file, use the Source command (.). Load the file, and then call the function in a way that directly gives the function name;
Use the SET command to view all functions in effect in the current shell;
Use the unset command to undo a function that has already been defined;
The return value of the function:
Two kinds of return values:
Return value of the execution result of the function:
1. The result of the Echo or printf command output is used in the function body;
2. The result of some command output in the function body;
The status return value of the function:
1. The execution status return value of the last command in the function;
2. Custom Exit Status code:
return [n]
n:0-255
Note: As long as the function executes, the return command is encountered, regardless of whether the command statement in the function is complete or not, immediately exits the function;
The life cycle of a function:
Starting from being called, until the execution of a return command or all statements is completed;
Arguments to functions
In the function body, you can use $1,$2,.. Positional variables provide parameters for functions, you can also reference all positional parameters using $* or [email protected], and you can use $ #计算为函数传递的参数个数;
When calling a function, separate multiple arguments directly after the function name with whitespace characters, for example: Func_name arg1 arg2 ...
The positional parameter passed to the function parameter is the string sequence separated by a blank character after the function name when the function is called, and is not the same as the location parameter of the script;
Variable:
A variable in the shell is a weak variable
1. Without prior notice
2. No need to specify variable type, default to character type
Variable classification:
Environment variables:
Current Shell and child shell
Local variables:
Current Shell
Local variables:
Local Var_name=value
Current function body
Positional variables
Special variables
Manually revoke any variables that you define or declare;
recursive invocation of functions
In simple terms, the function itself is called in the function body;
Factorial:
n!=n* (N-1)!=n* (N-1) * (N-2)!=...=n* (N-1) * (N-2) *...*2*1
#!/bin/bash
# Author:Tianyu.Zhao
#
Fact () {
If [$1-eq 0] | | [$1-eq 1]; Then
Echo 1
Else
echo "$[$1*$ (Fact $[$1-1])]"
Fi
}
Echo-n "$1!="
Fact $
Example: Fibonacci sequence (gold-delimited series):
1 1 2 3 5 8 13 21 34 55 ...
Suppose the rabbit is born one months before it has the ability to reproduce:
N=n-1 + N-2
Shell code:
#!/bin/bash
# Author:Tianyu.Zhao
#
Fabonacci () {
If [$1-eq 1]; Then
Echo 1
elif [$1-eq 2]; Then
Echo 1
Else
Echo $[$ (Fabonacci $[$1-1]) +$ (Fabonacci $[$1-2])
Fi
}
#列出所有的斐波那契数列的项
For I in ' seq 0 '; Do
Fabonacci $I
Done
Example: Hanoi (also known as Hanoi) is an ancient Indian legend. When big Brahma created the world, he made three diamond pillars, and stacked 64 gold discs on a pillar from bottom to top in order of size. The great Brahma commanded the Brahman to rearrange the discs from below to the other pillars in order of size. It is also stipulated that the disc cannot be enlarged on the small disc, and only one disc can be moved between the three pillars at a time.
Using the function to realize the moving steps of the Hanoi of n disk
#!/bin/bash
# Author:Tianyu.Zhao
#
Step=0
Move () {
Let step++
echo "$step: Move disk $-----> $"
}
Hanoi () {
If [$1-eq 1];then
Move $ $4
Else
Hanoi "$[$1-1]" $ $4 $
Move $ $4
Hanoi "$[$1-1]" $ $4
Fi
}
Hanoi $ A B C
The contents of the file Abc.txt are as follows:
2,3,4,5,6
B,c,d,e,f
6,7,8,9,10
F,g,h,i,j
Write a script that uses either loop structure to output the second and fourth characters of each line (separated by commas)
Review:
Function of shell script programming
Practice:
Write a script:
1. Allow users to pass parameters through the command line to achieve user account management;
2. If the-a|--add option is given, the user account after the option is created;
3. If the-d|--del option is given, the user account after the option is deleted;
4. If the user gives the-v|--verbose option, it displays the information of the user who deleted or created it;
5. If the user gives the-H|--HELP option, displays the help information, and exits the script with 0 as the exit status code;
6. If the user gives other options, display the Help information and use 5 as the exit status code to run the Ghost animal script;
#!/bin/bash
#Author: Link
#Description: administrate Users
#5: No enough args
#6: Error args
#
Debug=0
Adduser=0
Deuser=0
Usage () {
echo "Usage: $ (basename $)-a|--add User1,user2,... | -d|--del User1,user2,... | [-v|-verbose] | [-h|--help] "
Echo
echo "Options:"
Echo-e "-A,--add\vcreate user from list."
Echo-e "-D,--del\vdelete user from list."
Echo-e "-V,--verbose\vdisplay infomation for your operating."
Echo-e "-H,--help\vdisplay this menu."
}
CreateUser () {
adduser_list=$ (echo $ | tr ', ")
For I in $ADDUSER _list; Do
If ID $I &>/dev/null; Then
[$DEBUG-eq 1] && echo "$I exists."
Else
Useradd $I &>/dev/null
echo $I | passwd--stdin $I &>/dev/null
[$DEBUG-eq 1] && echo "Create $I successfully."
Fi
Done
}
DeleteUser () {
deluser_list=$ (echo $ | tr ', ")
For J in $DELUSER _list; Do
If ID $J &>/dev/null; Then
Userdel-r $J &>/dev/null
[$DEBUG-eq 1] && echo "Delete $J finished."
Else
[$DEBUG-eq 1] && echo "$I not exists."
Fi
Done
}
If [$#-le 0]; Then
Usage
Exit 5
Fi
While [$#-ne 0]; Do
Case $ in
-H|--HELP)
Usage
Exit
;;
-v|--verbose)
Debug=1
Shift
;;
-a|--add)
Adduser=1
Alist=$2
Shift 2
;;
-d|--del)
Deluser=1
Dlist=$2
Shift 2
;;
*)
Usage
Exit 6
;;
Esac
Done
If [$ADDUSER-eq 1]; Then
CreateUser $ALIST
Fi
If [$DELUSER-eq 1]; Then
DeleteUser $DLIST
Fi
Linux Beginner's function