bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: proposed BASH_SOURCE_PATH


From: Koichi Murase
Subject: Re: proposed BASH_SOURCE_PATH
Date: Wed, 15 May 2024 23:46:04 +0900

2024年5月15日(水) 13:13 Peng Yu <pengyu.ut@gmail.com>:
> On Tue, May 14, 2024 at 3:35 AM Koichi Murase <myoga.murase@gmail.com> wrote:
> > I totally agree that we should have a way to specify the files in
> > subdirectories by the path relative to the current script file.
>
> I currently use something like this to source script files relatively.
>
> declare -g -A __sourced__files__
> __sourced__files__[$BASH_SOURCE]=$(realpath "$BASH_SOURCE")
> # This is to ensure to the relative path is to the actual bash file
> instead of a symlink to the bash file.
> source 
> "${__sourced__files__[$BASH_SOURCE]%/*}/dirname1/dirname2/${BASH_SOURCE##*/}"
> # My convention is that the file sourced in the subdirectory has the
> same filename as the parent file.
> # The difference between them are expressed in the directory path,
> i.e., dirname1/dirname2

Yeah, as far as we resolve the paths by ourselves and specify the
absolute path to the `source' builtin, it would reliably work. Even
BASH_SOURCE_PATH is unnecessary.

By the way, I got an inspiration from your example. You can define
name references to automate the resolution of the directory. With the
following definitions somewhere in a framework:

  declare -gA _Impl_file _Impl_dir _Impl_empty
  declare -gn 
__file__='_Impl_file[${_Impl_empty[x${_Impl_file[${BASH_SOURCE-$0}]=$(realpath
"${BASH_SOURCE-$0}")}]-}${BASH_SOURCE-$0}]'
  declare -gn 
__dir__='_Impl_dir[${_Impl_empty[x${_Impl_dir[${BASH_SOURCE-$0}]=$(dirname
"$__file__")}]-}${BASH_SOURCE-$0}]'

you can simply call

  source "$__dir__/xxx/yyy/libzzz.bash"

in each file intended to be sourced. The value of __dir__ always
reflects the location of the current script file. The names of the
variables can be adjusted to suit your taste.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]