Why is this symbolic link created two instances

狂风中的少年 提交于 2020-01-15 06:38:29

问题


I have an install script used for my dotfiles. I am using to create symbolic links of one directory to my home folder. The links execute fine apart but a second symobolic link is created and I cannot reason why.

The folder structure in the project looks like this

install.sh
scripts/
    shell.sh
shell/

install.sh calls shell.sh and that calls the command

ln -s $SCRIPTS_DIR/shell/ $HOME/.shell

$SCRIPTS_DIR is a full path

So I do get a .shell directory in my home directory linked just fine but now my project folder has an extra symbolic link

install.sh
scripts/
    shell -> PATH_TO_PROJECT/shell
    shell.sh 
shell/

Any explanation would be appreciated


回答1:


Think about what happens when you run the ln -s command twice when its target is a directory rather than a file.

If $HOME/.shell doesn't exist, then

ln -s "$SCRIPTS_DIR/shell/" "$HOME/.shell"

...creates it. However, if it already exists, then...

ln -s "$SCRIPTS_DIR/shell/" "$HOME/.shell"

...treats .shell as a destination directory name, not a complete path to the destination to be created, and creates a new entry within that directory.


GNU ln has some extensions to fix this usage, including:

-h If the target_file or target_dir is a symbolic link, do not follow it. This is most useful with the -f option, to replace a symlink which may point to a directory.

Thus, if operating on a GNU system, you could use:

# quotes added for bash compatibility, since question is tagged for both shells
ln -sfh "$SCRIPTS_DIR/shell/" "$HOME/.shell"

Otherwise, just check first:

[[ -e $HOME/.shell ]] || ln -s "$SCRIPTS_DIR/shell/" "$HOME/.shell"


来源:https://stackoverflow.com/questions/30470530/why-is-this-symbolic-link-created-two-instances

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!