I have a script that goes like this
ln /myfile /dev/${uniquename}/myfile
I want to remove the link of /dev/somename/myfile
to decrease the link count.
How do I do this?
TL;DR... just delete the file name you don't want (with rm
).
If you create a hard link (which is what your command above is doing), you have two names pointing to the same area of storage. You can delete either name without affecting the other name or the storage - it's only when the last name is removed that the area of storage is released.
Compare this to soft links... created with ln -s
- there, the link is different, it's a pointer to the original name rather than a pointer to the storage. If you delete the original named file the soft links point to something that has been deleted, so the link remains but is broken.
I’m a little uncertain of your meaning, but I think your script creates /myfile
as a hardlink to /dev/…/myfile
and then you want to remove the latter.
If this is correct, instead of linking then removing the link, you could just move the file instead, producing the same result in a single command (mv) instead of two commands (ln and rm):
mv /dev/…/myfile /
Most existing answers advocate using rm
. This is entirely correct, because you don't remove files: you remove links (and the file is removed when the last link pointing to it is removed, and the last open file descriptor is closed).
However, you should be aware of another utility too, unlink
. It lacks the options of rm
, and always has implicit -f
option (sort of -- it will fail on a missing file, though). The benefit is that you can remove a file starting with a dash, at least in a theory...
...except you can't, if you use a Linux system, because the GNU crippled the unlink
utility by adding command-line option support! So unlink -t
does not remove a file named -t
on a Linux system or any other system using the GNU coreutils.
(Yes, I know that rm -- -t
or unlink -- -t
works, no need to comment about that.)
unlink -f foobar
gives usage: rm [-f | -i] [-dPRrvW] file ...
, so it's not just GNU. Even if it was, so what? If you have filenames starting with dashes, you'll need to know to use --
or ./
at some point anyway, it doesn't help much if there's just one application that doesn't use command line options.
unlink
aren't allowed to have any options, like it does say for echo
unlink
utility, even though it's standard, is so obscure that OpenBSD doesn't even have it in its base system.
/dev/${uniquename}
directory already exists and/myfile
and/dev/{uniquename}/.
are on the same filesystem.