[Operation and maintenance] Function usage of linux shell programming

foreword

Using linux shell programming, it can be said that functions are very important content, and are often used when writing various shell scripts. This article will introduce the use of functions.

Classification of shell functions

  • System function
  • custom function

System function

System functions are functions that come with linux and can be used directly in shell writing. The following introduces several commonly used system functions

1, basename

Used to get the file name function, extract the file name according to the given file path;

grammar

basename [string / pathname] [suffix]  

  • The file name can be intercepted according to the specified string or path name, for example: according to the path "/root/shells/aa.txt", aa.txt can be intercepted;
  • suffix: remove the specified suffix name when intercepting;

Simple case

For example, in the current directory, there is a file called ch1.sh, the effect of using this command is as follows

 

Purpose of the command

  • After traversing a file directory, you can use this command to get the file name in the directory for subsequent processing;
  • After getting the file name, change the permissions of a matching file, etc.;

2、dirname

From the absolute path of the specified file, strips the filename and returns the remaining prefixed directory path

grammar

dirname file absolute path

Simple case

 

For more system functions, you can use: declare -f command to view

custom function

Shell programmers can use custom development functions to achieve code reuse and improve the encapsulation, readability and maintainability of modules;

grammar

# Function definition
[ function ] funname ()
{     command     [return return value]

}

# Call function
funname passing parameter 1 passing parameter 2 ...

Syntax Description

  • It can be defined with function fun() or directly with fun() without any parameters;
  • If the parameter is returned, it can be displayed and added: return return, if not added, the result of the last command will be used as the return value, and return is followed by the value n (0~255);

be careful

The function must be declared before calling the function. The shell script is run line by line. Only after the function is run first, the function can be used in the following actions;

Case 1: Function with no parameters and no return value

#!/bin/bash

hello(){

        echo "hello func"

}


hello

Call this script and observe the effect display

 

Case 2: No-parameter return-value function

#! /bin/bash

function sum(){

    echo "求两个数的和..."
    read -p "请输入第一个数字: " n1
    read -p "请输入第二个数字: " n2
    echo "两个数字分别为 $n1 和 $n2 "
    return $(($n1+$n2))
}

sum

echo "两个数字的和为: $? "  # 获取函数返回值

Run the above shell and observe the output

Case 3: Function with parameters

In the shell, you can pass arguments to a function when you call it. Inside the function body, the value of the parameter is obtained $nin the form of , for example, $1for the first parameter, $2for the second parameter...

Introduction of other parameters

parameter handling illustrate
$# The number of arguments passed to the script or function
$* Displays all parameters passed to the script as a single string
$$ The current process ID number of the script running
$! ID number of the last process running in the background
$@ Same as $*, but used with quotes, returning each argument in quotes.
$? Displays the exit status of the last command. 0 means no error, any other value means there is an error.

Case introduction

Write an example that outputs user input parameters using the parameters above

#!/bin/bash
funParam(){
    echo "第一个参数为 $1 !"
    echo "第二个参数为 $2 !"
    echo "第十个参数为 $10 !"
    echo "第十个参数为 ${10} !"
    echo "第十一个参数为 ${11} !"
    echo "参数总数有 $# 个!"
    echo "作为一个字符串输出所有参数 $* !"
}

funParam 1 2 3 4 5 6 7 8 9 10 11 12 15

 

Call the above script to observe the effect

Supplement: Difference between Shell program and function

Functions are similar to shell programs, except that:

  • Shell program (built-in command and external script file), the external script file is run in a subshell, which will open an independent process to run;
  • Shell functions run in the current Shell process;

Introduction to common cases of linux shell programming

In the following, combined with the previous introduction to the technical points of shell programming, we will list some commonly used scenarios that can be handled by shell programming.

1. Log (data) backup

For example, in a production environment, in order to keep the daily core log, you can use a timed task to schedule a shell script, and write a program in the script to back up log data

 

Reference example

#!/bin/bash  

tar  -zcvf  log-`date +%Y-%m-%d`.tar.gz log-`date +%Y-%m-%d` /var/log   
  

2. Monitor memory and disk capacity, and alarm when it is less than a given value

When the memory and disk capacity of the production server is insufficient, you can monitor and alarm by writing a shell

Reference example

#!/bin/bash  
  
  
# 提取根分区剩余空间  
disk_size=$(df / | awk '/\//{print $4}')  
  
# 提取内存剩余空间  
mem_size=$(free | awk '/Mem/{print $4}')  
while :  
do  
# 注意内存和磁盘提取的空间大小都是以 Kb 为单位  
if  [  $disk_size -le 512000 -a $mem_size -le 1024000  ]  
then  
    mail  ‐s  "Warning"  root  <<EOF  
  Insufficient resources,资源不足  
EOF  
fi  
done  

3. Check how many remote IPs are connected to the machine

Reference example

#!/bin/bash  
  
# 查看多少远程 IP 连接本机(不管是通过 ssh 还是 web 还是 ftp 都统计)   
# 使用 netstat ‐atn 可以查看本机所有连接的状态,‐a 查看所有,  
# -t仅显示 tcp 连接的信息,‐n 数字格式显示  
# Local Address(第四列是本机的 IP 和端口信息)  
# Foreign Address(第五列是远程主机的 IP 和端口信息)  
# 使用 awk 命令仅显示第 5 列数据,再显示第 1 列 IP 地址的信息  
# sort 可以按数字大小排序,最后使用 uniq 将多余重复的删除,并统计重复的次数  

netstat -atn  |  awk  '{print $5}'  | awk  '{print $1}' | sort -nr  |  uniq -c  

4. Write nginx startup script

In actual operation and maintenance, many middleware services, in order to facilitate the management of each middleware service, can be considered as various startup scripts for unified maintenance. The following takes nginx as an example (others, such as redis, zk, etc. can be similar references are written);

#!/bin/bash  
  
# 脚本编写完成后,放置在/etc/init.d/目录下,就可以被 Linux 系统自动识别到该脚本  
# 如果脚本名为/etc/init.d/nginx,则 service nginx start 就可以启动该服务  
# service nginx stop 就可以关闭服务  
# service nginx restart 可以重启服务  
# service nginx status 可以查看服务状态  
program=/usr/local/nginx/sbin/nginx  
pid=/usr/local/nginx/logs/nginx.pid  
start(){  
if [ -f $pid ];then  
  echo  "nginx 服务已经处于开启状态"  
else  
  $program  
fi  
stop(){  
if [ -! -f $pid ];then  
  echo "nginx 服务已经关闭"  
else  
  $program -s stop  
  echo "关闭服务 ok"  
fi  
}  
status(){  
if [ -f $pid ];then  
  echo "服务正在运行..."  
else  
  echo "服务已经关闭"  
fi  
}  
  
case $1 in  
start)  
  start;;  
stop)  
  stop;;  
restart)  
  stop  
  sleep 1  
  start;;  
status)  
  status;;  
*)  
  echo  "你输入的语法格式错误"  
esac  

Guess you like

Origin blog.csdn.net/congge_study/article/details/127358033