Description of function definition formats, function parameters, and Shell functions

Source: Internet
Author: User

Description of function definition formats, function parameters, and Shell functions

You can use shell to define a function, and then use it in a shell script. The Function Definition Format in shell is as follows:

[ function ] funname [()]{    action;    [return int;]}

Function fun () or fun () can be defined without any parameters. If the parameter is returned, the result of the last command is used as the return value. Return followed by the value n (0-255)

Return not included
demoFun(){    echo "This is my first function"}echo "-----func start-----"demoFunecho "-----func end-----"
Include return
funWithReturn(){    echo "add action"    echo "input first num: "    read aNum    echo "input second num: "    read anotherNum    echo "The two nums are $aNum and $anotherNum !"    return $(($aNum+$anotherNum))}funWithReturnecho "The total of two nums are $? "

The Return Value of the function is $? .

Note: All functions must be defined before use. This means that the function must be placed at the beginning of the script until the shell interpreter discovers it for the first time. Only the function name can be used to call a function.

Function Parameters

In Shell, parameters can be passed to a function. Inside the function body, get the parameter value in the form of $ n. For example, $1 indicates the first parameter, and $2 indicates the second parameter ......

funWithParam(){    echo "first : $1 "    echo "second : $2 "    echo "tenth : $10 "    echo "tenth : ${10} "    echo "eleventh : ${11} "    echo "total num : $# "    echo "the single string : $* "}funWithParam 1 2 3 4 5 6 7 8 9 34 73

Note: $10 cannot obtain the tenth parameter. $ {10} is required to obtain the tenth parameter }. When n> = 10, you need to use $ {n} to obtain the parameter.

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.