Table of Contents
需求:
需求分析
注意事项
Home Computer Tutorials Computer Knowledge Linux script study notes, log function usage tips

Linux script study notes, log function usage tips

Feb 19, 2024 pm 05:36 PM
Script shell shell script log

Linux script study notes, log function usage tips

本文描述了一个用于记录shell脚本执行日志的日志脚本函数。在进行shell脚本开发时,经常需要监控系统数据。为了方便查看,我们可以将脚本运行情况记录为日志文件,避免需要一直在命令控制台上监视。

需求:

1、可以记录脚本的运行情况;

2、可以记录时间;

3、可以在输入log达到一定的行数后对以前的log进行删减,防止log文件无限累积;

需求分析

这个简单需求可以通过编写一个函数来实现,该函数能够将脚本中的日志信息输出到同名的log文件中,方便开发人员日后查阅分析脚本运行情况。可以根据个人喜好和技术能力选择合适的方式来实现这一功能。

需求实现:

经过三天三夜的奋战,写出了以下脚本函数:

#!/bin/bash
log(){
#log文件名
local fileName="./$(basename $0 .sh).log"
#log文件最大存储log行数(此处设置最大存储log行数是100行)
local fileMaxLen=100
#超过log最大存储行数后需要从顶部开始删除的行数(此处设置的是删除第1到第10行的数据)
local fileDeleteLen=10
if test $fileName
then
#记录log
echo "[`date +%y/%m/%d-%H:%M:%S`]:$*" >> $fileName
#获取log文件实际行数
loglen=`grep -c "" $fileName`

if [ $loglen -gt $fileMaxLen ]
then
#从顶部开始删除对应行数的log
sed -i '1,'$fileDeleteLen'd' $fileName
fi
else
echo "[`date +%y/%m/%d-%H:%M:%S`]:$*" > $fileName
fi
}


#test
testdate=100
#记录输出的字符串
log "test string"
#记录输出的数据
log "testdate=$testdate"
#记录输出的运算
log $[1+2]
#记录命令输出的信息
log $(printf "this is cmd test %sn" "this is cmd output string")
Copy after login

其中主要的就是log()这个脚本函数,’#test’之后的都是对这个函数的测试;

实现功能:

1、可以快速的加入到当前的脚本中,加入方法:将log()函数复制到在当前的脚本的最前面,然后后面对需要记录的日志直接调用log就可以;

2、加入需要记录日志的脚本后,执行脚本时,会在执行脚本同目录下生成一个同名的.log文件,里面就是执行脚本的日志输出;

3、可以记录脚本运行时间及可对字符串、数据变量、及命令输出的信息进行记录;

4、可以对log文件的行数进行判断,当行数超过最大限制行数后,会从log文件顶部开始删除以前的log记录。

使用示例:

比如要实时查看CPU的温度,就有如下脚本(cputemp.sh):

#!/bin/bash
echo CPU temperature is $[`cat /sys/class/thermal/thermal_zone0/temp`/1000]
Copy after login

在命令控制台使用watch命令可以做到实时监控

watch -n 1 ./cputemp.sh
Copy after login
Copy after login

执行结果如下:

这样是可以实现实时查看,可是为了数据的延续性,所以我加上了log脚本函数,修改了cputemp.sh脚本,如下:

#!/bin/bash
log(){
#log文件名
local fileName="./$(basename $0 .sh).log"
#log文件最大存储log行数(此处设置最大存储log行数是100行)
local fileMaxLen=100
#超过log最大存储行数后需要从顶部开始删除的行数(此处设置的是删除第1到第10行的数据)
local fileDeleteLen=10
if test $fileName
then
#记录log
echo "[`date +%y/%m/%d-%H:%M:%S`]:$*" >> $fileName
#获取log文件实际行数
loglen=`grep -c "" $fileName`

if [ $loglen -gt $fileMaxLen ]
then
#从顶部开始删除对应行数的log
sed -i '1,'$fileDeleteLen'd' $fileName
fi
else
echo "[`date +%y/%m/%d-%H:%M:%S`]:$*" > $fileName
fi
}




echo CPU temperature is $[`cat /sys/class/thermal/thermal_zone0/temp`/1000]
log $(echo CPU temperature is $[`cat /sys/class/thermal/thermal_zone0/temp`/1000])
Copy after login

使用watch命令循环执行

watch -n 1 ./cputemp.sh
Copy after login
Copy after login

执行在命令控制台的结果和之前是一样的,但是现在在同一个文件目录下会生成一个cputemp.log的文件,查看该文件可以发现CPU的温度信息已记录。

使用cat命令查看cputemp.log

cat ./cputemp.log
Copy after login

得到文件内容,如下

从图中可以看出CPU温度在40-41之间波动。

注意事项

1、不能把watch命令写到cputemp.sh脚本里面

这中间还是有一点不完善的地方是,不能把watch命令写到cputemp.sh脚本里面是比较麻烦的,如果把watch命令写到cputemp.sh脚本里面,就会出现执行的温度信息被固定成一个固定值,不能做到实时查看。

如下:

修改的脚本:

#!/bin/bash
watch -n 1 echo CPU temperature is $[`cat /sys/class/thermal/thermal_zone0/temp`/1000]
Copy after login

执行:

./cputemp.sh
Copy after login

执行结果:

从执行结果中可以看到

$[`cat /sys/class/thermal/thermal_zone0/temp`/1000]
Copy after login

被固定成了40,导致每秒循环只是打印

CPU temperature is 40
Copy after login

而不能达到效果,所以目前只能用命令调用脚本的方式了。

2、单引号内引用变量需要嵌套单引号

在使用 sed 命令时用到了单引号(‘’),单引号内需要引用变量时,需要对引用变量嵌套单引号,不然会报错。

sed -i '1,'$fileDeleteLen'd' $fileName
Copy after login

总结:

目前这种实现方式也满足了基本需求。

The above is the detailed content of Linux script study notes, log function usage tips. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create a script for editing? Tutorial on how to create a script through editing How to create a script for editing? Tutorial on how to create a script through editing Mar 13, 2024 pm 12:46 PM

Cutting is a video editing tool with comprehensive editing functions, support for variable speed, various filters and beauty effects, and rich music library resources. In this software, you can edit videos directly or create editing scripts, but how to do it? In this tutorial, the editor will introduce the method of editing and making scripts. Production method: 1. Click to open the editing software on your computer, then find the "Creation Script" option and click to open. 2. In the creation script page, enter the "script title", and then enter a brief introduction to the shooting content in the outline. 3. How can I see the "Storyboard Description" option in the outline?

How to execute .sh file in Linux system? How to execute .sh file in Linux system? Mar 14, 2024 pm 06:42 PM

How to execute .sh file in Linux system? In Linux systems, a .sh file is a file called a Shell script, which is used to execute a series of commands. Executing .sh files is a very common operation. This article will introduce how to execute .sh files in Linux systems and provide specific code examples. Method 1: Use an absolute path to execute a .sh file. To execute a .sh file in a Linux system, you can use an absolute path to specify the location of the file. The following are the specific steps: Open the terminal

How to convert ESD files to ISO format How to convert ESD files to ISO format Feb 19, 2024 am 08:37 AM

An esd file is a compression format used in Windows operating systems, while an ISO file is a disc image file used to create a disc copy or virtual optical drive. When we need to convert esd files to iso files, it may be because ISO files are more commonly used and easier to use. The following will introduce you to some common methods to complete this conversion process. Method 1: Use ESDDecrypter ESDDecrypter is a program specially used to decrypt and convert esd files to iso files.

How to quickly delete the line at the end of a file in Linux How to quickly delete the line at the end of a file in Linux Mar 01, 2024 pm 09:36 PM

When processing files under Linux systems, it is sometimes necessary to delete lines at the end of the file. This operation is very common in practical applications and can be achieved through some simple commands. This article will introduce the steps to quickly delete the line at the end of the file in Linux system, and provide specific code examples. Step 1: Check the last line of the file. Before performing the deletion operation, you first need to confirm which line is the last line of the file. You can use the tail command to view the last line of the file. The specific command is as follows: tail-n1filena

Secrets of the Linux root file system Secrets of the Linux root file system Feb 15, 2024 pm 01:42 PM

Linux is an open source, portable, and customizable operating system that is widely used in various fields, such as servers, desktops, embedded devices, etc. The core of Linux is the kernel, which is responsible for managing hardware resources and providing basic services. However, the kernel is not an independent entity and requires a file system to store and access various data and programs. A file system is a method of organizing and managing files. It defines the file's name, location, attributes, permissions and other information. In Linux, there are many different types of file systems, such as ext4, xfs, btrfs, etc., each of which has its own characteristics and advantages. However, among all file systems, there is a special file system, which is the foundation and core of the Linux system, which is

Why can't I execute bat file on Windows 7? Why can't I execute bat file on Windows 7? Feb 19, 2024 pm 03:19 PM

Why can't win7 run bat files? Recently, many users using the Windows7 operating system have reported that they cannot run .bat files. This sparked widespread discussion and confusion. Why can't a well-functioning operating system run a simple .bat file? First, we need to understand the background of the .bat file. A .bat file, also known as a batch file, is a plain text file that contains a series of commands that can be used by the Windows command interpreter (cmd.ex

Windows PowerShell Scripting Tutorial for Beginners Windows PowerShell Scripting Tutorial for Beginners Mar 13, 2024 pm 10:55 PM

We've designed this Windows PowerShell scripting tutorial for beginners, whether you're a tech enthusiast or a professional looking to improve your scripting skills. If you have no prior knowledge of PowerShell scripting, this article will start with the basics and be tailored for you. We'll help you master the installation steps for a PowerShell environment and walk you through the main concepts and features of PowerShell scripts. If you're ready to learn more about PowerShell scripting, let's embark on this exciting learning journey together! What is WindowsPowerShell? PowerShell is a hybrid command system developed by Microsoft

How to automate tasks using PowerShell How to automate tasks using PowerShell Feb 20, 2024 pm 01:51 PM

If you are an IT administrator or technology expert, you must be aware of the importance of automation. Especially for Windows users, Microsoft PowerShell is one of the best automation tools. Microsoft offers a variety of tools for your automation needs, without the need to install third-party applications. This guide will detail how to leverage PowerShell to automate tasks. What is a PowerShell script? If you have experience using PowerShell, you may have used commands to configure your operating system. A script is a collection of these commands in a .ps1 file. .ps1 files contain scripts executed by PowerShell, such as basic Get-Help

See all articles