I am trying to write a shell script to create link for file from my dotfiles repo to my home folder.

I want to use hard link if possible because it cannot be broken when moving it to somewhere in the same filesystem with HOME.

But if I clone the dotfiles to another filesystem, I have to use symlink instead.


So, how to create hard link for file if possible, else use symlink in shell script?

up vote 4 down vote accepted
ln source target 2>/dev/null || ln -s source target 2>/dev/null || exit 1

or, slightly more "interactively" (chattier),

if ! ln source target 2>/dev/null; then
    echo 'failed to create hard link, trying symbolic link instead' >&2
    if ! ln -s source target 2>/dev/null; then
        echo 'that failed too, bailing out' >&2
        exit 1
    fi
fi

Remove the redirections to /dev/null to see the error messages displayed by ln (if any).

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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