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?

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

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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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