function calls in the shell

Source: Internet
Author: User
Tags define function function definition

What to learn in this chapter

---------- Function Introduction

---------- function Definition

---------- function uses

---------- differentiate return and the Exit

---------- Delete a function

---------- Precautions


1. Introduction function  

When you write complex shell scripts, the code that completes the task may need to be reused, and we can peel the blocks out and give them a name, called functions. So, when we use such a block of code, we just need to refer to the name of the function that the code block is given (as a function call).

2. Defining functions

<1> Two ways

▲ function FName

{
Command
Command
}

▲f name

{
Command
Command
}

<2> function name cannot be the same as command, command precedence is higher than function

<3> function Naming conventions

cannot be the same as the command, otherwise the command will not work properly.

function Precedence > commands

Aliases that have the same name as the function names cannot be defined, otherwise the function cannot be used.

Alias Precedence > Functions

So priority: Aliases > functions > Commands

Variables in the <4> function are set to local variables to prevent conflicts with shell variables

Verify

# # # #创建函数文件fun2, define the test function [[email protected] ~] #vim fun2function Test () {a=first echo "a= $a"}### #编写脚本testfun2. Sh[[email Protected] ~] #vim testfun2.sh #!/bin/bash#a=secondsource fun2testecho "a= $a" # # # #执行脚本 [[email protected] ~] #bash Testfun2.sh A=firsta=first

The result shows that although a=second is defined in the script, the test function is executed and has become first. In order to solve the confusion of variables in the variables and functions in the script, the variables in the function are generally defined as local variables.

3. Using functions

<1> load function

In a child shell, if you need to use a function in the parent shell, you need to load the function into the shell

Load mode

SOURCE FUNCTION

. FUNCTION

Note: After modifying a function, the shell must be re-loaded to take effect

<2> calling functions

Enter the function name and add parameters.

4. The function returns the value return and exit are different

Return: Exiting the current function

Return: returned from the function, with the last state command to determine the return value

Return 0: No error returned.

Return 1-255: Error returned

Exit: Exit the current script

5. Delete function

unset function: Deleting functions

Set: View all defined Functions

6, about function parameter transfer problem

Do not know if you have ever had such a question, in the function of how the parameters are passed? Because this defines a function in the C language : int cmp (int a, int b), the variable is already declared in the function. But the function in the shell does not define the parameters, how is this process done? The small part is also very confused at the beginning, and later understand that the Shell function through the function position variable and the reference of the variable can realize the parameter transfer. Here are some examples and instructions for the instructions, you can refer to.

# # # #创建函数文件fun1, define function addfunction Add () {local sum sum=$[$1+$2] echo $sum}### #编写脚本testfun1. Sh#!/bin/bashsource Fun1add $2### #执行脚本: [[email protected] ~/bin] #bash funadd.sh 1 23

The script refers to the location variable of the command line, and the $ and $ in the function are the first and second variables in the reference script, which we call the function position variable. ( One of the methods of the real-present-pass argument)

Look at the following situation

# # # #创建函数文件fun1, define function addfunction Add () {local sum sum=$[$1+$2] echo $sum}### #编写脚本testfun1. Sh#!/bin/bashsource Fun1read- P "Please input figures:" A B # # # # # # # # # # # # #执行脚本 #只添加此行add $2### [[email protected] ~/bin] #bash funadd.sh please input Figures:1 2/root/bin/fun1:line 3: +: Syntax Error:operand expected (Error token is "+")

Why is there an error? Because the positional variables referenced in the script are not 1 and $2, meaning that $ and $ are not values, the function does not refer to the value, and the result is of course wrong. The side also illustrates that read cannot reference positional variables.

So, how to solve it? The answers are as follows

#!/bin/bashsource fun1read-p "Please input the figures:" A badd $a $b [[email protected] ~/bin] #bash funadd.sh please Inpu T-figures:1 23

Because $ A and $b at this point refer to 1 and 2 of the command line input, and the function calls both values, the result is calculated correctly.

Look at one more situation

# # # #创建函数文件fun1, define function addfunction Add () {local sum sum=$[$a + $b] echo $sum}### #编写脚本testfun1. Sh#!/bin/bashsource Fun1add $ $ or add $a $b or add### #执行脚本 [[email protected] ~/bin] #bash funadd.sh Please input both figures:1 23

Small series has been tested, these three kinds of situations can run the results, in order to write simple, are listed here again. But do you know why this is? Because the function directly refers to the command-line parameters (two methods of implementing the method of the pass-through, the variable references that are specific to the weakly typed programming language ), it is not necessary to pass the script. So if you don't use characters such as $ A and $ $ in a script to refer to a variable, you use a character such as $ A and $b, and that's when the meaning of the argument doesn't exist.


Give another example to deepen the impression

# # # #创建函数文件fun3, define the function Stringfunction string () {if [= = ha]; then echo "Nihao" fi}### #编写脚本testfun3. Sh#!/bin/bash#source Fu n3a=hastring $aunset a### #执行脚本 [[email protected] ~] #bash testfun3.sh Nihao

# # # #创建函数文件fun3, define the function Stringfunction string () {if [$a = = ha]; then echo "Nihao" fi}### #编写脚本testfun3. Sh#!/bin/bash#source Fu N3a=hastring $a or string $ or stringunset a### #执行脚本 [[email protected] ~] #bash testfun3.sh Nihao



After-school intensive exercises

1, write the service script/root/bin/testsrv.sh, complete the following requirements

(1) Script acceptable parameters: Start, stop, restart, status

(2) If the parameter is not one of these four, prompted to use the format after the error exit

(3) If start: Creates a/var/lock/subsys/script_name and displays "Start successful"

Consider: What should I do if I have already started it in advance?

(4) If stop: delete/var/lock/subsys/script_name and show "Stop Complete"

Consider: What should I do if I have stopped in advance?

(5) If restart, stop first, then start

Consider: If there is no start, how to deal with it?

(6) If status, if/var/lock/subsys/script_name file exists, then "Script_nameis running ..." is displayed.

If the/var/lock/subsys/script_name file does not exist, "Script_name is stopped ..." is displayed.

Where: Script_name is the current pin name

# # # #创建函数文件testsrv, define multiple functions [[[Email protected] ~/bin/dir] #vim  testsrvfunction start ()  {     if [ -e /var/lock/subsys/testsrv.sh ]; then       echo  "Already start ..."     else       touch /var/lock/subsys/testsrv.sh      echo  "Start ok"     fi}function stop ()  {    if [ ! -e / var/lock/subsys/testsrv.sh ]; then      echo  "Already stop ... "    else      rm -f /var/lock/subsys/ testsrv.sh      echo  "Stop ok"     fi}function  restart ()  {    stop stop    start start}function  status ()  {  if&nbsp [ -e /var/lock/subsys/testsrv.sh ]; then    echo  "testsrv.sh  is running ... "  else    echo " testsrv.sh is stopped ... "  fi}function quit ()  {  exit 2}function again ()  {   While [ $1 != start -a $1 != stop -a $1 != restart  -a $1 != status ]; do  read -p  "Error,please enter  again: " choice  done}    ### #最后一个函数未使用, question. # # # #编写脚本testsrv3 .sh   source /root/bin/dir/testsrvcat << eoffour  Choices for you:start) stop) (restart) status) eofread -p  "please input your  Choice (start|stop|restart|status|quit): " CHOICE  while [  $CHOICE  != " Start "  -a  $CHOICE  !=  "Stop" &NBSP;-A&NBSP, $CHOICE  !=  "Restart"  -a  $CHOICE  !=  "status"  ]; do     read -p  "Error,please enter again:"  choice   donecase   $CHOICE  in start)   start   ;; Stop)    stop  ;; Restart)    restart   ;; Status)    status  ;; Quit)   quit   ;; Esac

or use Select

# # # #函数不变, rewrite the script #!/bin/bashsource testsrvps3= "Please input your choice:" Select choice in start stop restart status quit;  Do case $CHOICE in start) start;  stop) stop;;  restart) restart;;  status) status;  Quit) quit;; *) echo "Error,please Enter again ..." Esacdone

2. Scripting/root/bin/copycmd.sh

(1) Prompt the user to enter an executable command name;

(2) Get a list of all library files that this command depends on

(3) Copy the command to a target directory (e.g./mnt/sysroot) under the corresponding path;

such as:/bin/bash ==>/mnt/sysroot/bin/bash

/usr/bin/passwd==>/mnt/sysroot/usr/bin/passwd

(4) Copy all the library files that this command relies on to the corresponding path under the target directory:

such as:/lib64/ld-linux-x86-64.so.2 ==>/mnt/sysroot/lib64/ld-linux-x86-64.so.2

(5) After each copy completes a command, do not exit, but prompt the user to type the new command to copy, and repeat the above functions; until user input quit quit

# # # #创建函数文件copycmd, define multiple functions Function query ()  {  ldd /usr/bin/$1}function copy ()  {  mkdir /mnt/sysroot &> /dev/null  local dir1   dir1=/mnt/sysroot  cp /usr/bin/$1  $dir 1  mkdir /mnt/sysroot/lib64  &> /dev/null  local dir2  dir2=/mnt/sysroot/lib64  cp   ' ldd /usr/bin/ls | sed -r  ' [Email protected][[:space:]]+.*=>? [[: Space:]]? (.*) [[: space:]].*@\[email protected] '   $dir 2 &> /dev/null}function quit ()  {   if [ $1 == quit ]; then    exit  fi}## # #编写脚本copycmd4 #!/bin/bashsource copycmdps3= ' please input your option: ' Select option  in run quit; do      ### #列出俩个选项, whether running or exiting, select comes with loop function    case  $option &NBsp;in                        exit, option is run and Quit  run)     read -p  " Input your cmd: " cmd   ### #赋初值, otherwise cannot be compared with quit, direct error                                                                until [[  $CMD  == quit ]]; do      if   which  $CMD  &> /dev/null; then        query   $CMD            ### #调用函数          copy  $CMD             ### #调用函数        else        read -p  "Error,again:"   cmd        fi    read -p  "Input  Your cmd: " cmd   ### #纠正初值, compare with quit     done  ;;   quit)     quit  $option   ;;   esacdone





This article is from the "dmwing" blog, make sure to keep this source http://dmwing.blog.51cto.com/11607397/1841055

function calls in the shell

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.