SoFunction
Updated on 2025-04-15

Detailed explanation of the use of functions and arrays in shell programming

shell function

Usage of functions

Shell functions can be used to store a series of instructions.

During the execution of the shell script, the function is placed in memory and does not need to be read from the hard disk each time the function is called, so it runs faster.

Functions are not necessary elements in shell programming, but using functions can better organize programs.

Turning some relatively independent code into function women can improve program readability and reusability and avoid writing a lot of duplicate code.

The method defined by the shell function is as follows:

[function]Function name() {
Command sequence
[return x]
}
  • The "function" keyword indicates that a function can be defined and can be omitted;
  • The "{" symbol represents the entry point for the function to execute the command. The symbol can be lined with the function name t or at the beginning of the sentence below the function name;
  • The "}" symbol indicates the end of the function body, and between the two braces {} is the function body;
  • The "command sequence" part can be any shell command or other functions can be called.
  • "return" means that the exit function returns an exit value. It determines whether the execution is successful by returning the value. You can also use exit to terminate the entire shell script.

Summarize two numbers

Use Shell script to implement the addition and sum of two numbers, which is done by defining functions.

The sum function receives two numbers input by the user through read, then performs addition operations, and finally outputs the sum of the two numbers by calling the function.

[root@localhost ~]# vim sum. sh
#!/bin/bash
sum() {
echo"Please enter the first number:"
read num1
if![[[$num1 =~ ^[0-9]+$ ]];
then
echo"The first number you entered is not a valid integer, please rerun the script and enter the correct number."
return 1
fi
echo"Please enter the second number:"
read num2echo"The first number you entered is not a valid integer, please rerun the script and enter the correct number."
return 1
fi
echo"Please enter the second number:"
read num2
if![[[ $num2 =~ ^[0-9]+$ ]]; 
then
echo"The second number entered is not a valid integer, please rerun the script and enter the correct number."
return 1
fi
result=$((num1 + num2))
echo"The sum of the two numbers is: $result"
sum
[root@localhost ~]# chmod +x 
[root@localhost ~]# ./
Please enter the first number:2
Please enter the second number:3
"The two numbers you enter are: 2 and 3."
"The sum of two numbers is: 5"

System resource monitoring and alarm function

This function will regularly monitor the system's CPU and memory usage. When the usage rate exceeds the set threshold, an alarm message will be sent. This is simply simulated as output to the console. In actual applications, it can be expanded to send emails, SMS, etc.

[root@localhost ~]# vim 
#!/bin/bash
#Function of sending alarm informationsend alert() {
local message=$1
echo "ALERT: $message"
}

monitor_system_resources() {
local cpu_threshold=$1
local mem_threshold=$2
local interval=$3

while true;
do
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print$2+$4}')
mem_usage=$(free | awk '/Mem/ {printf("%.2f",$3/$2 * 1((00)}.
if(( $(echo "$cpu_usage > $cpu_threshold" | bc -1) ));
then
   send_alert "CPU usage ($cpu_usage%)."
fi
if(( $(echo "$mem_usage > $mem_threshold" | bc-1) )); then
send_alert "Memory usage ($mem_usage%)."
fi
sleep "$interval"
done
}
monitor_system_resources 5 1 5
  • Parameter description: The function receives three parameters, namely the CPU usage threshold, the memory usage threshold, and the monitoring interval time (seconds).
  • Loop monitoring: Use whiletrue to loop continuously to monitor system resources. Get CPU and memory usage through top and free commands, and use the bc command to compare floating point numbers.
  • Alarm processing: When the usage rate exceeds the threshold, call the send_alert function to send alarm information.

Range of function variables

When writing scripts, sometimes the value of variables needs to be limited to the function, which can be implemented through the built-in command local. The use of variables inside the function can avoid the impact of the same name on the script results at the same time inside and outside the function.

[root@localhost ~]# vim fun_scope.sh
myfun ()
{
local i
i=8
echo $i
}
i=9
myfun
echo $i
[root@localhost ~]# chmod +x fun_scope.sh
[root@localhost ~]# ./fun_scope.sh
8
9

Function parameters

The usage of the function parameters is as follows.

Function name Parameter 1 Parameter 2 Parameter 3.

When using function parameters, the function name is in the front and the parameters are in the back, and the function name and the parameters are separated by spaces. There can be multiple parameters, and the parameters are expressed in the form of $1, $2, $3....

[root@localhost ~]# vim write_log.sh
#!/bin/bash
mydir="/data" outfile="${mydir}/"
[ -e "${mydir}" ] | mkdir -p ${mydir}
appendfile()
{
echo "$2" >> "$1"
}
appendfile ${outfile} "first line content."
appendfile ${outfile} "second line content."
[root@localhost ~]# chmod +x write_log.sh
[root@localhost ~]# ./write_log.sh
[root@localhost ~]# cat /data/
firstline content. second line content.

Recursive functions

Shell can also implement recursive functions, that is, it can call its own functions.

When writing shell scripts on Linux systems, you often need to recursively traverse the system's directories, list the files and directories in the directory, list them recursively layer by layer, and display these hierarchical relationships.

[root@localhost ~]# vim fun_recursion.sh
#!/bin/bash
traverse_directory() {
local dir=$1
for item in "$dir"/*; 
do
if [ -d "$item" ]; 
then
echo "Directory: $item"
traverse_directory "$item"
elif [ -f "$item" ];
 then
echo "File: $item"
fi
done
}

traverse_directory "."
[root@localhost ~]# chmod +x fun_recursion.sh
[root@localhost ~]# ./fun_recursion.sh

shell array

In shell scripts, arrays are a common data structure. Arrays in shells are different from Java, C, and Python. They only have dimensional arrays, but no two-dimensional arrays.

The size and limitations of array elements do not need to be defined in advance.

Shell arrays are represented by brackets (), elements are separated by spaces, and the subscript of elements is similar to most programming languages ​​to start from 0.

  • Method 1:

Array name =(value0value1value2...

  • Method 2:

Array name=([0]=value [1]=value [2]=value...)

  • Method 3:

List name="valuevalue1value2." Array name=($list name)

  • Method 4:

Array name[0]="value"Array name[1]="value"Array name[2]="value

Get the length of the array

To get the length of a normal array, you can use the same syntax effect as ${#array name[@]} or ${#array name[*]}.

[root@localhost ~]# arr_number=(1 2 3 4 5)
[root@localhost ~]# arr_length=${#arr_number[*]}
[root@localhost ~]# echo $arr_length
5
[root@localhost ~]# arr_length_1=${#arr_number[@] 
[root@localhost ~]# echo $arr_length_1
5

Read the specified value under a certain standard

In shell programming, you can read elements with specified subscripts in an array, or assign values ​​to array elements with specified subscripts.

[root@localhost ~]# arr_index2=${arr_number[2]}
[root@localhost ~]# echo $arr_index2
з

Array traversal

In Shell programming, array traversal refers to the process of accessing each element in an array in order and performing specific operations on these elements.

[root@localhost ~]# vim array_traverse.sh
#!/bin/bash
arr_number=(1 2 3 4 5)
for i in ${arr_number[@]}
do
echo $i
done
[root@localhost ~]# chmod +x array_traverse.sh
[root@localhost ~]# ./array_traverse.sh
1
2
3
4
5

Array slice

Array slicing is an operation that extracts a portion of continuous elements from an array and forms a new array. This operation has differences in different versions.

[root@localhost ~]# arr=(1 2 3 4 5)
[root@localhost ~]# echo ${arr[@]}
12345
[root@localhost ~]# echo ${arr[@]:0:2}
1 2
[root@localhost ~]# echo ${arr[@]:2:3}
3 4 5

Array replacement

[root@localhost ~]# arr=(1 2 3 4 5)
[root@localhost ~]# echo ${arr[@]/4/66}
1 2 3 66 5
[root@localhost ~]# echo ${arr[@]}
1 2 3 4 5
[root@localhost ~]# arr=(${arr[@]/4/66})
[root@localhost ~]# echo ${arr[@]}
1 2 3 66 5

Array Delete

  • Delete an array
[root@localhost ~]# arr=(1 2 3 4 5)
[root@localhost ~]# unset arr
  • Delete a single element
[root@localhost ~]# echo ${arr[*]}
[root@localhost ~]# arr=(1 2 3 4 5)
[root@localhost ~]# unset arr[2]
[root@localhost ~]# echo ${arr[*]}
1 2 4 5

Shell footstep debugging

In shell script development, we should pay attention to simplifying complex scripts, with clear ideas and segmented ideas.

In addition to echo, the bash shell also has corresponding parameters to debug scripts.

Debug with bash parameters, the syntax is:

sh [-nvx] script name

  • -n: The script will not be executed, and only query whether there is any problem with the script syntax. If there is no syntax problem, no content will be displayed. If there is any problem, an error will be reported.
  • -V: When executing a script, first output the content of the script to the screen and then execute the script. If there is an error, an error will be given.
  • -x: Output the executed script content to the screen, this is a very useful parameter for debugging.
[root@localhost ~
vim 
#!/bin/bash
set-x/
read-p"Please enter your score(0-100):"GRADE
if[$GRADE -ge 85 ] && [ $GRADE -le 100 ]
then
echo"$GRADEpoint!excellent"
elif [ $GRADE -ge 70 ] & [ $GRADE -1e 84 ]
then
echo"$GRADEpoint,qualified"else
echo"$GRADEpoint?不qualified"
fi
set +x

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.