Select and function under Linux

Source: Internet
Author: User
Tags define function

Select Loops and menus

It is primarily used to create menus, which are displayed as a list of menu items in the form of a numerically ordered display on the standard error output, and a PS3 prompt is displayed to request user input (by default, the value of PS3 is "#?"). )。 The heart is PS3. After the prompt, the shell waits for the user to enter, the input should be a number in the menu list, the input value is saved in a special variable of the shell reply China, which is associated with the string following the corresponding parentheses in the list of options.

When the case command is used in conjunction with the Select command, the user can select from the menu and execute the corresponding command based on the options.

1) Select Format

Select variable in list
Do
Circular Body Command
Done

2) Select and case Joint use

[[Email protected] newbin]# vi select.sh   1 #!/bin/bash  2   #function: select  3  #author:  xiaoshui  4 ps3= "Please input  a subject:  "  5 select var in language math english   quit;do //  6     case  $var  in         //selects the user to execute the corresponding command through the case command.   7     language)     8          echo  "you want to study  $var"   9          echo  $REPLY     //Displays the user's input  10 by REPLY variable saving          ;;  11     math)  12         echo   "you want to study  $var " 13         echo  $REPLY   14         ;;  15     english)  16          echo  "you want to study  $var"  17          echo  $REPLY  18         ;;  19     quit)  20         echo   $REPLY  21         exit 22          ;;  23     *)                  //If the user entered is not in the list, return to the following  24          echo  "Must be language|math|english|quit" &Nbsp;25         echo  $REPLY  26          ;;  27     esac 28 done[[email protected] newbin]# bash  select.sh 1) ( language2)  math3)  english4)  quitplease input a  subject: 1    //input 1, the language is assigned to the VAR variable you want to study language     1                             //shows what the user is typing through reply.  input a subject: 2you want to study math2please input a  subject: 3you want to study english3please input a subject:  dmust be language|math|english|quitdplease input a subject: 44[[email protected] newbin]# 

Function:

The code of an independent function as a whole, and so far named a name; a named code snippet, which is a function;

1) Important rules of the function

(1) The function must be defined first and then used

(2) The function shares the variable of the script that called it

(3) The function can accept parameters:

Pass parameters to the function:

In the function body, you can use the $1,$2: reference to arguments passed to the function, you can also use $* or [email protected] in the function to reference all parameters, $ #引用传递的参数的个数;

When calling a function, split the given argument list with a blank character after the function name, for example, TestFunc arg1 arg2

(4) Function return value:

The return value of the function's execution result:

(1) using the Echo or printf command to output;

(2) Execution result of the command invoked in the function

Exit status code for the function:

(1) The default depends on the exit status code of the last command executed in the function body;

(2) Custom: Return

(5) If the Exit command is used in the function, the entire script is introduced, even if there is a command behind the function.

(6) Functions can be saved in other files, using Srouce or. Load a file into a script

(7) Recursive function that calls itself

2) Declaration of functions

Functions consist of two parts: the function name and the function body.
Syntax One:
function f_name{
... function Body ...
}
Syntax Two:
F_name () {
... function Body ...
}

Functions can only be defined in the following environments

1. function can be defined in interactive environment
2. You can put a function in a script file as part of it
3. Can be placed in a separate file containing only functions

[[email protected] newbin]# cat func.sh #!/bin/bash#function:test functions#author:xiaoshuifun () {//fun is the function name E Cho "Hello World"//{} for function contents}

3) Use of functions

Call: The function is executed only if it is called;
Call: given function name
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

[[email protected] newbin]# bash func.sh Hello world[[email protected] newbin]# cat func.sh #!/bin/bash#function:test Fun Ctions#author:xiaoshuifun () {///define function, {} Inside for function content echo "Hello World"}fun//Call function (just write the name of the letter) [[Email PR Otected] newbin]#

4) return value of function

The

     function has two return values:     
     Execution result return value of the function:
          (1) output with the Echo or printf command
          (2) The output result of the call command in the function body
     exit status code for the function:
          (1) The default depends on the exit status code of the last command executed in the function
         (2) Custom exit status code, in the format:
        return returned from the function, using the last state command to determine the return value
         return 0 ERROR-free return.
        return 1-255 has an error returning

[[email protected] newbin]# cat funcadduser    //defines the function's file add () {if  id $1 &> /dev/null;then        //if ID to $1  Then return to 2    return 2else    useradd $1 &> /dev/ null        //otherwise returns the command return value of the last command of the Else statement, which is 0fi}[[email protected]  newbin]# cat funcadduser.sh#!/bin/bash#function: diaoyong func#author: xiaoshui . funcadduser                 //loading a function file read -p  "input a username you want to add: "   name    //Read variable [ -z  $Name  ] && echo  "No argue" &&exitadd  $Name                      //Call Function if [ $? -eq 0 ];then         //If the function returns a value of 0, then the statement after then is executed     echo  "user  $Name  add success!" else                         //otherwise executes the Else statement     echo  user  $Name   Exits. " fi    [[email protected] newbin]# [[email protected] newbin]#  vi funcadduser.sh [[email protected] newbin]# bash  funcadduser.sh  input a username you want to add: xiaoshui    // read  read-in variable user xiaoshui exits:                          //because Xiaoshui user exists beforehand [[EMAIL PROTECTED] NEWBIN]# bash  funcadduser.sh input a username you want to add:  nihaoma    user nihaoma exits. [[Email protected] newbin]# bash  funcadduser.sh input a username  you want to add: nihaoa    //because there is no NIHAOA in advance, then successuser  nihaoa add success!

     found a small detail of the return when testing the file. The code is as follows

[[Email protected] newbin]# vi funcadduser  1 add () {                       The function defined by        //is the same as above   2 if id $1 &>  /dev/null;then  3     return 2  4 else   5     useradd $1 &> /dev/null  6 fi   7 }~     [[email protected] newbin]# vi funcadduser.sh   1 #!/bin/bash  2  #function: diaoyong func  3  #author:  xiaoshui  4 . funcadduser  5 read -p  "input a  username you want to add:  " Name  6 [ -z  $Name  ]  && echo "No argue" &&exit  7 add  $Name   8 if [ $? -eq  0 ];then                The  //function returns a value of 0, which is useradd success  9     echo  "user  $Name  add success! "  10 elif [ $? -eq 2 ];then         The     //function returns a value of 2, which is exits 11     echo  "user  $Name  exits. "  12 else                Before              //wrote else, he would have thought that this was not the match. So I wrote a echo 13     echo  14 fi[[email protected] . newbin]# id xiaoshui            // XiaoshuI user pre-existing uid=1001 (Xiaoshui)  gid=1001 (Xiaoshui)  groups=1001 (Xiaoshui) [[email protected]  Newbin]# bash  funcadduser.shinput a username you want to add:  xiaoshui    //input Xiaoshui, but not the imagined exits[[email protected] newbin]#

Bash-x viewing the execution process

[Email protected] newbin]# bash-x funcadduser.sh+. funcadduser+ read-p ' input a username you want to add: ' Nameinput a username "want to add:xiaoshui+ ' ['-Z Xiaoshui  '] ' + add xiaoshui+ ID xiaoshui+ return 2//return2 nothing wrong, stating that the Add function is not wrong + ' [' 2-eq 0 '] '//judgment 2 equals 0 + ' [' 1 -eq 2 '] '//results show 1 is equal to 2, suddenly understood, the problem is here + echo[[email protected] newbin]#

through the above discovery, it can be concluded that, when the IF condition executes, if there is no match to the condition, the return value will be refreshed again, so that the result of the comparison of the return value after the command is meaningless. I remember

5) function recursion

function calls itself directly or indirectly
Note the number of recursive layers

Recursive instances

[[Email protected] bin]# VI func.sh 1 #!/bin/bash 2 # 3 fact () {4 If [$1-eq 0-o $1-eq 1]; then 5 echo 1 6 els E 7 echo $[$1*$ (Fact $[$1-1])] 8 fi 9} fact 5[[email protected] bin]# bash func.sh 120

Thank you for browsing

This article is from the "Endless Learning" blog, please be sure to keep this source http://dashui.blog.51cto.com/11254923/1841185

Select and function under Linux

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.