Linux好用到跺脚的shell 脚本--持续更新

下面是一些实用的 Shell 脚本示例,涵盖了一些常见的用例:

1. 文件备份脚本:

#!/bin/bash

# 定义源目录和目标目录
source_dir="/path/to/source"
backup_dir="/path/to/backup"

# 创建备份目录
mkdir -p "$backup_dir"

# 备份文件
cp -r "$source_dir" "$backup_dir"

echo "Backup completed!"

2. 日志文件清理脚本:

#!/bin/bash

# 定义日志目录和保留天数
log_dir="/var/log/myapp"
retention_days=7

# 删除旧于保留天数的日志文件
find "$log_dir" -name "*.log" -mtime +$retention_days -exec rm {
   } \;

echo "Log files older than $retention_days days have been deleted."

3. 批量文件重命名脚本:

#!/bin/bash

# 定义文件名前缀和目录
prefix="new_"
directory="/path/to/files"

# 批量重命名文件
for file in "$directory"/*; do
  new_name="$directory/$prefix$(basename "$file")"
  mv "$file" "$new_name"
done

echo "Files have been renamed with prefix '$prefix'."

4. 网络连接检测脚本:

#!/bin/bash

# 定义要检测的远程主机
remote_host="example.com"
ping_count=3

# 执行 ping 命令检测连接状态
ping -c $ping_count $remote_host > /dev/null 2>&1

if [ $? -eq 0 ]; then
  echo "Connection to $remote_host is successful."
else
  echo "Connection to $remote_host failed."
fi

5. 文件批量转换脚本:

#!/bin/bash

# 定义源文件类型和目标文件类型
source_extension="txt"
target_extension="md"

# 批量转换文件类型
for file in *.$source_extension; do
  mv "$file" "${file%.$source_extension}.$target_extension"
done

echo "Files have been converted from .$source_extension to .$target_extension."

6. 用户账户管理脚本:

#!/bin/bash

# 定义用户名和密码
new_user="new_user"
password="password123"

# 检查用户是否已存在
if id "$new_user" &>/dev/null; then
  echo "User $new_user already exists."
else
  # 创建新用户
  useradd -m -s /bin/bash "$new_user"
  echo "$new_user:$password" | chpasswd
  echo "User $new_user has been created with password $password."
fi

7. 定时备份脚本:

#!/bin/bash

# 定义源目录、目标目录和备份文件名
source_dir="/path/to/source"
backup_dir="/path/to/backups"
backup_file="backup_$(date +\%Y\%m\%d).tar.gz"

# 创建备份目录
mkdir -p "$backup_dir"

# 执行备份
tar -czf "$backup_dir/$backup_file" "$source_dir"

echo "Backup completed and saved as $backup_file."

8. 文件内容搜索脚本:

#!/bin/bash

# 定义搜索目录和关键字
search_dir="/path/to/search"
keyword="example"

# 在文件中搜索关键字
grep -r "$keyword" "$search_dir"

echo "Search completed for keyword '$keyword'."

9. 自动化 Git 操作脚本:

#!/bin/bash

# 定义仓库目录和提交消息
repo_dir="/path/to/repository"
commit_message="Update files"

# 进入仓库目录
cd "$repo_dir" || exit

# 添加所有文件到暂存区
git add .

# 提交更改
git commit -m "$commit_message"

# 推送到远程仓库
git push origin master

echo "Git operations completed."

10. 系统性能监控脚本:

#!/bin/bash

# 显示 CPU 使用率
echo "CPU Usage:"
mpstat 1 1

# 显示内存使用情况
echo "Memory Usage:"
free -m

# 显示磁盘使用情况
echo "Disk Usage:"
df -h

# 显示网络连接情况
echo 

你可能感兴趣的:(Linux,chrome,前端,linux)