我希望快速找出目录中所有可写文件。有什么快捷的方法吗?
find -type f -maxdepth 1 -writable
-writable
选项将查找当前用户可写的文件。如果您想查找任何人都可以编写的文件(甚至是其他组合),可以使用-perm
选项:
find -maxdepth 1 -type f -perm /222
这将查找由其所有者(无论是谁)可写的文件:
find -maxdepth 1 -type f -perm /200
不同的字符可以用来控制mode参数的含义:
/
- 任何权限位-
- 所有位(-222
表示所有位 - 用户、组和其他人)222
表示除了写权限没有其他权限)-perm -u+w ! -perm -g+w ! -perm -o+w
。 - Dennis Williamson要查找可写文件,无论所有者、组或其他人,您可以检查ls中文件权限列中的w
标志。
ls -l | awk '$1 ~ /^.*w.*/'
$1是第一个字段,也就是ls -l命令的权限块,正则表达式只是查找第一个字段中的字母"w"。就是这样。
如果你想查找所有者的写权限
ls -l | awk '$1 ~ /^..w/'
如果您想查找组写入权限
ls -l | awk '$1 ~ /^.....w/'
如果您想查找其他人的写入权限
ls -l | awk '$1 ~ /w.$/'
=〜
正则表达式运算符类似。 - ghostdog74-f
会测试文件是否存在
-w
会测试文件是否可写
示例:
$ for f in *; do [ -f $f ] && [ -w $f ] && echo $f; done
test
命令的选项,也可以拼写为[
命令。 - bignosefind . -maxdepth 1 -type f -writable
看到这种类型的问题,您可以在superuser.com或serverfault.com上找到更好的答案。
如果您正在编写代码而不仅仅是使用shell,则可能会对access(2)系统调用感兴趣。
这个问题已经在serverfault上被问过了。
编辑:@ghostdog74问您是否删除了此文件的写权限,是否仍然会找到该文件。 答案是,否,这只会找到可写的文件。
dwaters@eirene ~/temp
$ cd temp
dwaters@eirene ~/temp/temp
$ ls
dwaters@eirene ~/temp/temp
$ touch newfile
dwaters@eirene ~/temp/temp
$ ls -alph
total 0
drwxr-xr-x+ 2 dwaters Domain Users 0 Mar 22 13:27 ./
drwxrwxrwx+ 3 dwaters Domain Users 0 Mar 22 13:26 ../
-rw-r--r-- 1 dwaters Domain Users 0 Mar 22 13:27 newfile
dwaters@eirene ~/temp/temp
$ find . -maxdepth 1 -type f -writable
./newfile
dwaters@eirene ~/temp/temp
$ chmod 000 newfile
dwaters@eirene ~/temp/temp
$ ls -alph
total 0
drwxr-xr-x+ 2 dwaters Domain Users 0 Mar 22 13:27 ./
drwxrwxrwx+ 3 dwaters Domain Users 0 Mar 22 13:26 ../
---------- 1 dwaters Domain Users 0 Mar 22 13:27 newfile
dwaters@eirene ~/temp/temp
$ find . -maxdepth 1 -type f -writable
dwaters@eirene ~/temp/temp
查找所有者可写的文件:
find ./ -perm /u+w
查找组可写文件:
find ./ -perm /g+w
查找任何人都可写的文件:
find ./ -perm /o+w
查找具有定义权限的文件:
find ./ -type -d -perm 0777
find ./ -type -d -perm 0755
find ./ -type -f -perm 0666
find ./ -type -f -perm 0644
使用以下方法禁用递归:
-maxdepth 1
for var in `ls`
do
if [ -f $var -a -w $var ]
then
echo "$var having write permission";
else
echo "$var not having write permission";
fi
done
find -writable
的问题在于它不具备可移植性,而且使用可移植的 find
运算符正确地模拟它也不容易。如果您的 find
版本没有它,您可以使用 touch
来检查文件是否可写,使用 -r
确保您(几乎)不会修改文件:
find . -type f | while read f; do touch -r "$f" "$f" && echo "File $f is writable"; done
touch
的 -r
选项在 POSIX 中,因此可以被认为是可移植的。当然,这比 find -writable
要低效得多。
请注意,touch -r
确实会更新每个文件的 ctime(元数据的最后更改时间),但人们很少关心 ctime。
touch
命令吗?更新时间戳的能力并不意味着该文件是可写的。 - Chris Johnsenstat -c "%A->%n" *| sed -n '/^.*w.*/p'
sudo su www-data
find . -writable 2>/dev/null
将 www-data 替换为 nobody 或 apache 或您的 Web 用户是什么。
touch 444 file
或touch 555 file
或chown somebodyelse:somebodyelse file
或许多变化,它都找不到它。 - Dennis Williamson