I want to take down data in /path/to/data/folder/month/date/hour/minute/file and symlink it to /path/to/recent/file and do this automatically every time a file is created.
Assuming I will not know ahead of time if /path/to/recent/file exists, how can I go about creating it (if it doesn’t exist) or replacing it (if it does exist)? I am sure I can just check if it exists and then do a delete, symlink, but I’m wondering if there is a simple command which will do what I want in one step.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
This is the purpose of ln‘s -f option: it removes existing destination files, if any, before creating the link.
ln -sf /path/to/data/folder/month/date/hour/minute/file /path/to/recent/file
will create the symlink /path/to/recent/file pointing to /path/to/data/folder/month/date/hour/minute/file, replacing any existing file or symlink to a file if necessary (and working fine if nothing exists there already).
If a directory, or symlink to a directory, already exists with the target name, the symlink will be created inside it (so you’d end up with /path/to/recent/file/file in the example above). The -n option, available in some versions of ln, will take care of symlinks to directories for you, replacing them as necessary:
ln -sfn /path/to/data/folder/month/date/hour/minute/file /path/to/recent/file
POSIX ln doesn’t specify -n so you can’t rely on it generally. Much of ln’s behaviour is implementation-defined so you really need to check the specifics of the system you’re using. If you’re using GNU ln, you can use the -t and -T options too, to make its behaviour fully predictable in the presence of directories (i.e. fail instead of creating the link inside the existing directory with the same name).
Method 2
Please read the manual.
ln -sfn /new/target /path/to/symlink
$ man ln
-n, –no-dereference
treat LINK_NAME as a normal file if it is a symbolic link to a
directory
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0