Shell脚本如何批量修改文件权限

wen 实用脚本 1

本文目录导读:

Shell脚本如何批量修改文件权限

  1. 使用 find 命令批量修改
  2. 使用 chmod 配合通配符
  3. 完整的批量修改脚本
  4. 选择性修改脚本
  5. 交互式批量修改
  6. 以当前用户为主的安全修改
  7. 实用技巧

下面是几种批量修改文件权限的Shell脚本方法:

使用 find 命令批量修改

修改所有 .sh 文件为可执行

find /path/to/directory -name "*.sh" -exec chmod +x {} \;

递归修改目录权限

# 设置目录为755
find /path/to/directory -type d -exec chmod 755 {} \;
# 设置普通文件为644
find /path/to/directory -type f -exec chmod 644 {} \;

使用 chmod 配合通配符

修改当前目录下的所有文件

# 所有文件设置为644
chmod 644 *
# 所有.py文件设置为755
chmod 755 *.py

完整的批量修改脚本

#!/bin/bash
# 批量修改文件权限脚本
# 用法: ./batch_chmod.sh <目录路径> <权限模式>
target_dir="${1:-.}"  # 默认当前目录
permission="${2:-644}"
# 检查目录是否存在
if [ ! -d "$target_dir" ]; then
    echo "错误: 目录 $target_dir 不存在"
    exit 1
fi
echo "开始修改 $target_dir 下的文件权限为 $permission"
# 修改所有文件(不包括目录)
find "$target_dir" -type f -exec chmod "$permission" {} \;
# 可选:单独设置目录权限
# find "$target_dir" -type d -exec chmod 755 {} \;
echo "修改完成"

选择性修改脚本

#!/bin/bash
# 选择性批量修改
directory="/path/to/directory"
# 修改特定类型文件
echo "修改日志文件权限..."
find "$directory" -name "*.log" -exec chmod 644 {} \;
echo "修改可执行脚本权限..."
find "$directory" -name "*.sh" -name "*.py" -exec chmod 755 {} \;
echo "修改配置文件权限..."
find "$directory" -name "*.conf" -name "*.ini" -exec chmod 600 {} \;

交互式批量修改

#!/bin/bash
read -p "请输入目录路径: " target_dir
read -p "请输入文件权限(如644): " permission
# 预览将要修改的文件
echo "以下文件将被修改:"
find "$target_dir" -type f -exec ls -l {} \;
read -p "确认修改? (y/n): " confirm
if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
    find "$target_dir" -type f -exec chmod "$permission" {} \;
    echo "修改完成"
else
    echo "已取消"
fi

以当前用户为主的安全修改

#!/bin/bash
# 只修改当前用户拥有的文件
user=$(whoami)
find /path/to/directory -user "$user" -type f -exec chmod 644 {} \;
find /path/to/directory -user "$user" -type d -exec chmod 755 {} \;

实用技巧

查看当前权限

# 查看文件权限
ls -l
# 查看特定类型文件权限
ls -l *.txt

常用权限设置

  • 755: 目录或可执行文件(rwxr-xr-x)
  • 644: 普通文件(rw-r--r--)
  • 600: 敏感文件(rw-------)
  • 777: 所有用户完全控制(不推荐)

权限含义

r=4 (读)
w=2 (写)
x=1 (执行)

选择哪种方法取决于你的具体需求:

  • 需要递归处理:用 find
  • 简单批量:用通配符
  • 需要选择性:编写脚本

抱歉,评论功能暂时关闭!