function of Shell syntax

Source: Internet
Author: User

A function is a block of script code that is given a name and can be reused anywhere in the code. Whenever you need to use such a block of code in your script, simply reference the name of the function that the block is assigned to.

Create a function

Format

function name {

  Commands

}

The Name property defines a unique name for the function. There will be a space after name.

name () {

  Commands

}

Example

#!/bin/bash
# using a function in a script

function Func1 {
echo "This was an example of a function"
}

Count=1
While [$count-le 5]
Do
Func1
count=$[$count + 1]
Done
echo "This is the end of the loop"
Func1
echo "Now this is the end of the script"

Note: If you use a function before the function definition, you get an error message.

If the function is redefined, the new definition supersedes the original definition of the function.

function return value

Default Exit Status

By default, the exit state of a function is the exit state returned by the last command of the function.

Example

#!/bin/bash
# Testing the exit status of a function

Func1 () {
echo "Trying to display a non-existent file"
Ls-l Badfile
}

echo "Testing the function:"
Func1
echo "The exit status is: $?"

Use the return command

The return command can use a single integer value to define the function exit state, providing a simple way to programmatically set a function to exit the state.

Example

#!/bin/bash
# using the return command in a function

function DB1 {
Read-p "Enter A value:" Value
echo "Doubling the value"
Return $[$value * 2]
}

Db1
echo "The new value is $?"

Note: Remember to extract the return value as soon as the function is complete

Remember that the value range for exit status is 0~255

Using function output

Just as the command output can be captured and placed in a shell variable, the output of the function can also be captured and placed in the shell variable.

Example

#!/bin/bash
# using the Echo to return a value

function DB1 {
Read-p "Enter A value:" Value
echo $[($value) * 2]
}

result= ' DB1 '
echo "The new value is $result"

Passing parameters to a function

A function can use a standard parameter environment variable to represent the arguments that the command line passes to the function.

The function name is defined in the variable $ $, and the other parameters of the function command line use the variable $, $ ..., the private variable $ #可以用来确定传递给函数的参数数目.

Example

#!/bin/bash
# passing parameters to a function

function Addem {
If [$#-eq 0] | | [$#-GT 2]
Then
Echo-1
elif [$#-eq 1]
Then
Echo $[$ +]
Else
Echo $[$ [+ $]
Fi
}

Echo-n "Adding and 15:"
Value= ' Addem 10 15 '
Echo $value
Echo-n "Let ' s try adding just one number:"
Value= ' Addem 10 '
Echo $value
Echo-n "Now trying adding no numbers:"
Value= ' Addem '
Echo $value
Echo-n "Finally, try adding three numbers:"
Value= ' Addem 10 15 20 '
Echo $value

Because the function uses a dedicated parameter environment variable for its own parameter value, the function cannot access the script parameter values directly from the script command line. If you want to use these values in a function, you must pass the data manually when the function is called.

Example

#!/bin/bash
# trying to access script parameters inside a function

function Func7 {
Echo $[$ * $]
}

If [$#-eq 2]
Then
Value= 'func7'
echo "The result is $value"
Else
echo "Usage:badtest1 a B"
Fi

Using Variables in functions

Global variables are variables that are valid everywhere in a shell script.

Example

#!/bin/bash
# using a global variable to pass a value

function DB1 {
value=$[$value * 2]
}

Read-p "Enter A value:" Value
Db1
echo "The new value is: $value"

A local variable is a variable that is used inside a function and is prefixed with the local keyword before the variable declaration.

If the script has a variable with the same name outside the function, the shell will be able to partition the two variables.

Example

#!/bin/bash
# demonstrating the local keyword

function Func1 {
Local temp=$[$value + 5]
result=$[$temp * 2]
}

Temp=4
Value=6

Func1
echo "The result is $result"
If [$temp-gt $value]
Then
echo "Temp is larger"
Else
echo "TEMP is smaller"
Fi

Passing an array to a function

If you attempt to use an array variable as a function parameter, the function extracts only the first value of the array variable.

Example

#!/bin/sh
# array variable to function test

function Testit {
Local NewArray
newarray= ("[email protected]")
echo "The new array value is: ${newarray[*]}"
}

Myarray= (1 2 3 4 5)
echo "The original array is ${myarray[*]}"
Testit ${myarray[*]}

You must split the array variables into individual elements, and then use the values of those elements as function arguments.

Using arrays inside functions

Example

#!/bin/bash
# Adding values in an array

function AddArray {
Local sum=0
Local NewArray
newarray= (' echo ' [email protected] ')
For value in ${newarray[*]}
Do
sum=$[$sum + $value]
Done
Echo $sum
}

Myarray= (1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
Arg1= ' echo ${myarray[*]} '
result= ' AddArray $arg 1 '
echo "The result is $result"

Returning an array from a function

Example

#!/bin/sh
# returning an array value

function Arraydblr {
Local Origarray
Local NewArray
Local elements
Local I
origarray= (' echo ' [email protected] ')
newarray= (' echo ' [email protected] ')
elements=$[$#-1]
for ((i=0; i<=elements; i++)
{
newarray[$i]=$[${origarray[$i]} * 2]
}
Echo ${newarray[*]}
}

Myarray= (1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
Arg1= ' echo ${myarray[*]} '
result= (' Arraydblr $arg 1 ')
echo "The new array is: ${result[*]}"

function recursion

Example

#!/bin/sh
# using recursion

function factorial {
If [$1-eq 1]
Then
Echo 1
Else
Local temp=$[$1-1]
Local result= ' factorial $temp '
Echo $[$ * $result]
Fi
}

Read-p "Enter Value:" Value
result= ' factorial $value '
echo "The factorial of $value is: $result"

Create a library

Create a library file of functions that can reference the library file in different scripts.

The difficulty lies in the scope of the Shell function. As with environment variables, shell functions are only valid in the shell session where they are defined. If you run the library file from the shell command line interface, the shell opens a new shell and runs the script in the new shell, but the library function is not available when you try to run another script that calls these library functions.

The key to using the library is the source command. The source command executes the command in the current shell environment, rather than creating a new shell to execute the command. Use the source command to run the library file script inside the shell script.

Source has a short alias, called The dot Operator (.).

Example

#!/bin/bash
# using Functions defiend in a library file

. ./myfuncs

value1=10
Value2=5
Result1= ' Addem $value 1 $value 2 '
Result2= ' Multem $value 1 $value 2 '
Result3= ' Divem $value 1 $value 2 '

echo "The result of adding them is: $result 1"
echo "The result of multiplying them is: $result 2"
echo "The result of dividing them is: $result 3"

Using parameters in the command line

$ function Divem {echo $[$ + $];}

$ DIVEM 100 5

Defining functions in the. bashrc file

Place the function definition where the shell can be re-loaded each time it starts,. BASHRC.

You can define a function directly, or provide a function file.

function of Shell syntax

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.