Appearance
文件权限
基本概念
权限类型
bash
#!/bin/bash
# 查看文件权限
ls -l file.txt
# 输出示例:-rw-r--r-- 1 user group 1234 Jan 1 12:00 file.txt
# -rw-r--r--
# ^^^^^^^^
# ||||||||
# |||||||+--- 其他用户权限
# ||||||+---- 组权限
# |||||+----- 所有者权限
# ||||+------ 文件类型权限说明
- r:读权限
- w:写权限
- x:执行权限
- -:无权限
权限表示
符号表示
bash
#!/bin/bash
# 符号表示
# rwx rwx rwx
# ^^^ ^^^ ^^^
# ||| ||| |||
# ||| ||| +--- 其他用户权限
# ||| ||+---- 其他用户写权限
# ||| |+----- 其他用户读权限
# ||| +------ 组权限
# ||+------- 组写权限
# |+-------- 组读权限
# +--------- 所有者权限数字表示
bash
#!/bin/bash
# 数字表示
# r = 4
# w = 2
# x = 1
# - = 0
# 示例
# rwx = 4 + 2 + 1 = 7
# r-x = 4 + 0 + 1 = 5
# r-- = 4 + 0 + 0 = 4修改权限
使用符号
bash
#!/bin/bash
# 添加执行权限
chmod +x file.txt
# 移除写权限
chmod -w file.txt
# 设置特定权限
chmod u=rwx,g=rx,o=r file.txt使用数字
bash
#!/bin/bash
# 设置权限为 755
chmod 755 file.txt
# 设置权限为 644
chmod 644 file.txt
# 设置权限为 777
chmod 777 file.txt递归修改
bash
#!/bin/bash
# 递归修改目录权限
chmod -R 755 directory
# 递归修改目录权限(仅目录)
find directory -type d -exec chmod 755 {} \;
# 递归修改文件权限(仅文件)
find directory -type f -exec chmod 644 {} \;常用权限
文件权限
bash
#!/bin/bash
# 644:所有者读写,组和其他用户只读
chmod 644 file.txt
# 755:所有者读写执行,组和其他用户读执行
chmod 755 script.sh目录权限
bash
#!/bin/bash
# 755:所有者读写执行,组和其他用户读执行
chmod 755 directory
# 777:所有用户读写执行
chmod 777 directory特殊权限
SUID
bash
#!/bin/bash
# 设置 SUID
chmod u+s file.txt
# 移除 SUID
chmod u-s file.txtSGID
bash
#!/bin/bash
# 设置 SGID
chmod g+s directory
# 移除 SGID
chmod g-s directorySticky Bit
bash
#!/bin/bash
# 设置 Sticky Bit
chmod +t directory
# 移除 Sticky Bit
chmod -t directory实用示例
示例1:设置脚本权限
bash
#!/bin/bash
# 设置脚本为可执行
chmod +x script.sh
# 设置脚本权限为 755
chmod 755 script.sh示例2:设置配置文件权限
bash
#!/bin/bash
# 设置配置文件权限为 644
chmod 644 config.conf
# 设置敏感配置文件权限为 600
chmod 600 secret.conf示例3:设置目录权限
bash
#!/bin/bash
# 设置目录权限为 755
chmod 755 directory
# 递归设置目录权限
chmod -R 755 directory示例4:检查权限
bash
#!/bin/bash
# 检查文件权限
if [ -r file.txt ]; then
echo "文件可读"
fi
if [ -w file.txt ]; then
echo "文件可写"
fi
if [ -x file.txt ]; then
echo "文件可执行"
fi最佳实践
1. 使用最小权限
bash
# 好的做法
chmod 644 file.txt
# 不好的做法
chmod 777 file.txt2. 使用数字权限
bash
# 好的做法
chmod 755 script.sh
# 不好的做法
chmod u=rwx,g=rx,o=rx script.sh3. 递归修改
bash
# 好的做法
chmod -R 755 directory
# 不好的做法
find directory -exec chmod 755 {} \;总结
文件权限的关键点:
- 基本概念:读、写、执行权限
- 权限表示:符号表示、数字表示
- 修改权限:使用
chmod命令 - 常用权限:644、755、777
- 特殊权限:SUID、SGID、Sticky Bit
- 实用示例:设置脚本权限、设置配置文件权限、设置目录权限、检查权限
- 最佳实践:使用最小权限、使用数字权限、递归修改
下一节我们将学习文件查找的使用。