0

I can't find an example of appending to an environment variable. For example, the code below completely replaces PATH. Could someone help me with appending, either directly or by showing me how to access the current PATH so that I can then modify itself and pass the fully-modified value to the Process

val out2 = Process("env", None, "PATH" -> "/usr/local/bin") 

1 Answer 1

4

There's:

scala> util.Properties.envOrNone("PATH") res0: Option[String] = Some(/home/apm/go1.1/go/bin:/home/apm/go/bin:/home/apm/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games) 

That is:

scala> util.Properties.envOrSome("PATH", Some("")) map (p => s"$p${new sys.SystemProperties()("path.separator")}/tmp") get warning: there was one feature warning; re-run with -feature for details res5: String = /home/apm/go1.1/go/bin:/home/apm/go/bin:/home/apm/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/tmp 

I just noticed my PATH has gone stale.

Edit for idiom:

scala> def appendToEnv(key: String, value: String) = util.Properties.envOrNone(key) match { | case Some(v) if v.nonEmpty => s"$v${System getProperty "path.separator"}$value" | case _ => value | } appendToEnv: (key: String, value: String)String scala> appendToEnv("PATH", "/opt") res0: String = /home/apm/go1.1/go/bin:/home/apm/go/bin:/home/apm/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/opt scala> appendToEnv("UNPATH", "/opt") res1: String = /opt 
Sign up to request clarification or add additional context in comments.

2 Comments

Woohoo, exactly what I needed. Funny you answered the other question on this topic too :-P
Life is funny. I added what I think is more idiomatic code. It also handles Some("") as edge case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.