0

I would like to ask for your help:

I have a main.sh script, which is in dir1, and another variables.sh script, which is in dir2.

The variables.sh script is being loaded inside main.sh as follows:

. variables.sh

Inside the variables.sh, I have the following snippet:

VARIABLES_PATH=$0
VARIABLES_DIR=$(dirname "$VARIABLES_PATH")
dir=$(pwd)

echo "*************************** VARIABLES_DIR=> $VARIABLES_DIR"
echo "*************************** pwd=> $dir"

I would like to get the name of the variables.sh directory and use it in other variables within this same script doing a concatenation...

The problem is:

The result of $dir and $VARIABLES_DIR is always being filled with dir1 (when I need it to be dir2). Did you understand? Can anyone/know how to help me do what I need?

Do I have to change my logic when getting the dir2 value?

  • 1
    Use `$BASH_SOURCE`, not `$0`. This is extensively covered in the relevant BashFAQ entry, [BashFAQ #28](https://mywiki.wooledge.org/BashFAQ/028). – Charles Duffy Jan 12 '22 at 21:03
  • 1
    Also, `$(pwd)` is needlessly slow compared to `$PWD` (like every other use of `$(...)`, it `fork()`s off a new copy of your shell). For similar reasons, `result=$(dirname "$somefile")` is much slower than `result=${somefile%/*}` (though it _does_ cover some corner cases the latter does not). – Charles Duffy Jan 12 '22 at 21:03
  • 1
    ...also, note that all-caps names are used for variables that reflect or modify behavior of POSIX-defined tools, whereas names with at least one lowercase character are reserved for application use. Much better to use `variables_path` / `variables_dir` if you don't have a compelling reason to do otherwise, so you can't corrupt a shell builtin variable that's added in the future under that same name. (Granted, zsh muddies the waters here by giving lowercase variables special reason, but zsh doesn't pretend or attempt to be POSIX-compliant) – Charles Duffy Jan 12 '22 at 21:06
  • 1
    BTW, `source . variables.sh` doesn't really make sense. Do you mean `source ./variables.sh` or `. variables.sh`? – Charles Duffy Jan 12 '22 at 21:07
  • Hi @CharlesDuffy! It was a typing error. The way to run is `. variables.sh` – Aécio Pires Jan 12 '22 at 21:50
  • **SOLVED** Thanks @CharlesDuffy! I solved the problem with the $BASH_SOURCE. I saw your comments, the related [post](https://stackoverflow.com/questions/35718955/bash-script-to-get-its-full-path-use-source-to-invoke-it) and also the [official doc](https://www.gnu.org/software/bash/manual/html_node/Bash-Variables.html). ``variables.sh``: ``` #!/bin/bash variables_path=$BASH_SOURCE variables_dir=$(dirname "$variables_path") echo "********* variables_dir => $variables_dir" config_file="${variables_dir}/config.yaml echo "********* config_file => $config_file" ``` – Aécio Pires Jan 12 '22 at 22:38

0 Answers0