What does ln -T do? I know the flag does not exist in the BSD version of ln, and it only exists in the GNU version, and I have read the documentation that it will make ln "treat LINK_NAME as a normal file always", but what does that mean and why does the BSD version not have it?

  • 1
    The GNU implementation of ln has both -t (--target-directory) and -T (--no-target-directory). You reference both in your question, but I assume that you actually mean only -T? – Kusalananda Sep 24 '19 at 18:00
  • The flags -T and -t have the same purpose in ln, cp, mv and install, as explained in the "Target Directory" entry of texinfo manual -- the link is temporary not working, but you can get the same via info ln. – mosvy Sep 24 '19 at 21:46

The -T (--no-target-directory) option to GNU ln provides a safety feature that may be useful in scripts.

Suppose that you want to create a new name, $newname, for a file $filename, where the new name is maybe provided from external sources.

The command

ln -T "$filename" "$newname"

would then fail if $newname was an already existing directory, instead of unexpectedly creating the name $filename inside that directory (which may cause further operations to fail in hilarious ways).

It's a shortcut for something like

if [ ! -e "$newname" ]; then
    ln "$filename" "$newname"
    printf 'failed to create hard link "%s": File exists\n' "$newname" >&2
    # Further code to handle failure to create link here.

Likewise, the -t (--target-directory) provides a way of ensuring that the new name for the file is actually created inside an existing directory, and nowhere else.

Also, as pointed out by Stephen Kitt in comments, moving the test on the filetype of the target/"link name" into the utility itself may also decrease the risk of being affected by the race condition whereby the target is changed in-between testing for its existence and/or type and actually creating the link.

Why does POSIX or BSD not have -T or -t? Well, GNU tool in general have many extensions added that provide convenience. The -T and -t options to ln are some of these. They don't really let you do something that couldn't be done without them, and they don't add functionality. Some systems, like the BSDs, have not even considered adding them, or have considered but rejected the idea of adding them (I don't really know, I can't recall seeing anyone send in a patch to add it on the openbsd-tech mailing list, for example).

  • Convenience is the key. Your pseudo-code is an apt workaround for the lack of -T. And indeed, ln foo bar/ fails if bar is neither a directory nor a symlink to a directory. Plus it is slightly more compact to write. – Jim L. Sep 24 '19 at 20:19
  • One benefit of the options is that they allow less racy implementations. – Stephen Kitt Sep 24 '19 at 22:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.