The use of shell function

Time:2021-6-15

The definition of function

  • Function keyword, you don’t need brackets
    function  func_name {
    command 1
    command 2
    ...
    command N
    }
  • There is no function keyword, parentheses are required
    func_name() {
    command 1
    command 2
    ...
    command N
    }

How functions are used (called)

  • It can be called directly by using the function name without brackets. You can think of it as a command in a shell
    $ func_name [arg1 arg2 ... argN]
  • Function internal can use $1 $2… $n directly
    func_name() {
    echo $1
    echo $2
    }

    The return value of the function

  • Return the return value can only return an integer from 1 to 255, which is usually only used for other places to call to get the status, so it usually only returns 0 or 1, and non-zero means failure
  • Echo can return any string result, usually used to return data, such as a string value or list value

    Global variable and local variable

  • global variable

    • Without special declaration, all variables in shell are global variables
    • Tips: careful use of global variables in large script programs

    vim test_local1.sh

    #!/bin/bash
    var1="Hello World"
    function test {
    var2=120
    }
    [[email protected] shell]$ sh test_local.sh 
    Hello World
                        //Null because the test function did not execute
    [[email protected] shell]$

    vim test_local2.sh

#!/bin/bash
var1="Hello World"
function test {
    var2=120
}
echo $var1
echo $var2
Test // var2 becomes a global variable
echo $var1
echo $var2
function test2 {
  echo $var1
  echo $var2

}
test2

Running results

[[email protected] shell]$ sh test_local2.sh 
Hello World

Hello World
120
Hello World
120
[[email protected] shell]$
  • local variable
    • When defining variables, use the local keyword
    • If there is a variable with the same name inside and outside the function, the function will cover the external variable inside

vim test_local3.sh

#!/bin/bash
var1="Hello World"
function test {
    Local var2 = 120 // only valid inside the function
}
test 
echo $var1
echo $var2

results of enforcement

[[email protected] shell]$ sh test_local3.sh 
Hello World

[[email protected] shell]$

function library

Why should we define the function library and encapsulate some common functions to facilitate the call of other places

  • The frequently used repetitive code is encapsulated into function files
  • Generally, it is not executed directly, but called by other scripts

This work adoptsCC agreementReprint must indicate the author and the link of this article