Home > database >  Better/Nicest way to symlink into multiple folders?
Better/Nicest way to symlink into multiple folders?

Time:07-09

I have this directory structure, and I need to generate symlinks for common/provider.tf in both environments/prod and environments/prod/module.

/
├─ common
│  ├─ provider.tf
├─ environments/
│  ├─ prod/
│  │  ├─ module/

I managed to do it this way:

  if [ -e "../../../common/provider.tf" ]; then  # I'm in environments/prod/module
    ln -s ../../../common/provider.tf provider.tf
  else  # I'm in the root folder "/"
    ln -s common/provider.tf $environment/provider.tf  # $environment is /environments/prod
  fi

But I realize that my code sucks and I can't come up with a better idea.

Any idea on how to do it better? Note: There are lots of environments and lots of modules, I'm using that code recursively.

CodePudding user response:

Store the absolute path to the root directory, and construct the various link destination paths relative to this reference root directory.

#!/bin/sh

root_dir='/absolute/path/to/root/dir'
provider_tf="${root_dir}/common/provider.tf"
prod_dir="${root_dir}/environments/prod"
module_dir="${prod_dir}/module"

for dest_dir in "${prod_dir}" "${module_dir}"; do
  ln --symbolic --relative "${provider_tf}" "${dest_dir}/"
done

CodePudding user response:

The OS actually doesn't care at all what your symlink points to. You can do

ln -s /no/such/path brokenlink

and similarly you can

ln -s ../../../common/provider.tf environments/prod/module/provider.tf

regardless of what your current directory is; the symlink will be resolved relative to the directory where you created it.

Unfortunately, ln only allows you to create a single symlink at a time; but with this, you could also create the links from the project's base directory with a simple loop.

for dest in environment environment/prod
do
    ln -s $PWD/common/provider.tf "$dest"
done

The variable $PWD is a Bash built-in (but not available in sh, which you had also originally tagged your question as; perhaps see also Difference between sh and bash) - you could also add a --relative option to convert it to a relative symlink like Léa proposes if you have GNU ln (but again, this is not properly portable to POSIX ln). (If you need POSIX/sh portability, you can add PWD=$(pwd) before the loop.)

  • Related