Ammonite icon indicating copy to clipboard operation
Ammonite copied to clipboard

Ability to know easily the directory where the script is located

Open DavidPerezIngeniero opened this issue 2 years ago • 1 comments

Curretnly this is possible with the help of bash, but I find it cumbersome. Withi thsi trick, the 1st argument is the path. This is valid if the script has several entry points:

#!/bin/bash
  cmd=$1
  shift
	exec amm "$0" $cmd "$(cd `dirname "${BASH_SOURCE[0]}"` && pwd)" "$@"
!#

If it has only one entry point:

#!/bin/bash
	exec amm "$0" "$(cd `dirname "${BASH_SOURCE[0]}"` && pwd)" "$@"
!#

I like to have an Ammonite built-in to obtain this data. I use it to locate resources relative to the current script.

DavidPerezIngeniero avatar Jun 20 '22 08:06 DavidPerezIngeniero

Hi, you can get absolute source code path by sourcecode.File() as String. For convenience, os.Path(sourcecode.File()) will return Path class from os-lib (You don't need to declare dependency because os-lib is built in library).

And also, you can retrieve directory path via os.Path(sourcecode.File() / os.up

example

@main
def main() = {
  val p = os.Path(sourcecode.File())
  println(s"script file: $p")
  println(s"script directory: ${p / os.up}")
}

cf. #493

windymelt avatar Sep 27 '22 09:09 windymelt