在设置权限前,需明确三个核心维度:
u(所有者,文件创建者)、g(所属组,所有者所在组的用户)、o(其他用户,系统其余用户)、a(所有用户,等同于ugo)。r(读,查看文件内容/列出目录内容)、w(写,修改文件内容/删除目录内文件)、x(执行,运行文件/进入目录)。r=4、w=2、x=1,将每组权限的数值相加(如rwx=7,rw-=6,r--=4),例如755表示所有者有rwx,组和其他用户有r-x。u/g/o/a指定用户,+/-/=调整权限(如u+x给所有者加执行权限,g-w移除组写权限,o=r设置其他用户为只读)。script.sh为所有者可读写执行(7)、组和其他用户可读执行(5):chmod 755 script.sh。config.txt为所有者可读写(6)、组和其他用户只读(4):chmod 644 config.txt。chmod u+x script.sh。chmod go-w data/(目录需保留x权限,否则无法进入)。使用-R参数可递归修改目录及其所有子目录、文件的权限,适用于批量调整。例如:
project/为755(所有者rwx,组和其他用户r-x):chmod -R 755 project/。logs/为组可写(775):chmod -R 775 logs/(注意:避免对系统目录使用777,防止安全风险)。除基本权限外,Linux提供三种特殊权限位,增强安全性或功能性:
passwd命令),设置命令:chmod u+s file(或数字权限第一位加4,如4755)。chmod g+s dir(或数字权限第二位加2,如2770)。/tmp目录),设置命令:chmod +t dir(或数字权限第三位加1,如1777)。结合find命令可精准批量修改权限,适用于复杂场景:
.sh脚本文件添加执行权限:find /path/to/dir -type f -name "*.sh" -exec chmod +x {} \;。.txt文件的写权限:find /path/to/dir -type f -name "*.txt" -exec chmod a-w {} \;。755,文件为644:find /path/to/dir -type d -exec chmod 755 {} \; + find /path/to/dir -type f -exec chmod 644 {} \;。/etc/passwd、/etc/shadow)设置777权限,防止未授权访问。chmod 770 file比chmod 777 file更安全)。semanage或restorecon调整SELinux上下文(如restorecon -Rv /path/to/dir)。public_html为所有者rwx、组r-x、其他用户r-x:chmod 755 public_html/。team_project设置SGID,确保新文件继承组:chmod 2770 team_project/。scripts/目录下所有.py文件添加执行权限:find scripts/ -type f -name "*.py" -exec chmod +x {} \;。backup/目录下所有文件的写权限:find backup/ -type f -exec chmod a-w {} \;。