Shell script function application and array introduction, size sorting, script debugging and array slicing

1. Shell function application

  • If there are some command sequences that need to be called and executed repeatedly, if the same command is repeatedly written every time, the amount of code will be relatively large. Shell function can write the command sequence together in a format so that it can be re-read and used.
  • In the Shell format, function is optional, which means the function of the function, this can be omitted; add a () after the function name, there is no content inside. The executed command is placed in {}. The function of return x is to give a return value when the command is executed. Return is followed by the value n (0-255), which can be omitted.
function 函数名(){
    
    
  命令序列
  [return x]
  }

1.1 Methods of calling functions

  • Function name [parameter 1 ($1)] [parameter 2 ($2)]
  • In Shell, you can pass parameters to a function when calling it. Inside the function body, the value of the parameter is obtained in the form of $n, for example, $1 means the first parameter, $2 means the second parameter...
  • 10 Cannot get the tenth parameter, get the tenth parameter, 10 can't get the tenth parameter, get the tenth parameter, 10 can't get the tenth parameter, get the tenth parameter, {10}. When n>=10, you need to use ${n} to get the parameters.

#! /bin/bash
# 求和函数体
function  sum(){
    
    
# 命令序列
  read -p "请输入第一个整数: "  num1
  read -p "请输入第二个整数: "  num2
        SUM=$[$num1+$num2]
        #echo 返回的是处理结果值
        echo $SUM
        # return返回给系统一个值
        return 100
}
sum  ## 表示调用函数 这次不需要添加参数,所以后面没有跟
echo $? ## 输出 return返回的值

1.2 Put the function in the environment variable and call the function directly

  • step
函数放到环境变量直接调用  
~/.bashrc    ## 用户环境变量
/etc/profile## 系统环境变量
~/.bash_profile: 每个用户都可使用该文件输入专用于自己使用的shell信息,当用户登录时,该文件仅仅执行一次!默认情况下,他设置一些环境变量,执行用户的.bashrc文件.
~/.bashrc: 该文件包含专用于你的bash shell的bash信息,当登录时以及每次打开新的shell时,该该文件被读取.
/etc/profile中设定的变量(全局)的可以作用于任何用户,而~/.bashrc等中设定的变量(局部)只能继承/etc/profile中的变量,他们是"父子"关系.
source   ~/.bashrc  ## 重新加载生效
[root@promote ~]# vim ~/.bashrc 
### 在末尾添加
function  sum(){
    
    
# 命令序列
  read -p "请输入第一个整数: "  num1
  read -p "请输入第二个整数: "  num2
        SUM=$[$num1+$num2]
        #echo 返回的是处理结果值
       echo "输入的两个数和为:$SUM"
        # return返回的是状态码
        return 100
}
[root@promote ~]# source   ~/.bashrc
-bash: /root: 是一个目录
[root@promote ~]# sum  ## 直接调用函数sum  但是切换用户后就不能调用,因为刚刚修改的文件时用户环境变量
请输入第一个整数: 10
请输入第二个整数: 20
输入的两个数和为:30    

1.3 Recursive function

  • Call your own function, that is, call yourself.

1.3.1 View all files and subdirectories in the /var/log directory.

#! /bin/bash
function list(){
    
    
 for f in `ls $1`     ## 遍历/var/log下的文件和目录
do
if [ -d "$1/$f" ]       ## 如果 为目录
then
 echo "$2$f"   ## 输出路径  前面空一个空格
 list  "$1/$f"  " $2"      ## 继续调用list函数  遍历子目录下的文件和目录
 else          ## 如果不是目录
       echo "$2$f"    ## 则输出文件路径,空一个空格
fi
done
}
list "/var/log" ""

Two, Shell array

  • Array: often put a collection of the same data type, called an array, often used in conjunction with loops.
  • Application scenarios: Get array length, get element length, traverse elements, element slice, element replacement, element deletion.
 数组名称  arr=(11,22,33,44)        arr是数组名称
 数组元素(11 22 等都是其中一个元素)
 数组的长度(元素的个数,从1开始数 上面的数组长度为4  数组长度获取 echo  $#{num[*]})
 数组下标:调用数组中某一个元素   (数组下标  0  1   2   3    索引,基本都是从0开始)

2.1 How to define an array

方法一:数组名=(value 0  value1   value2)        ## 调用方法  echo  ${num[*]}
方法二:数组名=[0]=55 [1]=66 [2]=77 [3]=88)  调用方法 echo ${num[@]}或者echo ${num[*]}
方法三:数组名= “value 0  value1   value2”  list="11 12 13 14"   num=($list)  echo ${num[*]}  ## 先定义列表,再赋值给数组
方法四:(主要用来做替换的)
数组名[0]="value"
数组名[1]="value"
数组名[2]="value"

2.2 Method of calling array

echo  ${num[*]}  ## 但凡看到中括号,用的就是数组

2.3 Array length acquisition

echo  $#{num[*]}

2.4 Array traversal

for v  in    echo  ${num[*]}
>do
>  echo $v

2.5 Array script sentence example

2.5.1 Arrange the numbers in the array from small to large-bubble method

#!/bin/bash
a=(55 66 11 33 99)
k=${#a[*]}
for ((i=1;i<=$k;i++))
 do
    temp=1
   for ((j=1;j<=$[$k-$i];j++))
        do
             if [ ${a[$j]} -lt  ${a[$j-1]} ]
           then
            tem=${a[$j]}
            a[$j]=${a[$j-1]}
            a[$j-1]=$tem
            temp=0
           fi
     done
      if [ $temp -eq 1 ]
       then
         break
       fi

done
echo ${a[*]}
~          

2.5.2 Arrange the numbers in the array from small to large-insertion method

#!/bin/bash
a=(98 23 45 67 7 8 99 100)
k=${#a[*]}
for ((i=1;i<$k-1;i++))
 do
   if [ ${a[$i]} -lt ${a[$i-1]} ]
   then
       temp=${a[$i]}
      for ((j=$i-1;j>=0;j--))
      do
        if [ ${a[$j]} -gt $temp ]
       then
            a[$j+1]=${a[$j]}
        else
           break
        fi
      done
       a[$j+1]=$temp
   fi
done
echo ${a[*]}                                                                                                                                      
~                                                                                                                                   
~                

2.5.3 Arrange the numbers in the array from largest to smallest

#!/bin/bash
a=(98 23 45 67 7 8 99)
k=${#a[*]}
for (( i=1;i<$k;i++ ))
 do
   if [ ${a[$i]} -gt ${a[$i-1]} ]
     then
      let temp=${a[$i]}
        for (( j=$i-1; j>=0;j--))
          do
           if [ ${a[j]} -lt $temp ]
           then
           let a[$j+1]=a[$j]
           else
            break
           fi
           done
        let a[$j+1]=$temp
fi
done
echo ${a[*]}
~                                                                                                                                   
~                

2.5.3 Talk about removing all numbers less than 60 in the array

!/bin/bash
a=(10 60 70 80 90 10 50 55 49 88 35 89 56 77)
i=0
k=${#a[*]}
for ((i=0;i<$k;i++))
do
  if [ ${a[$i]} -lt 60 ];then
        unset a[$i]
   fi
done
echo ${a[*]}
~          

Three, script debugging

3.1 bash command

  • Basic format
    sh [-nvx] script name
-n   不执行,仅检查语法有无问题,语法无误便不会显示任何内容
-x    将执行的脚本内容输出到屏幕上
-v    在执行脚本时,先将脚本的内容输出到屏幕上然后执行脚本,如果有错误,也会给出错误提示

3.2 set command

set -x close adjustment## Enter
set +x in the program to open the adjustment mode

Four, array slice

4.1 Array Slicing

 数组切片   ${数组名[@]:起始位置:长度}或者${
    
    数组名[*]:起始位置:长度  
(起始位置(索引下标 从0开始,为数组长度   包括开始那个数)
[root@localhost opt]# a=(1 2 3 4 5 6 7 8 9)
[root@localhost opt]# echo ${a[@]:0:5}
1 2 3 4 5

4.2 Array replacement

${数组名[@]/查找字符/替换字符}或者${
    
    数组名[*]/查找字符/替换字符    
(不会更改原有数组当中的值,只在缓存的副本中修改,原有的不会变)
[root@localhost opt]# a=(1 2 3 4 5 6 7 8 9)
[root@localhost opt]# echo ${a[@]/1/5}
5 2 3 4 5 6 7 8 9
[root@localhost opt]# echo ${a[@]}
1 2 3 4 5 6 7 8 9
  • To modify the array, rewrite or overwrite
 [root@localhost opt]#  a=(${a[@]/4/66})
[root@localhost opt]# echo ${a[@]}
1 2 3 66 5 6 7 8 9

4.3 Delete

  • Delete a single element in the array
    unset a[3]
[root@localhost opt]# echo ${a[@]}
1 2 3 66 5 6 7 8 9
[root@localhost opt]# unset a[3]
[root@localhost opt]# echo ${a[@]}
1 2 3 5 6 7 8 9

  • Delete the entire array
删除整个数组:   unset  a
[root@localhost opt]# unset a
[root@localhost opt]# echo ${a[@]}


Guess you like

Origin blog.csdn.net/weixin_47219725/article/details/107532314