使用 yes 命令对所有问题回答否

Answer no to all questions using the yes command

我正在尝试删除 所有 文件 除了 只读文件,但此命令无论如何都会删除所有文件:

yes n | rm *

我是不是做错了什么?如果不是,为什么它不起作用?

在 Posix 系统中,文件的只读状态不会阻止它被 rm 删除。

你还没有说你的 shell 是什么,但也许你有一个 rm 的别名,当文件是只读的时候它会要求你确认,而且这个别名的行为不同当它 stdin 是管道的一部分时。

rm自动启用提示用户删除不可写文件的-i模式,标准输入必须是终端(如手册页中指定)。

因此,为了使命令正常工作,用户必须手动指定 -i 选项:

yes n | rm -i *

执行此操作后,命令将按预期运行。

问题是您只需要对文件夹的写入权限,而不是对文件的写入权限,即可删除它们:

(From here)

Any attempt to access a file's data requires read permission. Any attempt to modify a file's data requires write permission. Any attempt to execute a file (a program or a script) requires execute permission.

In *nix systems directories are also files and thus use the same permission system as for regular files. Note permissions assigned to a directory are not inherited by the files within that directory.

Because directories are not used in the same way as regular files, the permissions work slightly (but only slightly) differently. An attempt to list the files in a directory requires read permission for the directory, but not on the files within. An attempt to add a file to a directory, delete a file from a directory, or to rename a file, all require write permission for the directory, but (perhaps surprisingly) not for the files within. Execute permission doesn't apply to directories (a directory can't also be a program). But that permission bit is reused for directories for other purposes.

要查找具有特定权限的文件,您可以使用

find -perm <mode>

read more

要删除通过查找找到的文件,您可以使用

 find . -perm 444 -exec /bin/rm {} \;

(mybe略有不同,这取决于您搜索的文件和您拥有的系统)

more exec examples