Shell Programming - Create function

1 basic script function

Function is a script block, you can give it a name and reused anywhere in your code. To use this code block in the script, as long as the function name is played on the line.

1.1 Creating function

There are two formats that can be used to create a function in bash shell script. The first format using the keyword function, followed by the function name assigned to the code block.

function name { 
    commands 
}

Two formats closer manner other programming languages ​​defined function.

name() {
     commands                                                   
}

1.2 using the function

$ cat test1 
#!/bin/bash 
# using a function in a script 
function func1 {    
   echo "This is 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" 
 
$ ./ test1
This is an example of a function 
This is an example of a function 
This is an example of a function 
This is an example of a function 
This is an example of a function 
This is the end of the loop     

Function definition must be in a position before a position to use this function.

 

2 return value

2.1 default exit status

By default, the exit status of a function is a function of the last command returns an exit status code. After the function executes, you can use a standard variable $? Exit status to determine the function.

$ cat test4 
#!/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: $?" 

$ ./ test4
testing the function: 
trying to display a non-existent file 
ls: badfile: No such file or directory 
The exit status is: 1 

Exit status function is 1. This is because the function of the last command did not run successfully. But you can not know the function of the other commands run successfully. See the examples below:

$ cat test4b
#!/bin/bash
# testing the exit status of a function
 func1() { 
    ls -l badfile   
     echo "This was a test of a bad command"
}  
echo "testing the function:" 
func1 
echo "The exit status is: $?"

$ ./ test4b
testing the function:
ls: badfile: No such file or directory
This was a test of a bad command
The exit status is: 0

This time, because the last statement echo function runs successfully, the exit status of the function is 0, although there is a command and not operating properly.

2.2 using the return command

return command to exit the function and return to a specific exit status. return an integer value command allows to define exit-state code, thus providing a simple way to exit status codes programmed functions.

$ cat test5
#!/bin/bash
# using the return command in a function
 function dbl {
   read -p "Enter a value: " value   
    echo "doubling the value"    
    return $[ $value * 2 ]
}  
dbl 
echo "The new value is $?" 

The value of variable $ value function will dbl user input doubled, with return command and returns the result. Script $? Variable shows the value.

But in this way the return value from the function, to be careful. Remember the following tips to avoid two problems:

  • To take the end of a function return value;
  • Exit status code must be from 0 to 255.

For example, we run it:

$ ./test5 
Enter a value: 200 
doubling the value 
The new value is
144

 

2.3 using the function output

This can use the following method to obtain any type of function output and save it to a variable:

result=$(dbl)

 

3 used in the function variable

Passing arguments to functions 3.1

You can use the standard function parameter environment variable to represent the command line parameter of the function to upload. For example, the function name will be defined in the variable $ 0, no parameters are a function of the command line by $ 1, $ 2, etc. defined. It can also be used to determine the special variable $ # number of parameters passed to the function.

When you specify a function in the script, parameters and functions must be on the same line, like this:

func1 $value1 10

Function can then be obtained by the environment variable parameter the parameter value. Here is an example using this method the value of the transfer function.

$ cat test6
#!/bin/bash
# passing parameters to a function
function addem {
   if [ $# -eq 0 ] || [ $# -gt 2 ]    
   then
      echo -1
   elif [ $# -eq 1 ]    
   then
      echo $[ $1 + $1 ]   
   else
      echo $[ $1 + $2 ]    
   be
}  
echo -n "Adding 10 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 

$ ./ test6
Adding 10 and 15: 25
Let's try adding just one number: 20
Now trying adding no numbers: -1
Finally, try adding three numbers: -1

Since the function parameter using a special environment variable as its parameter value, so it can not get the script from the command line parameter values ​​directly.

3.2 process variables in the function

Function uses two types of variables:

  • Global Variables
  • Local variables

By default, any variables that you define in the script are global variables. Variables may be defined outside of the function in the normal access functions:

$ cat test8
#!/bin/bash
# using a global variable to pass a value
 function dbl {
   value=$[ $value * 2 ]
}  
read -p "Enter a value: " value 
dbl 
echo "The new value is: $value"

$ ./ test8
Enter a value: 450
The new value is: 900

Any internal variables used by the function can be declared as local variables. To do this, just add a keyword in front of the local variable declaration on it.

$ cat test9
#!/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" 
be 

$ ./ test9
The result is 22 
temp is smaller

 

4 array variables and functions

4.1 array parameter passed to the function

If you try the array variable as a function parameter, the function will take the first value of the array variable. To solve this problem, you have to break down the value of the array variable into a single value, and then use these values as a function parameter. Inside the function, all parameters can be reassembled into a new variable . The following is a specific example:

$ cat test10
#!/bin/bash
# array variable to function test
 function testit {
     local newarray    
     newarray=($(echo "$@"))    
     echo "The new array value is: ${newarray[*]}"
}  
myarray=(1 2 3 4 5) 
echo "The original array is ${myarray[*]}" 
testit ${myarray[*]}

$ ./ test10
The original array is 1 2 3 4 5
The new array value is: 1 2 3 4 5

The script with $ myarray variable to hold all of the array elements, then they are placed on the command line functions. The function then reconstructed array variable in the command line parameter. Inside the function, the array can still be used like any other array of the same.

$ cat test11
#!/bin/bash
# adding values in an array 
function addarray {
    local sum=0    
    local newarray    
    newarray=($(echo "$@"))    
    for value in ${newarray[*]}    
    do 
          sum=$[ $sum + $value ]    
    done    
    echo $sum
}  
myarray=(1 2 3 4 5) 
echo "The original array is: ${myarray[*]}" 
result=$(addarray ${myarray[*]}) 
echo "The result is $result"

$ ./test11
The original array is: 1 2 3 4 5
The result is 15

addarray function through all the array elements, the accumulated them together. You can place as many values ​​in myarray array variable, addarry function will they all add up.

4.2 return an array from a function

Out of a function to return an array shell script variables are also in a similar way. Function is used to echo the statement in the correct order output a single array of values, and then the script them back into a new array variable.

#!/bin/bash
function test {
local array
local newarray
array=($(echo "$@"))
sum=0
for val in ${array[*]}
do
newarray[$sum]=$[$val*2]
sum=$[$sum+1]
done
Echo $ {newArray [* ]}
}
myarray=(1 2 3 4 5)
echo "array: ${myarray[*]}"
array=$(test ${myarray[*]})
echo ${array[*]}      

$ ./test12
array: 1 2 3 4 5 
2 4 6 8 10       

 

5 recursive function

$ cat test13
#!/bin/bash
# using recursion
 function factorial { 
    if [ $1 -eq 1 ]    
    then 
          echo 1    
    else
           local temp=$[ $1 - 1 ]       
           local result=$(factorial $temp)       
           echo $[ $result * $1 ]    
    be
}   
read -p "Enter value: " value 
result=$(factorial $value) 
echo "The factorial of $value is: $result"

$ ./ test13
Enter value: 5
The factorial of 5 is: 120

 

6 Create a library

Use omit some input function can work in the script, this is obvious. But if you happen to use the same piece of code in multiple scripts do? Obviously, once and for all define the same function in every script too much trouble. There is a way to solve this problem! bash shell allows you to create the library file, and then reference the library files in multiple scripts.

The first step is to create a public library file that contains the script required function

$ cat myfuncs
# my script functions
 function addem {
     echo $[ $1 + $2 ]
}  
function multem {
    echo $[ $1 * $2 ]
}  
function divem {
    if [ $2 -ne 0 ]    
    then 
          echo $[ $1 / $2 ]    
    else 
          echo -1    
    be 
}

The second step is to use the library file that contains myfuncs these functions in a script file. (Command with source)

The key is to use the library source command. command has a quick source of aliases, called the dot operator. To run myfuncs library files in shell scripts, simply add the following line:

. ./myfuncs

So, here's an example of creating a script with myfuncs library file:

$ cat test14
#!/bin/bash
# using functions defined in a library file
. ./myfuncs
 value1=10 
 value2=5 
 result1=$(addem $value1 $value2) 
 result2=$(multem $value1 $value2) 
 result3=$(divem $value1 $value2) 
 echo "The result of adding them is: $result1" 
 echo "The result of multiplying them is: $result2" 
 echo "The result of dividing them is: $result3"

$ ./ test14
The result of adding them is: 15
The result of multiplying them is: 50
The result of dividing them is: 2

 

7 using the function on the command line

7.1 create a function on the command line

Because the shell will interpret a command input by a user, a function can be defined directly on the command line. There are two ways.

Embodiment method is to use one-way function is defined.

$ function divem { echo $[ $1 / $2 ];  }
$ divem 100 5
20

When the command line defined functions, you must remember to add a semicolon after each command, so that the shell will be able to know where is the beginning and end of the command.

$ function divem { echo $[ $1 / $2 ];  }
$ divem 100 5
20

Another method is to use a multi-line mode is defined functions. When defining, bash shell uses the secondary prompt to prompt more commands. In this way, you do not put a semicolon at the end of each command, just press the Enter key on the line:

$ function multem {
> echo $[ $1 * $2 ]
> }
$ multem 2 5
10

Use curly braces at the end of the function, shell will know that you have finished defining the function.

7.2 in .bashrc defined function file

bash shell will find this file in your home directory at every startup, so the function is written in the .bashrc file inside, every time I start a new shell, that they will be reloaded from the shell.

1. Direct defined functions

 

$ cat .bashrc
# .bashrc
# Source global definitions
if [ -r /etc/bashrc ]; then
        . /etc/bashrc
             be                                                         
 
function addem {
   echo $[ $1 + $2 ]
 }                                                         
$ cat .bashrc
# .bashrc
# Source global definitions
if [ -r /etc/bashrc ]; then
        . /etc/bashrc
                                      

2. Read function file

$ cat .bashrc
# .bashrc
# Source global definitions                                 
if [ -r /etc/bashrc ]; then
        . /etc/bashrc
be
                                                                      
. /home/rich/libraries/myfuncs

 

Guess you like

Origin www.cnblogs.com/ericz2j/p/12045667.html