Why doesn’t recursion go upwards with rm

recursive

I'm wondering about direction of recursion in general and rm specifically.

rm recursion only works downwards correct?

Running: sudo rm -R *.QTFS will delete all *.QTFS files in current directory and its children, correct?

current directory as displayed by ls -lha also contains . and .. links for the lack of a better word, so why doesn't recursion follow these upwards in the directory tree? Is there an artificial limit on rm app, or . and .. are not real things?

Best Answer

rm recursion only works downwards correct?

rm -r x y will delete x and y and everything inside them (if they are directories), but not their parents or anything outside them.

Running: sudo rm -R *.QTFS will delete all *.QTFS files in current directory and its children, correct?

No. It will delete all files named *.QTFS, any files recursively inside directories called *.QTFS, and those directories themselves. If you want that other deletion behaviour, use find -delete.

current directory as displayed by ls -lha also contains . and .. links for the lack of a better word, so why doesn't recursion follow these upwards in the directory tree? Is there an artificial limit on rm app, or . and .. are not real things?

It's an artificial limit of rm.

It's not really all that artificial, though - it's the only way it could ever work. If rm followed the parent .. links, every rm -r would remove every file on the system, by following all of the .. links all the way back to /. rm sees the .. and . entries in each directory when it lists the content, and explicitly disregards them for that reason.

You can try that out yourself, in fact. Run rm -r . and most rm implementations will refuse to act, reporting an error explicitly:

$ rm -r .
rm: refusing to remove ‘.’ or ‘..’ directory: skipping ‘.’

(that message is from GNU rm; others are similar). When it encounters these entries implicitly, rather than as explicit arguments, it just ignores them and continues on. That behaviour is required by POSIX. In GNU rm and many of the BSDs, it's provided automatically by the fts_read family of hierarchy-traversal functions.

or . and .. are not real things?

. and .. are generally real directory entries, although that is filesystem-specific. They will almost always be presented as though they are real entries to all user code, regardless. Many pieces of software (not just rm) special-case their behaviour in order to catch or prevent runaway or undesirable recursion.

Related Question