Shell script: Functions

Source: Internet
Author: User
Tags function definition

The Shell also supports functions. The shell function must be defined before use.

Definition and invocation of a function

The Shell functions are defined in the following format:

Function_name () {    List of commands    [return value]}

function return value, you can explicitly increment the return statement, if not added, the last command will run the result as the return value.

The calling function only needs to give the function name, and no parentheses are required. A simple example of the Shell function definition and invocation is given below:

#!/bin/function  Herehello () {   echo"hello World" ThefunctionHello

Then look at a function with a return statement:

#!/bin/Bashfunwithreturn () {Echo "The function is to get the sum of the numbers ..."    Echo-N"Input First Number:"Read AnumEcho-N"Input Another number:"Read AnothernumEcho "The numbers is $aNum and $anotherNum!"return $ ($aNum+$anotherNum))} funwithreturn# Capture value Returnd by LastCommandret=$?Echo "The sum of numbers is $ret!"

Like deleting a variable, deleting a function can also use the unset command, but add the. F option

function parameters

In the shell, arguments can be passed to a function when it is called. Inside the function body, get the value of the parameter in the form of a $n

#!/bin/Bashfunwithparam () {Echo "The value of the first parameter is $ !"    Echo "The value of the second parameter is $!"    Echo "The value of the tenth parameter is $!"    Echo "The value of the tenth parameter is ${10}!"    Echo "The value of the eleventh parameter is ${11}!"    Echo "The amount of the parameters is $#!"# Number of parametersEcho "The string of the parameters is $*!"# All arguments passed to the function}funwithparam1 2 3 4 5 6 7 8 9  the  the

Note that the $ $ cannot get the tenth parameter, and the tenth parameter requires ${10}. When n>=10, you need to use ${n} to get the parameters.

Shell script: 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.