Shell function definition and application

Source: Internet
Author: User
Tags function definition variable scope

1. Function Introduction

Functional function is a block of statements consisting of several shell commands for code reuse and modular programming.

It is similar to the shell program, but it is not a separate process, it cannot run independently, but is part of the shell program.

When used, Source/path fo function_file in the shell, the function will remain until the user exits, or you can use unset function_name, undo function

A function is similar to a shell program, except that:

Shell program runs in child shell

The Shell function runs in the current shell. So in the current shell, the function can modify the variables in the shell

2. function return value

The function has two return values:

The return value of the function's execution result:

(1) Output with the Echo or printf command

(2) output of the call command in the function body

Exit status code for the function:

(1) The default depends on the exit status code of the last command executed in the function

(2) Custom exit status code, in the form of:

Return returned from the function, with the last state command to determine the return value

return 0 returns without error.

Return 1-255 has error returned

3. Define and use functions in scripts

function definition:

Functions must be defined before they are used, so the function definition should be placed in the beginning of the script,

Until the shell finds it for the first time before it can be used

The calling function uses only its name of functions.

Example:

$cat func1

#!/bin/bash

# func1

Hello ()

{

echo "Hello there today ' s date is ' date +%f '"

}

echo "Now going to the function hello"

Hello

echo "Back from the function

Using functions:

You can store frequently used functions in a function file and then load the function file into the shell.

The file name can be arbitrarily selected, but it is best to have some kind of connection to the related task. Example: Functions.main

Once the function file is loaded into the shell, the function can be called from the command line or script.

You can use the SET command to view all defined functions whose output list includes all functions that have been loaded into the shell.

To change a function, first remove the function from the shell with the unset command. After the change is complete, reload the file

To create a function file:

Example of a function file:

$cat Functions.main

#!/bin/bash

#functions. Main

Findit ()

{

If [$#-lt 1]; Then

echo "Usage:findit file"

Return 1

Fi

Find/-name $1–print

}

Load function:

Once the function file has been created, load it into the shell.

Locate the function file and load the shell into the format:

. FileName or source filename

Note: This is < point > < space > < file name >

The file name here takes the correct path

Example: The function in the previous example, you can use the following command:

$ . Functions.main

Execute function:

To execute a function, simply type in the name of the letter:

Example:

$findit groups

/usr/bin/groups

/usr/local/backups/groups.bak

To delete a function:

Now make some changes to the function. First remove the function so that it is not available to the shell. Use the unset command to complete this function.

The command format is:

unset function_name

Instance:

$unset Findit

Type the set command again, and the function will no longer display


Function parameters:

The function can accept parameters:

Pass parameters to the function: When the function is called, it is separated by a white space after the function name

Given a list of parameters, for example "TestFunc arg1 arg2 ..."

In the function body, you can use $, $, ... These parameters are called;

You can use [email protected], $*, $ #等特殊变量

4. Function variables

Variable scope:

Environment variables: current shell and child shell are valid

Local variable: Only valid in the current shell process, the dedicated child shell process is started for script execution, so the local variable is scoped to the current shell script

Program files, including functions in the script.

Local variables: The life cycle of a function; The variable is automatically destroyed at the end of the function

Note: If there are local variables in the function, use local variables if their names are the same as local variables.

Methods for defining local variables in a function

Local Name=value

To avoid conflicts with variables or command names already defined in the shell, use local variables whenever possible


5. Function recursion

function recursion:

function calls itself directly or indirectly

(Note the number of recursive layers)

Recursive instances:

Factorial is an operational symbol invented by Kiston Kaman in 1808, which is the factorial of a positive integer in mathematical terms (factorial) is

All the product of a positive integer less than and equal to the number, and a factorial of 0 is 1. The factorial writing n! of the natural number N.

N!=1x2x3x...xn.

Factorial can also be defined recursively: 0!=1, n!= (n-1)!xn.

N!=n (n-1) (n-2) ... 1

N (n-1)! = N (n-1) (n-2)

Example: fact.sh

#!/bin/bash

#

Fact () {

If [$1-eq 0-o $1-eq 1]; Then

Echo 1

Else

echo $[$1*$ (fact $[$1-1])

Fi

}

Fact 5


Shell function definition and application

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.