In a script, we can use $env.FILE_PWD to get the script's location. However, this approach failed for sourced file, e.g.
main.nu:
source ./lib/func.nu
echo $"Script file: ($env.FILE_PWD)"
echo $"Sourced file: (get-sourced-file)"
./lib/func.nu:
export def get-sourced-file [] {
# this will return path of main.nu
# Is there command/env to retrieve path of func.nu?
$env.FILE_PWD
}
Output:
$ nu main.nu
Script file: /tmp/test
Sourced file: /tmp/test
Q: How to retrieve the sourced file path of /tmp/test/lib from within the lib/func.nu?
Nu is a compiled language, strictly separating the parsing of source code from its evaluation (see How Nushell Code Gets Run). Therefore, this path is known at compile time (when the sources are collected and parsed), but not at run time (when any code is evaluated and executed). But your
main.nualready contains the path relative to its own location, so just make this static string available, e.g. usingconst, to be used later in a dynamic context where it can be expanded, e.g. usingpath expand:Output: