Shell creation functions and reference functions

Source: Internet
Author: User

Typically, when you write a shell script, you'll find that the same piece of code is used in multiple places. It doesn't matter if it's just a small piece of code. But it's hard to rewrite chunks of code multiple times in a shell script. The bash shell supports user-defined functions, which solves this challenge. Talk about how the function is played in the shell today.

The bash Shell has a feature that allows us to do this. A function is a block of code that can be named and reused anywhere in the code. If we use this block of code in our script, we can simply use the Assigned function name (this process is called the call function). Next we'll talk about the creation and use of functions:

    • Create a function

      The bash shell script creation function has two forms:

    1. Takes the keyword function, followed by the name of the functions assigned to the code block:

      Function name {

      Commands

      }

      The Name property defines the unique name assigned to the function. You must assign a unique name to each function defined in the script.

      Commands is one or more bash shell commands that make up a function. When the function is called, the Bash Shell executes the command in the order in which it appears in the function, as in the normal script.

    2. Name () {commands}
    • Using functions in a script, you can specify the function name directly on the command line, just as you would with other shell commands:


    1. #!/bin/bash

    2. #using a function in a script


    3. function Func1 {

    4. echo "This was an example of a function"

    5. }


    6. Count=1

    7. While [$count-le 5]

    8. Do

    9. Func1

    10. count=$[$count + 1]

    11. Done


    12. echo "This is the end of the loop"

    13. Func1

    14. echo "Now this is the end of the script"

Shell creation functions and reference 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.