scriptingammonite

How to know the directory where the current script lies


When writing a script, I'd like to know where lies the current script, in order to locate other files.

With a regular Scala script, I know how to do so, but with an Ammonite script I don't.


Solution

  • Instead of the standard bang line I normally use:

    #!/usr/bin/env amm
    

    I changed my script to:

    #!/bin/bash
        exec amm "$0" `dirname "$0"` "$@"
    !#
    
    @main
    def main(dir: String) {
        print(dir)
    }
    

    The dir argument receives the path where the script lies. It can be absolute or relative.

    If we always desire an absolute path:

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