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

时间:2015-08-17 16:56:34

标签: bash error-handling chown

当我使用递归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” 有可能吗?

1 个答案:

答案 0 :(得分:2)

没有。检测此类错误的唯一方法是观察标准错误,但是当您检测到并对错误做出反应时,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 {中不存在这样的选项{1}}。)