首页 > 解决方案 > 如何防止我的脚本自行符号链接?

问题描述

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

在下面的脚本中,.vscodefiles 变量中的条目是一个目录。当我最初运行脚本时(当没有创建符号链接时)一切正常。当我第二次运行脚本时,它仍然可以正常工作。但是,在第三次运行时,会在 ~/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

我想防止这种情况发生,但我不明白为什么会这样。我怎样才能防止这种情况?

标签: shelldotfiles

解决方案


从 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


推荐阅读