CLOVER🍀

That was when it all began.

Groovyで現在実行しているスクリプトのパス、またはファイル名を取得する

小ネタです。Groovyで、現在実行中のスクリプトファイルのパスおよびファイル名を取得する方法です。

サンプルコード。
print_script_name.groovy

println("path => " + this.class.protectionDomain.codeSource.location.path)
println("fileName => " + new File(this.class.protectionDomain.codeSource.location.file).name)

実行結果。

$ groovy print_script_name.groovy 
path => /xxxxx/script-name/print_script_name.groovy
fileName => print_script_name.groovy

ClassクラスからProtectionDomainを抜き、そこから取れるCodeSourceが持っているlocationプロパティを取得します。あとは、欲しいパス情報をURLから取得しましょう。

こんな感じで。