What is the difference between unlink and rm?

Solution 1:

Both are a wrapper to the same fundamental function which is an unlink() system call.

To weigh up the differences between the userland utilies.

rm(1):

  • More options.
  • More feedback.
  • Sanity checking.
  • A bit slower for single calls as a result of the above.
  • Can be called with multiple arguments at the same time.

unlink(1):

  • Less sanity checking.
  • Unable to delete directories.
  • Unable to recurse.
  • Can only take one argument at a time.
  • Marginally leaner for single calls due to it's simplicity.
  • Slower when compared with giving rm(1) multiple arguments.

You could demonstrate the difference with:

$ touch $(seq 1 100)
$ unlink $(seq 1 100)
unlink: extra operand `2'

$ touch $(seq 1 100)
$ time rm $(seq 1 100)

real    0m0.048s
user    0m0.004s
sys     0m0.008s

$ touch $(seq 1 100)
$ time for i in $(seq 1 100); do rm $i; done

real    0m0.207s
user    0m0.044s
sys     0m0.112s

$ touch $(seq 1 100)
$ time for i in $(seq 1 100); do unlink $i; done

real    0m0.167s
user    0m0.048s
sys     0m0.120s

If however we're talking about an unadulterated call to the system unlink(2) function, which I now realise is probably not what you're accounting for.

You can perform a system unlink() on directories and files alike. But if the directory is a parent to other directories and files, then the link to that parent would be removed, but the children would be left dangling. Which is less than ideal.

Edit:

Sorry, clarified the difference between unlink(1) and unlink(2). Semantics are still going to differ between platform.

Solution 2:

At the POSIX spec level, what rm does is specified much more tightly than what unlink does.

The portability of the outcome seems likely to be better using rm, if your script has to run across OS's.


Solution 3:

The slow part of removing is the filesystem code and disk stuff, not the userspace preparation of the unlink() system call.

I.e.: if the speed difference matters, then you shouldn't be storing the data on the file system.

unlink is just a rm "light". rm has more features but they do the same thing.

Tags:

Linux

Shell