Get current sourced script location in Nu shell

81 Views Asked by At

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?

1

There are 1 best solutions below

0
pmf On

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.nu already contains the path relative to its own location, so just make this static string available, e.g. using const, to be used later in a dynamic context where it can be expanded, e.g. using path expand:

# ./main.nu

const libpath = './lib'
source $"($libpath)/func.nu"

# unchanged rest of the file:
echo $"Script file:  ($env.FILE_PWD)"
echo $"Sourced file: (get-sourced-file)"
# ./lib/func.nu

export def get-sourced-file [] {
  $libpath | path expand
}

Output:

$ nu main.nu
Script file:  /tmp/test
Sourced file: /tmp/test/lib