On Mon, 8 Jul 2024, 05:23 alex xmb sw ratchev, <fxmb...@gmail.com> wrote:
> i dont get the BASH_SOURCE[n] one > the point of prefix $PWD/ infront of relative paths is a static part of > fitting into the first lines of the script , assigning vars > That's not the only use case. Consider where you have a script that uses two independently written libraries, each comprising a main and number of ancillary files. Each library is installed in its own directory, but that directory isn't encoded into the library. The standard advice would be to add both directories to PATH (or some stand-in such as BASH_SOURCE_PATH), however remember, these are independently written libraries, and the same filename could be used for files in both libraries, or the "main" script. By far the most straightforward way to avoid this problem is to source files using paths relative to (the directory containing) the file containing the "." or "source" statement itself. But there is no fully general, portable, and reliable ways to do this, since: * "${BASH_SOURCE[0]}" might be a relative path based on somewhere in PATH rather than $PWD, or relative to a different $PWD that's been outdated by cd ; * "${BASH_SOURCE[0]}" might be a symbolic link into a different directory; * The directory containing any given file might be unreachable from the root directory (because of filesystem permissions, process restrictions (SELinux contexts and equivalents on other OSes), version shadowing, mount shadowing, soft unmounting, mount namespaces, and probably numerous other reasons I haven't thought of). While some of these are intractable, Bash itself at least has a better chance of getting it right than having to embed screeds of boilerplate code in every "portable" script. (The more portable/reliable the boilerplate solution is, the larger and more complex it is, and if it involves realpath, the slower it gets.) It's not possible to change "${BASH_SOURCE[@]}" without breaking some existing code, which leaves us with some kind of explicit opt-in such as: # 1. mark the source command itself source -r file_in_same_dir.bash # 2. Change the default behaviour via shopt/-O #!/bin/bash -Orelsource source file_in_same_dir.bash # 3. set all the forward compat options by controlling argv[0] #!/bin/bash7 source file_in_same_dir.bash Or else we could use a new variable such as "${BASH_SOURCE_DIR[@]}" to hold the normalized directories (and they're slightly less work than normalizing the whole path and then discarding the last component). Whatever solution is chosen, I would like it to be easier for a script author to do the right thing than to do the wrong thing. And all the better if it could quietly fix the myriad scripts out there that assume [[ ${0%/*} -ef . ]]. -Martin