有没有机会在第一个错误时停止 chown?

Is there any opportunity to stop chown on first error?

当我使用递归 chown 时,我想在第一次出错时停止它。

$ chown -R /tmp/cache someuser
chown: changing ownership of `/tmp/cache/1/thumbnail/100x/9df78eab33525d08d6e5fb8d27136e95/h/d': Operation not permitted
chown: changing ownership of `/tmp/cache/1/thumbnail/100x/9df78eab33525d08d6e5fb8d27136e95/h': Operation not permitted
chown: changing ownership of `/tmp/cache/1/thumbnail/100x/9df78eab33525d08d6e5fb8d27136e95': Operation not permitted
chown: changing ownership of `/tmp/cache/1/thumbnail/100x': Operation not permitted
chown: changing ownership of `/tmp/cache/1/thumbnail': Operation not permitted
chown: changing ownership of `/tmp/cache/1': Operation not permitted
chown: changing ownership of `/tmp/cache': Operation not permitted

即我应该只得到 echo $?.
的第一个错误和状态代码“1” 可能吗?

没有。检测此类错误的唯一方法是观察标准错误,但是当您可以检测到错误并对错误做出反应时,chown 将继续运行。如果您需要在出现任何错误后采取措施,则需要 运行 chown 分别对每个文件进行处理,如果出现错误则采取措施。

# Assuming bash 4 for simplicity; handling the recursive directory walk
# without ** is left as an exercise for the reader.
shopt -s globstar
for f in /tmp/cache/**/*; do
    chown "$f" someuser || break
done

(完全有可能有人 可以 实现 chown 并带有在第一个错误后停止的选项,但这样的选项在 POSIX 规范或 GNU chown.)