如何防止脚本自身链接?

时间:2019-07-24 14:28:16

标签: shell dotfiles

我已经修改了shell脚本,将我的dotfile从git存储库符号链接到我的主目录中。除一个问题外,它运作良好……似乎是在目录本身内部创建目录的符号链接。

在下面的脚本中,files变量中的.vscode条目是目录。最初运行脚本时(未创建符号链接时),一切正常。当我第二次运行脚本时,它仍然可以正常工作。但是,在第三次运行时,在〜/ projects / dotfiles / .vscode文件夹中创建了一个.vscode符号链接。

#!/bin/bash
############################
# makesymlinks.sh
# This script creates symlinks from the home directory to any desired dotfiles in ~/projects/dotfiles
############################

########## Variables

dir=~/projects/dotfiles                    # dotfiles directory
olddir=~/dotfiles_old             # old dotfiles backup directory
files=(.vscode .bash_profile .zshrc .gitconfig)    # list of files/folders to symlink in homedir

##########

# create dotfiles_old in homedir
echo -n "Creating $olddir for backup of any existing dotfiles in ~ ..."
mkdir -p $olddir
echo "done"

# change to the dotfiles directory
echo -n "Changing to the $dir directory ..."
cd $dir
echo "done"

# move any existing dotfiles in homedir to dotfiles_old directory, then create symlinks from the homedir to any files in the ~/projects/dotfiles directory specified in $files
for file in $files; do
    echo "Moving any existing dotfiles from ~ to $olddir"
    mv ~/$file $olddir/
    echo "Creating symlink to $file in home directory."
    ln -s $dir/$file ~/$file
done

我想防止这种情况的发生,但是我不知道为什么会这样。我该如何预防?

1 个答案:

答案 0 :(得分:0)

在ln(1)的手册页中:

-n    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.

尝试更新您的ln -s命令以改为使用ln -sfn