Shell Script Programming Learning notes-functions

Source: Internet
Author: User
Tags exit in

1. Why use a function

Look at the role of aliases first

[[email protected] ~]# alias httpd=‘/etc/init.d/httpd‘[[email protected] ~]# httpd start正在启动 httpd:   [确定]

function is to call the program multiple times the same code part is defined as a copy and then a name for the code, all the other repeated calls this part of the code will only call this name, when the need to modify this part of the code, just modify a code in the function body to implement all the calls to modify.

Advantages of using functions:

(1) The same program segment is defined as a function, which reduces the amount of code for the entire program.

(2) Increase the readability and legibility of the program.

(3) can realize the modular function of the program, different programs using the function of modular.

Note: the 2000 commands of a Linux system can be said to be functions of a shell script.

Syntax for 2.Shell functions

Simple syntax Format:

Function name () {

Instructions...

return n

}

Canonical syntax format:

Function name () {

Instructions...

return n

}

Tip: The return value of the shell is the exit output return value, the function returns the value with return output

Execution of 3.Shell functions

Call Function:

(1) Direct execution function name without parentheses

Attention:

A. When executing a function, the parentheses after the function do not need to be

B. function definitions and function bodies must be defined before the name of the function to be executed, and the execution of the shell is
Executes from top to bottom by row.

(2) parameter of function

The function's arguments are similar to the script's, except that the script name is replaced by the function name.

Function Name parameter 1 parameter 2

Description of the parameters followed by the function:

A.shell position parameters ($, $ $, $ $, $4, $ $, $#, $*, $?) , [email protected]) can be parameters of a function.

B. The parameters of the parent script are temporarily obscured or hidden by the function arguments.

C.$0 is more special, it is still the name of the parent script.

D. When the function is complete, the parameters of the original command-line script can be restored.

E. Inside the shell function, the return command function is similar to exit in the shell, which is the function of jumping out of functions.

The F.return statement returns an exit value (return value) to the program that called the function.

G. The function's parameter variable is defined within the function body, and if it is a normal variable, it is generally used local, for example, defining a is defined by local a.

4.Shell Function Example

Example 1: Develop a script to build two simple functions and invoke execute

[[email protected] jiaobenlianxi]# cat hanshu01.sh #/bin/bashnishishei(){    echo "who are you?"}function linzhongniao(){    echo "I am linzhongniao"}nishisheilinzhongniao

Perform

[[email protected] jiaobenlianxi]# sh hanshu01.sh who are you?I am linzhongniao

If the function that we call is called in every script that we develop, we can write the function into/etc/init.d/functions, here, in order to make it easier to see the script with source, you can use the dot number "."

[[email protected] jiaobenlianxi]# tail -5 /etc/init.d/functions }linzhongniao(){    echo "I am linzhongniao"}[[email protected] jiaobenlianxi]# cat hanshu02.sh #/bin/bashsource /etc/init.d/functionsnishishei(){    echo "who are you?"}nishisheilinzhongniao[[email protected] jiaobenlianxi]# sh hanshu02.sh who are you?I am linzhongniao

Example 2: Function arguments are converted to script argument command-line parameters, which determine whether any specified URL is normal. Of course, you can also judge the service, such as MySQL, httpd and so on, and so on, like this does not say, the front branch loop structure has a judgment service example.

Steps to answer:

A. Script parameters Check that the Web URL is normal

B. Function of the check is written as function

C. function arguments are converted to script command-line arguments, and any specified URLs are judged to be abnormal.

[[email protected] jiaobenlianxi]# cat check_url.sh #!/bin/bash[ -f /etc/init.d/functions ]&& . /etc/init.d/functionsusage(){   #usage给用户一个提示    echo "USAGE:$0 url"     exit 1}RETVAL=0CheckUrl(){    wget -T 10 --spider -t 2 $1 &>/dev/null    jieguo=$?    if [ $jieguo -eq 0 ];then        action "$1 url" /bin/true    else        action "$1 url" /bin/false    fi      return $RETVAL}main(){    if [ $# -ne 1 ];then  判断参数输入参数的个数,如果不等于1执行usage函数    usage    fi    CheckUrl $1    jieguo=$?    Return $jieguo}main $*   # $*这里的作用是不管敲多少个参数都当成一个,防止乱输入别的东西

Execution Result:

[[email protected] jiaobenlianxi]# sh check_url.sh www.baidu.comwww.baidu.com url  [确定][[email protected] jiaobenlianxi]# sh check_url.sh www.sss.comwww.sss.com url[失败]

Example 3: Example of a parameter that adds color to a string

Use the If mode to implement the output color to be escaped with Echo–e.

[[email protected] jiaobenlianxi]# cat color.sh #!/bin/bashRED_COLOR=‘\E[1;31m‘GREEN_COLOR=‘\E[1;32m‘YELLOW_COLOR=‘\E[1;33m‘BLUE_COLOR=‘\E[1;34m‘PINK=‘\E[1;35m‘SHAN=‘\E[31;5m‘ #提示闪烁,配合echo –e 使用RES=‘\E[0m‘usage(){    echo -e  ${SHAN} "USAGE:$0 {red|green|yellow|pink}" contents ${RES}    exit 1  }color(){if [ "$1" = "red" ];then    echo -e "${RED_COLOR} $2 $RES"elif [ "$1" = "green" ];then    echo -e "${GREEN_COLOR} $2 $RES"elif [ "$1" = "yellow" ];then    echo -e "${YELLOW_COLOR} $2 $RES"elif [ "$1" = "blue" ];then    echo -e "${BLUE_COLOR} $2 $RES"else    usagefi}main(){    if [ $# -ne 2 ];then    usage    fi    color $1 $2}main $*
Expansion: 1. Add color directly
[[email protected] jiaobenlianxi]# cat color1.sh #!/bin/bashecho -e "\033[30m 黑色字 I am linzhongniao \033[0m"echo -e "\033[31m 红色字 I am linzhongniao \033[0m"echo -e "\033[32m 绿色字 I am linzhongniao \033[0m"echo -e "\033[33m ×××字 I am linzhongniao \033[0m"echo -e "\033[34m 蓝色字 I am linzhongniao \033[0m"echo -e "\033[35m 紫色字 I am linzhongniao \033[0m"echo -e "\033[36m 天蓝字 I am linzhongniao \033[0m"echo -e "\033[37m 白色字 I am linzhongniao \033[0m"

Execution results

2. Word Background color Range---47
[[email protected] jiaobenlianxi]# cat beijingcolor.sh #!/bin/bashecho -e "\033[40;37m 黑底白字 I am linzhongniao \033[0m"echo -e "\033[41;37m 红底白字 I am linzhongniao \033[0m"echo -e "\033[42;37m 绿底白字 I am linzhongniao \033[0m"echo -e "\033[43;37m 黄底白字 I am linzhongniao \033[0m"echo -e "\033[44;37m 蓝底白字 I am linzhongniao \033[0m"echo -e "\033[45;37m 紫底白字 I am linzhongniao \033[0m"echo -e "\033[46;37m 天蓝白字 I am linzhongniao \033[0m"echo -e "\033[47;30m 白底黑字 I am linzhongniao \033[0m"

Execution Result:

Shell Script Programming Learning notes-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.