Assume I want to symlink like in the following command:

ln -s /home/user/dots/cmus/cmus.theme /home/user/cmus/cmus.theme

But for the above command to work, I need to make sure that the directory /home/user/cmus is already existing. Otherwise, there will be error. Is there a way to work around this like mkdir -p?

In order to make my problem clear, I'll put down my use case. I want to create a shell script which will symlink my dotfiles in appropriate locations. Until now, I have the following:



for dotfile in "${DOTFILES[@]}";do
    rm -rf "${HOME}/${dotfile}"
    ln -sf "${DIR}/${dotfile}" "${HOME}/${dotfile}"

But, I have no idea how I can work around the problem I specified without explicitly creating the directory beforehand.


If you’re using GNU cp, you can use its -s option:

cd "${HOME}"
cp -rs "${DIR}/.*" "${DIR}/*" .

This will create the appropriate directory hierarchies and symlink files instead of copying them.


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.