Skip to content

Instantly share code, notes, and snippets.

@rbuckland
Last active February 6, 2019 16:10
Show Gist options
  • Save rbuckland/8c93241078b7fbac4751 to your computer and use it in GitHub Desktop.
Save rbuckland/8c93241078b7fbac4751 to your computer and use it in GitHub Desktop.
Ammonite Shell - Environment Output Odd Behaviour
/*
* Simple script to show / work out why environment variables are not passing through
* in some circumstances
*
* run this on a suitable "*nix" box like 'ARG=foobar amm environment-out.scala'
*/
import ammonite.ops._
import ammonite.ops.ImplicitWd._
def main() = {
// here is out environment variable
println("----------- " + sys.env("ARG"))
// these work
%(root/'bin/'bash, "-c", "echo '=========== '$ARG",ARG=sys.env("ARG"))
%(root/'bin/'bash, "-c", "echo ........... $ARG", ARG=sys.env("ARG"))
// remove (and ignore if not there)
%%(root/'bin/'rm, "debug-output.sh")
// create a simple "output dumper"
write(cwd/"debug-output.sh", "#!/bin/sh\necho $*\necho environment : ARG=$ARG\n")
%(root/'bin/'chmod, "755", "debug-output.sh")
// these don't
%(cwd/"debug-output.sh", "::::::::::: $ARG", ARG=sys.env("ARG"))
%(cwd/"debug-output.sh", "~~~~~~~~~~~ ", "$ARG", ARG=sys.env("ARG"))
// the right way to do it
val someString = "this is my ARG=${ARG} string"
val varRegex = """(\$\{(\w+)\})""".r
val expanded = varRegex.replaceAllIn(someString,a => s"${sys.env(a.group(2))}")
%(cwd/"debug-output.sh", "√√√√√√√√√√√ ", expanded)
}

this is the example output from running the above scala script with ARG=foobar amm environment-out.scala

----------- foobar
=========== foobar
........... foobar
::::::::::: $ARG
environment : ARG=foobar
~~~~~~~~~~~ $ARG
environment : ARG=foobar
√√√√√√√√√√√ this is my ARG=foobar string
environment : ARG=foobar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment