Custom functions in shell scripts

Source: Internet
Author: User

Functions are often used when writing programs, and general development tools have a rich library of functions. But sometimes you need to customize the function to meet our needs.

In Linux, the same is true for shell scripts, which sometimes use custom functions.

The simplest definition of a function is a set of command sets or statements that form an available block called a function.


1. Define the format of the function:

Function-name () {        Command1 ...        }

Or

#函数名前面也可以加上function关键字function  Function-name () {          Command1 ...        }

2. Function calls

The following is a script instance of a function:

    #!/bin/bash    function Hello () {          #声明函数      echo "hello!"            #函数的主体, Output "hello!"    }                          #函数结束    Hello                      #调用函数

3. Parameter passing
passing arguments to a function is like using a variable location in a script $1,$2,$3...$9
The following is an instance of a passing parameter:

  #!/bin/bash  function Hello () {      echo ' hello! The first parameter is ' $ '. "  }  Hello good
#该脚本执行的结果是: hello! The first parameter is ' good '.


4. function files
Save the file of the function, write a function file with the above example as follows:

  #!/bin/bash  function  Hello () {    echo "hello!"    Return 1  }
The Hellofunction file above is a function file that can be called from another script

  #!/bin/bash  . hellofunction      #调用函数文件, there is a space between the point and the hellofunction  Hello                #调用函数

5. Loading and deleting
to view loaded functions with Set
Cancel loading with unset function-name
Examples are as follows:

  #!/bin/bash  #hellof  . hellofunction  unset Hello  Hello            #因为已经取消载入, so there will be an error


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Custom functions in shell scripts

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.