[Shell scripts are refined into magic] The actual combat of shell script functions

foreword

insert image description here

The concept of function

In shell scripting, a function is a way to encapsulate a series of commands and logic for reuse.

Basic Syntax of Functions

In a shell script, you can use the following methods to define functions:

1. Use the keyword function:

function function_name { # function body }

This method is a more traditional function definition method, which is supported in most shell environments.

2. Use the function name and braces directly:

function_name { # function body }

This method is a relatively concise function definition method, without using the keyword function, just enclose the function name and curly braces directly.

Simple case of functions

Case 1, welcome function

# 使用关键字 function
function greet {
    
    
    echo "Hello, $1!"
}

# 使用直接定义函数名和大括号
bye() {
    
    
    echo "Goodbye, $1!"
}

$1is a positional variable.

Results of the:

./greeting.sh itlaoxin

Case 2: Shopping list


[root@laoxin21 test]# cat list.sh 
#!/bin/bash
list(){
    
    
        cat <<END
        1.apple
        2.banana
        3.pear
        4.orange
        
        please slect one that you like:
END
}
list
[root@laoxin21 test]# 
root@laoxin21 test]# bash list.sh 
        1.apple
        2.banana
        3.pear
        4.orange
        
        please slect one that you like:

Function parameter passing

Function parameters can be passed in the following forms:

  • positional parameters
  • command substitution
  • array parameter

1. Positional parameters

Positional Parameters: Use positional parameters to pass arguments to functions. Positional parameters are referenced by the numbers $1, $2, $3, etc., representing the first, second, third, and so on passed to the function, respectively

#!/bin/bash

greet() {
    
    
    echo "Hello, $1! Your age is $2."
}

greet "John" 25

2. Command Substitution

Command Substitution: Use the command substitution syntax $() or backticks ```` to pass the output of a command as an argument

#!/bin/bash

greet() {
    
    
    echo "Hello, $(whoami)!"
}

greet

Get the current user here $(whoami) , and echooutput the greeting by

3. Array parameters

Pass an array as an argument to a function

#!/bin/bash

print_array() {
    
    
    local arr=("$@")  # 将所有参数赋值给数组变量 arr
    for element in "${arr[@]}"; do
        echo "$element"
    done
}

my_array=("apple" "banana" "cherry")
print_array "${my_array[@]}"

print_arrayThe function takes an array parameter and uses a for loop to iterate through the array and output each element.
When using an array parameter, you need to use "${array[@]}" to pass all the elements of the array.

function return value

The return value of a general shell script uses return

1. Judging the execution result of the function

The execution of the function can be judged by the return value. As a general convention, a return value of 0 indicates that the function was executed successfully, and a non-zero value indicates that the function failed to execute or there was an error

#!/bin/bash

is_file_exists() {
    
    
    local file="$1"
    if [ -f "$file" ]; then
        return 0  # 文件存在,返回成功
    else
        return 1  # 文件不存在,返回失败
    fi
}

check_file() {
    
    
    local file_name="$1"
    is_file_exists "$file_name"
    if [ $? -eq 0 ]; then
        echo "File exists."
    else
        echo "File does not exist."
    fi
}

check_file "example.txt"

2. Assign the result of the function to a variable

Sometimes, a function needs to return some calculation results, status information, etc. By assigning the return value of a function to a variable, these results can be easily used later in the script.

#!/bin/bash

calculate_sum() {
    
    
    local num1=$1
    local num2=$2
    local sum=$((num1 + num2))
    return $sum
}

result=0
calculate_sum 5 10
result=$?
echo "Sum: $result"

calculate_sumA function calculates the sum of two numbers and returns the result via return.

3. As input to other functions

The return value of the function can be used as the input parameter of other functions to realize data transfer and cooperation between different functions

#!/bin/bash

get_full_name() {
    
    
    local first_name="$1"
    local last_name="$2"
    local full_name="$first_name $last_name"
    echo "$full_name"
}

greet() {
    
    
    local name="$1"
    echo "Hello, $name!"
}

first_name="John"
last_name="Doe"
full_name=$(get_full_name "$first_name" "$last_name")
greet "$full_name"

get_full_name The function accepts the first and last name of the first name as parameters and returns the full first name. Then, we assign the return value of the function to the variable full_name, and pass it as a parameter to the greet function to greet the full name.

Scope of shell script functions

Variables inside functions have local scope, meaning they are not visible outside the function. This is determined by the shell interpreter's scoping rules

1. Local variables

Local Variables: Variables declared inside a function are by default local variables, meaning they are only visible and used inside the function. Such variables cannot be accessed by code outside the function

#!/bin/bash

my_function() {
    
    
    local my_var="Hello"
    echo "Inside function: $my_var"
}

my_function
echo "Outside function: $my_var"  # 输出为空,无法访问函数内部的局部变量

Here: my_var is a local variable declared inside the function using the local keyword. It is only visible inside the function and cannot be accessed outside the function

2. Global variables

Global variables: Global variables can also be accessed and modified inside functions, and these variables are visible and available anywhere in the script. The scope of global variables extends beyond the scope of functions.

#!/bin/bash

global_var="Hello"  # 全局变量

my_function() {
    
    
    echo "Inside function: $global_var"
    global_var="World"  # 修改全局变量的值
}

my_function
echo "Outside function: $global_var"  # 输出 "World",函数内修改了全局变量

global_varis a global variable defined outside the function. The value of this global variable can be accessed and modified inside the function, and the modification of the global variable after the function is executed is visible outside the function.

There is no concept of block-level scope in shell scripts. Only local variables can be created inside the function, and variables declared elsewhere (such as if statements, for loops, etc.) still have global scope.

Summary: For situations where data needs to be shared between functions, use global variables or pass parameters. Using the local keyword can limit variables within the scope of the function, avoiding conflicts in the global namespace. Make sure to understand the scope and visibility of variables when using them in and out of functions to avoid unexpected behavior

Use functions to create custom commands

1. Create a shell script file, such as welcome.sh.

2. Define a function called welcome_message in the script file to output the welcome message.

   #!/bin/bash

   welcome_message() {
    
    
       echo "欢迎来到沐风晓月的csdn博客"
   }

3. Add executable permission to the script file.

   chmod +x welcome.sh

4. Place the script file in the system command search path.

   smv welcome.sh /usr/local/bin/

5. Add the following in the user's shell profile (such as .bashrc or .bash_profile) to invoke the custom command when the user logs in.

   welcome_message

In this way, every time a user logs in to the system, the welcome_message function will be automatically executed and the welcome message will be displayed.

Summarize

The above is all the actual content of the function in the shell script. If it is useful to you, please leave a message.

Guess you like

Origin blog.csdn.net/wisdom_futrue/article/details/131451403