简单而有效的Linux Shell脚本示例

原创
ithorizon 6个月前 (10-16) 阅读数 28 #Linux

明了而有效的Linux Shell脚本示例

在Linux系统中,Shell脚本是一种强势的工具,可以帮助我们自动化日常任务,减成本时间工作高效能。下面,我将通过几个明了而有效的Shell脚本示例,向大家展示Shell脚本的魅力。

### 1. 检查系统是否正常运行

这个脚本可以检查系统是否正常运行,包括CPU、内存、磁盘空间等关键指标。

bash

#!/bin/bash

# 检查CPU使用率

cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')

echo "CPU使用率: $cpu_usage%"

# 检查内存使用率

mem_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')

echo "内存使用率: $mem_usage%"

# 检查磁盘空间

disk_usage=$(df / | grep / | awk '{print $5}')

echo "磁盘空间使用率: $disk_usage"

### 2. 自动备份重要文件

这个脚本可以将指定目录下的重要文件备份到另一个目录。

bash

#!/bin/bash

# 源目录

source_dir="/path/to/source"

# 目标目录

dest_dir="/path/to/destination"

# 创建备份目录

mkdir -p $dest_dir

# 备份文件

tar -czvf $dest_dir/backup_$(date +%Y%m%d%H%M%S).tar.gz $source_dir

### 3. 清理日志文件

这个脚本可以自动清理指定目录下的日志文件,保留最近7天的日志。

bash

#!/bin/bash

# 日志目录

log_dir="/path/to/log"

# 获取当前日期

current_date=$(date +%Y%m%d)

# 获取7天前的日期

last_date=$(date --date="7 days ago" +%Y%m%d)

# 删除7天前的日志文件

find $log_dir -type f -name "*.log" -mtime +7 -exec rm {} \;

# 保留最近7天的日志文件

find $log_dir -type f -name "*.log" -mtime -7 -exec mv {} $log_dir/$current_date \;

### 4. 查找大文件

这个脚本可以查找指定目录下大于指定大小的文件。

bash

#!/bin/bash

# 搜索目录

search_dir="/path/to/search"

# 大小束缚(单位:MB)

size_limit=100

# 查找大于指定大小的文件

find $search_dir -type f -size +${size_limit}M

### 5. 自动重启服务

这个脚本可以自动重启指定服务。

bash

#!/bin/bash

# 服务名称

service_name="nginx"

# 重启服务

systemctl restart $service_name

### 总结

以上几个Shell脚本示例展示了Shell脚本在Linux系统中的明了应用。通过这些示例,我们可以了解到Shell脚本的基本语法和常用命令。在实际工作中,我们可以通过需要编写更复杂化的脚本,实现更多自动化任务。期望这些示例能够帮助大家更好地掌握Shell脚本,减成本时间工作高效能。

本文由IT视界版权所有,禁止未经同意的情况下转发

文章标签: Linux


热门