1

Iterate over files in folder and creating symlinks:

I have the current script that is trying to iterate over files in a folder, and create symlinks into another folder:

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

########## Variables

dir=~/dotfiles                    # dotfiles directory
config_files=$dir/*

# move any existing home files in homedir to dotfiles_old directory, then create symlinks
for config_file in $config_files; do
  ln -s $dir/$config_file ~/.$config_file
done

Now, if in my ~/dotfiles I have more than files, for example, I have folders with files in it. How can I make sure that I create the folders as well as do the symlinking?

So, for example, in my ~/dotfiles I have:

~/dotfiles/.config/fish/config.fish and ~/dotfiles/.config/fish/conf.d/config.fish

I should finish with a symlink to

~/.config/fish/config.fish and ~/.config/fish/conf.d/config.fish

How can I do that?

  • augh quote those variables in the event a space sneaks into a filename – thrig Dec 31 '17 at 1:06
  • What's wrong with symlinks to directories? – Kamil Maciorowski Dec 31 '17 at 2:46
2

Maybe you can use cp instead of ln. From man 1 cp:

-R
copy directories recursively

-s
make symbolic links instead of copying

Notes:

  • -R is required by POSIX but -s is not (your cp may or may not support it).
  • If you "copy" a file this way, -R won't hurt.
  • cp -Rs … will replicate directory structure with symlinks to files (not symlinks to directories); it seems this is what you want.
  • In my Kubuntu creating relative symlinks with cp is limited to the current directory, so it's useless with -R. Use full path to the directory you want to "copy".
  • Research -p option of cp. I guess you want to use it.

Few concerns about your script:

  • This comment is wise; quote variables.
  • * won't return files nor directories with names starting with a dot (.).
  • Good idea but this works only if the source dir is an absolute path. Otherwise you get cp: targetdir/subdir/file2: can make relative symbolic links only in current directory – Hauke Laging Dec 31 '17 at 12:13

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.