Why is ls ~ or ls $ HOME not working in the process?

I am using Process to call shell (zsh), I want cd ~ or some other directory like cd $ PROJ_ROOT which is defined in the shell. But it looks like this token cannot be processed. How to solve this?

scala> import scala.sys.process._
import scala.sys.process._

scala> "ls ~".!!
ls: ~: No such file or directory
java.lang.RuntimeException: Nonzero exit value: 2
  at scala.sys.package$.error(package.scala:27)
  at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.slurp(ProcessBuilderImpl.scala:132)
  at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang$bang(ProcessBuilderImpl.scala:102)
  ... 33 elided

      

+3


source to share


2 answers


Tilde expansion (as well as globulation, parameter expansion, etc.) is done by the shell. Starting a process does not invoke a shell, so no replacement is performed.

The only way to achieve this is to invoke the shell yourself:



Seq("/bin/sh", "-c", "ls ~").!!

      

Edit: My original suggestion "/bin/sh -c ls ~"

doesn't actually work, since it will always list the current directory and ignore the tilde argument. Splitting the command line as a sequence as shown above seems to be a safe way to achieve this.

+8


source


you can access the environment variable with System.getenv("YOURVAR")

, so in your case you can do something like this



scala> import scala.sys.process._
import scala.sys.process._

scala> val home = System.getenv("HOME")
home: String = /home/user1

scala> s"ls $home".!!
val res0: String = ....

      

+2


source







All Articles