How to execute a shell from Scala

I need to check some system settings like ulimit -n from Scala script on Linux. If I were dealing with regular commands, I would use the scala.sys.process package, for example:

 import scala.sys.process._ println("ls -lha".!!) 

Unfortunately, this does not work for embedded shells. Is there a way to catch the output from a shell built into Scala?

Update:

I tried the usual sh -c "ulimit -n" trick in several forms with no luck; All commands below:

 "sh -c 'ulimit -n'".!! "sh -c \"ulimit -n\"".!! """sh -c "ulimit -n"""".!! """sh -c "ulimit -n """ + "\"".!! 

And I get a runtime error in REPL:

 -n": 1: Syntax error: Unterminated quoted string java.lang.RuntimeException: Nonzero exit value: 2 at scala.sys.package$.error(package.scala:27) at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.slurp(ProcessBuilderImpl.scala:131) at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang$bang(ProcessBuilderImpl.scala:101) at .<init>(<console>:11) at .<clinit>(<console>) at .<init>(<console>:11) at .<clinit>(<console>) at $print(<console>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704) at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920) at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43) at scala.tools.nsc.io.package$$anon$2.run(package.scala:25) at java.lang.Thread.run(Thread.java:722) 
+7
source share
2 answers

When strings are converted to shell commands, the parameters are separated by a space. The conventions you tried are shell conventions, so you need a shell to apply them.

If you need more control over each parameter, use Seq[String] instead of String or one of the Process factories that are the same. For example:

 Seq("sh", "-c", "ulimit -n").!! 
+10
source

Using

 println( Process("sh", Seq("-c","ulimit -n")).!! ) 

to mimic what the shell usually does when you type sh -c 'ulimit -n' . That is, the sh command and the arguments -c and ulimit -n .

+4
source

All Articles