Home > Mobile >  (bash script) Better/Nicest way to perform this if statement inside folders?
(bash script) Better/Nicest way to perform this if statement inside folders?

Time:07-08

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

  • Related