"Linux command line and Shell Scripting Encyclopedia" chapter 17th Create a function

Source: Internet
Author: User
Tags function definition

You can encapsulate the shell script code in a function so that it can be used more than once anywhere in the script.

17.1 Basic Scripting functions

Function: is a block of script code that can be named and reused anywhere in the code.

17.1.1 Creating a function

There are two types of formats: Name is the function name

1)

Function name

{

Commands

}

2) This is more akin to the C language style.

Name ()

{

Commands

}

17.1.2 using Functions

As with other shell commands, it is good to specify the function name in the row.

The function is used before the function definition and you receive an error message.

Function names are unique, and if you redefine the functions, the new ones overwrite the old ones and do not produce any error messages.

Example:

1 #!/bin/bash

2

3 function Fun

4 {

5 echo "Hahahaha, I am a function"

6}

7

8 Count=1

9 While [$count-LT 5]

Ten do

Fun

count=$[$count + 1]

Done

14

FUN2 # Error Fun2 not define

fun2 () # another way to declare a function

17 {

echo "I am Fun2, hahaha"

19}

Fun2

17.2 return value

When the function ends, an exit status code is returned, and there are 3 ways to generate an exit status code for the function.

17.2.1 Default Exit Status code

At the end of the function, with $? To determine the exit status code for the function.

Like what:

...

Fun

echo "Return code:$?"

...

If the last statement executed by the function fails, it returns a non-0, and finally succeeds (regardless of whether there is a previous failure) the return is 0.

17.2.2 using the return command

Bashshell uses the return command to exit the function and return a specific exit status code. Return allows you to specify an integer value to define the exit status code for the function.

Attention:

Immediately after the function is finished, the return value is taken

The exit status code must be 0–255. (greater than 255 will produce an error value)

17.2.3 using function output

You can save the function output ( any type of function output ) to the shell variable.

Syntax:result=$ (fun) This command assigns the output of the fun function to the $result variable

Example:

1 #!/bin/bash

2

3 function Fun

4 {

5 echo "Hahahaha, I am a function"

6 return 1

7}

8

9 Fun

Ten echo "Fun return $?"

11

function fun2

13 {

echo "This is Function fun2"

Read-p "Enter a value:" num

Echo $[$num * 2]

17}

18

#fun2 # If you add this sentence, you will be twice.

result=$ (fun2)

echo "fun2 return:$result"

This allows you to return floating-point numbers and strings.

17.3 using Variables in functions

Introduces some methods for dealing with internal and external variables of shell scripting functions

17.3.1 passing parameters to a function

Just like passing parameters to the script, you can use $#

Note that the script body is not the same as the "$" and "upload" function.

Example:

1 #!/bin/bash

2 function add

3 {

4 If [$#-eq 0] | | [$#-GT 2]

5 Then

6 echo-1

7 Elif [$#-eq 1]

8 Then

9 echo $[$ +]

Ten Else

Echo $[$ + $

Fi

13}

14

#ret =$ (ADD)

#ret =$ (add) # here's how to pass in Parameters

ret=$ (add 23 18)

If [$ret-eq-1]

Then

echo "Function add Error"

+ Else

echo "The value = $ret"

+ fi

24

if [$#-eq 2] # The number of arguments received by this script body

Then

echo "The value is $ (add $)" # Pass parameters of the script body to the function inside

-Else

echo "Input Error"

-Fi

17.3.2 working with variables in a function

The scope of the variable is more troublesome. The scope is the area where the variable is visible.

The variables defined in the function are scoped differently from the normal variables, meaning they are hidden from the rest of the script

Functions use two types of variables: global variables and local variables

1. Global variables

Refers to variables that are valid anywhere in the shell script.

When a global variable is defined in the Script body section, its value can be read within the function.

A global variable is defined within a function, and its value can be read in the body part of the script.

by default, any variable defined in the script is a global variable . Variables defined outside the function can be accessed within the function

This gives special attention to the use of variables. It's easy to change the variable.

2. Local Variables

Any variable that can be used inside a function is declared as a local variable.

Just add the local keyword before the variable declaration.

Local Temp

Example:

1 #!/bin/bash

2 function Fun

3 {

4 #temp =$[$value + 5] # If this is a global variable, the result will be an exception.

5 Local temp=$[$value + 5]

6 ret=$[$temp * 2]

7}

8

9 temp=4

Ten value=6

Fun

echo "Fun:ret = $ret"

If [$temp-gt $value]

Then

echo "Temp is big"

+ Else

echo "Value is big"

Fi

17.4 array variables and functions

The 6th chapter discusses the advanced usage of arrays to hold multiple values in a single variable

17.4.1 array parameters to functions

Review the usage of the array:

Definition Method 1: Initialize array array= (a b C)

Definition Method 2: Create a new array and add the primary color array[array]= elements

Definition Method 3: array= the command output as an array element ($ (command))

Array operations:

1) Get all elements: Echo ${array[*]}

2) Gets the nth element: Echo ${array[n]} n is an array subscript

3) add element: Array[3]=d

4) Delete element: unset array[n] n array subscript

1. The array cannot be used $arrayName when it is passed as a parameter.

It should be like this: Fun ${arrname[*]}

You can also add double quotes.

Example:

1 #!/bin/bash

2 function Testit

3 {

4 echo "The Param are:[email protected], param count:$#"

5 thisarray=$1

6 echo "The received array is:${thisarray[*]}"

7

8 for param in "[email protected]"

9 Do

echo "Param = $param"

One-Done

12}

13

myarray= (13 25 35 45 55 65)

echo "The original array is: ${myarray[*]}"

testit "${myarray[*]}"

Testit ${myarray[*]}

When there are double quotes, the function accepts a number of 1 arguments.

17.4.2 returning a parameter from a function

The function uses the Echo statement to output a single array value in the correct order, and the script then re-puts them into a new array variable.

Example:

1 #!/bin/bash

2 function Fun

3 {

4 Local Origarray

5 Local NewArray

6 Local count

7 Local I

8 origarray= ($ (echo "[email protected]"))

9 newarray= ($ (echo "[email protected]"))

Ten count=$[$#-1]

One for ((i = 0; I <= count; i++))

12 {

newarray[$i]=$[${origarray[$i]} * 2]

14}

Echo ${newarray[*]}

16}

17

Myarr= (1 2 3 4 5 6 7 8 9 10 11 12 13 14)

echo "Original arr is: ${myarr[*]}"

arg1=$ (Echo ${myarr[*]}) # here, define the array with the command output.

Ret= ($ (Fun $arg 1))

echo "New arr is: ${ret[*]}"

Use the ARG1 variable to pass the array value to the function fun. function to reorganize the array into a new array variable.

The script uses the output of the fun function to regenerate a new array variable

17.5 function recursion

The return value of the function is passed directly with Echo.

Example: Seeking factorial (note the example in the book p369 the middle part of the result * * is written incorrectly)

1 #!/bin/bash

2 function fun1

3 {

4 If [$1-eq 1]

5 Then

6 Echo 1

7 Else

8 local temp=$[$1-1]

9 Local ret=$ (fun1 $temp)

Echo $[$ret * $]

One fi

12}

13

Read-p "Enter Value:" Value

ret=$ (fun1 $value)

echo "ret = $ret"

17.6 Creating a library

Allows you to create a function library file, and then reference the library file in multiple scripts.

Suppose there is a script, Myfuncs. Some functions are defined inside:

1 function Addem

2 {

3 Echo $[$ + $

6?

5

6 function Multem

9 5

8 Echo $[$ * $]

9}

10

11

function Divem

13 {

If [$2-ne 0]

Then

Echo $[$/$ [$]

+ Else

Echo-1

Fi

20}

The shell function is valid only in the shell session in which it is defined.

If you run the Myfuncs shell script at the prompt of the shell command line interface, the shell creates a new shell and runs the script in it.

It will define the function for that new shell, but when you run another script that uses these functions, they are unusable.

How to use: The key to using the library is the source command, which executes the command in the current shell context. Instead of creating a new shell.

The source command has a shortcut alias, called a point operator.

How to use: ../myfuncs

This is assumed to be in the same directory, and if not, you need to specify the appropriate path name.

Instance:

1 #!/bin/bash

2 ../myfuncs

3

4 value1=10

5 value2=5

6 echo "ADD Test ret = $ (addem $value 1 $value 2)"

7 echo "Mult Test ret = $ (multem $value 1 $value 2)"

8 echo "Div Test ret = $ (divem $value 1 $value 2)"

17.7 using the function 17.7.1 on the command line to create a function on the command line

Functions can be used directly at the prompt of the command line interface.

Use it like an order. And once the function is defined, it can be used throughout the system, without the need to pipe the PATH environment variable.

Example:

Attention:

1) A semicolon must be appended to each command to know where the command ends and ends

2) cannot create functions that are the same as built-in commands or other commands, or overwrite the original command

17.7.2 defining functions in. bashrc files

The obvious disadvantage of defining shell functions on the command line is that the function disappears when you exit the shell.

Workaround: define the function in a specific location, which is loaded by the shell each time a new shell is started.

The best place to be . BASHRC. The bash shell looks for this file in the home directory each time it is started .

1. Directly define Functions

Add it directly behind the. BASHRC

function Addem

{

Echo $[$ [+ $]

}

This function is used anywhere on the system.

2. Reading function files

You can use the source command to add a function from the library file to the. BASHRC

Add it directly behind the. BASHRC

. /home/xcy/myfuncs

So you can use the function inside the Myfuncs.

17.8 example

This section describes the GNU Shtool Shell script function library. The Shtool library provides a few simple shell scripting libraries. It's not written here for the time being.

"Linux command line and Shell Scripting Encyclopedia" chapter 17th Create a function

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.