Functions: function
Program programming: Code reuse;
Modular programming;
Structured programming;
Consider the code of an independent function as a whole, and take a name for it; a named code snippet, which is a function;
Definition and use of functions:
Functions can be defined in an interactive environment;
A function can be placed in a script file as part of it;
Can be placed in a separate file containing only functions;
Interactively define functions: (defined in the current shell environment, restart invalidation)
#dir () {
> ls-l
>}
#dir #在命令行直接输入函数名dir执行函数; If the function name is the same as the system command name, the function takes precedence;
#unset dir #取消函数;
You can store frequently used functions in function files (libraries), and you need to load the function files into the shell when you call them;
Once the function file is loaded into the shell, the function can be called from the command line or script;
There are two ways to load a library of functions:
(1) Use the dot number:
. /path/to/file.sh
(2) using the source command:
Source/path/to/file
You can use the SET command to view all functions that are already loaded;
To modify a function, you need to unset cancel the function to load, modify and reload the shell;
Note: The code snippet that defines the function is not executed automatically, and the function is executed only if it is called;
Called functions, given the name of a function in the code;
Any location where the function name appears, is automatically replaced with the function code when the code executes;
Syntax One:
function F_name {
function body
}
Syntax Two:
F_name () {
function body
}
The life cycle of a function: created every time it is called, terminates when returned;
Its status returns the result of the state of the last command running in the function body;
Custom status return value, you need to use return
Return
0: Success
1-255: Failure
Given a user name, get the user ID number and the default shell;
#vim f1.sh
#/bin/bash
#
UserInfo () {
If ID "$" &>/dev/null;then
grep "^$1\>"/etc/passwd | Cut-d:-f3,7
Else
echo "No this user."
Fi
}
UserInfo $
#bash f1.sh Root
#bash f1.sh Keith
Rewrite service scripts with functions;
#!bin/bash
#chkconfig:-50 50
#description: Test Service script
#
Prog= ' basename
lockfile=/var/lock/subsys/$prog
Start () {
If [-F $lockfile];then
echo "$prog is running."
Else
Touch $lockfile
[$?-eq 0] && echo "Start $prog finished."
Fi
}
Stop () {
If [-F $lockfile];then
Rm-f $lockfile
[$?-eq 0] && echo "Stop $prog finished."
Else
echo "$prog is not running."
Fi
}
Status () {
If [-F $lockfile];then
echo "$prog is running."
Else
echo "$prog is stopped."
Fi
}
Usage () {
echo "Usage: $prog {start|stop|restart|status}"
}
Case $ in
Start
start;;
Stop
stop;;
Restart
Stop
start;;
Status
status;;
*)
Usage
Exit 1;;
Esac
function return value:
The return value of the function's execution result:
(1) using the Echo or printf command to output;
(2) The execution result of the command called in the function body;
Exit status code for the function:
(1) The default depends on the exit state of the last command executed in the function body;
(2) Custom: return;
return command:
Represents the return from the function returned to the keynote function to continue execution, the return can be customized to a return value;
Used in functions, common usage: returen n; n is a specified number that causes the function to exit with the specified value, and if no n value is specified, the return value is the exit state of the last command executed in the body of the function;
return [n]: Return from a shell function.
Vim return.sh
#/bin/bash
function fun_01 {#定义一个函数, which simply returns 1;
Return 1
}
Fun_01 #调用该函数;
echo $? #查看返回值;
#bash return.sh
1
Local: Declare the variables locally;
Used to declare a local variable in a script, typically used in the body of a function whose scope is in the body of the function that declares the variable;
If you attempt to use the local declaration variable outside the function body, you will be prompted with an error;
Local Var=value
#vim scope.sh
#!/bin/bash
#
Name=tom #本地变量;
SetName () {
Name=jerry #这里函数会调用本地变量;
echo "Function: $name"
}
SetName
echo "Shell: $name"
#bash scope.sh
Function:jerry
Shell:jerry
#vim scope.sh
#!/bin/bash
#
Name=tom #本地变量;
SetName () {
Local Name=jerry #局部变量, only used in function body, not affected by external;
echo "Function: $name"
}
SetName
echo "Shell: $name"
#bash scope.sh
Function:jerry
Shell:tom
Function parameters:
function can accept parameters;
When calling a function, the given argument list is separated by a whitespace character after the function name, for example: TestFunc arg1 arg2 ...;
In the function body, you can use $1,$2 ... to reference arguments passed to a function, or you can use $* or [email protected] in a function to reference all parameters, $ #引用传递的参数的个数;
Add 10 users, add the user's function using function implementation, the user name as a parameter passed to the function;
#! /bin/bash
#
AddUsers () {
If ID $ &>/dev/null;then
Return 5
Else
Useradd $
Retval=$?
Return $retval
Fi
}
For i in {1..10}
Do
AddUsers $1$i #脚本参数和函数参数是两回事;
Retval=$?
If [$retval-eq 0];then
echo "Add user ${1}${i} finished."
elif [$retval-eq 5];then
echo "User ${1}${i} exists."
Else
echo "Unknown error."
Fi
Done
function library:
The system comes with the function library:/etc/init.d/functions;
Although the Functions function library provides some useful functions, but only these functions are not enough, so self-development function library is a very important part of the daily work;
function recursion:
function calls itself;
Factorial (factorial):
10!=10*9!=10*9*8!=10*9*8*7! =...
n!=n* (n-1)!=n* (n-1) (n-2)! = ...
1!=1
0!=1
#vim factorial.sh
#/bin/bash
#
Fact () {
If [$1-eq 0-o $1-eq 1];then
Echo 1
Else
echo $[$1*$ (fact $[$1-1])
Fi
}
Fact $
#bash factorial.sh 10
3628800
Fibonacci sequence (Fibonacci sequence):
1,1,2,3,5,8,13,21,34,...
F (n) =f (n-1) +f (n-2)
#vim fibo.sh
#!/bin/bash
#
Fab () {
If [$1-eq 1-o $1-eq 2];then
Echo 1
Else
echo $[$ (Fab $[$1-1]) +$ (Fab $[$1-2])
Fi
}
For i in ' seq 1 ';d o
Fab $i
Done
#bash fibo.sh 7
1
1
2
3
5
8
13
Functions of Shell programming