Introduction to "shell" Linux shell functions

Source: Internet
Author: User

Linux Shell functions

Write in front: function, this word in just the beginning of the classmate looks very tall, in fact, the shell inside the function is very simple, function is actually to reduce the amount of code, so this space may be a little bit shorter.

Basic format of the function

The format of the function:
function functionname () {
function contents

}

Recommendation: Using the functionname () {} format directly, you do not need to add the function keyword in front of you, because the functions are used to reduce the amount of code, plus the keyword function does not work.

Note: Defined function must be called to take effect, only the definition is not any effect Oh!

Application Scenarios for functions

Assuming that there is a code that needs to be used multiple times, and we don't want to write duplicate code, then we can use the function, write the duplicated code in a function, and we can call the function directly if we need to call it.

Example:
Determines whether the file exists and returns a long string of characters if it does not exist. At this point we do two things, one is to knock over the repeated code.

[ -z a.txt ] && echo fdsfsdfsdfkslfjklsdjfklsdfjkl || echo fjklsfjlsjflkjlkjlkjafsd[ -z b.txt ] && echo fdsfsdfsdfkslfjklsdjfklsdfjkl || echo fjklsfjlsjflkjlkjlkjafsd[ -z c.txt ] && echo fdsfsdfsdfkslfjklsdjfklsdfjkl || echo fjklsfjlsjflkjlkjlkjafsd

The second is to write the duplicate value into a function and then call it.

创建函数andinfoandinfo(){        echo fdsfsdfsdfkslfjklsdjfklsdfjkl}创建函数orinfoorinfo(){        echo fjklsfjlsjflkjlkjlkjafsd}调用函数[ -z a.txt ] && andinfo || orinfo运行结果:[[email protected] scripts]# bash test1.sh fjklsfjlsjflkjlkjlkjafsd

Note: The invocation of a function in the shell does not require ' () ', the function name can be directly written, and the functions in the shell cannot be passed.

All rights reserved: Arppinging

Introduction to "shell" Linux shell functions

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.