Shell Scripting Learning notes--functions

Source: Internet
Author: User

I. DEFINITION of format

[Function] Function name ()

{

Command table

}

Ii. Method of Invocation

First define, then use, direct input function name, no parentheses required ()

Three, function parameter transfer method

Can be passed using positional parameters or variables

#!/bin/bash
# myfirst.sh
testfunction () {echo"$1,$2" #positional parameter passing parametersEcho"$val 1, $val 2" #Variable pass parameter}val1="test1"Val2="test2"testfunction1 2#calling FunctionsEcho"$1,$2" #positional parameters passed when printing a call script

Operation Result:

[[email protected] shell] # ./myfirst.sh a btest1,test2a,b

Iv. return

Normally, after the last command of a function executes, it exits the function, but you can also exit the function immediately with the return command

return [n]

Where the n value is the exit value when the Exit function is exited, but the N value defaults to the exit value when the last command exits

How far shell scripts can contain multiple functions

#!/bin/bash
# myfirst2.sh
TestFunction1 () {echo"$1,$2" return1Echo"$val 1, $val 2"}val1="test1"Val2="test2"TestFunction11 2#call the first functionEcho"$?" #print out the exit value of the function TestFunction1Echo"$1,$2"TestFunction2 () {echo"This is fun2" return2Echo"Test"}testfunction2#call a second functionEcho"$?" #print out the exit value of TestFunction2

Operation Result:

[[email protected] shell] # ./myfirst2.sh a b1,21a,bthis is fun22

Vi. Summary

Functions in the shell can assemble several commands together, call through a function name, and make repeated calls to enhance the reuse of the script.

Shell Scripting 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.