操作演示

启动scala

1
2
docker run --rm -it hseeberger/scala-sbt:11.0.3_1.2.8_2.13.0 bash
scala -language:postfixOps

命令里面不能直接用管道或重定向符号
需要用#来拼接

报错解决

scala代码中如果使用 !执行命令时, 会有一段警告

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
scala> import scala.sys.process._
import scala.sys.process._

scala> "ls -lh /bin/cp" !
<console>:15: warning: postfix operator ! should be enabled
by making the implicit value scala.language.postfixOps visible.
This can be achieved by adding the import clause 'import scala.language.postfixOps'
or by setting the compiler option -language:postfixOps.
See the Scaladoc for value scala.language.postfixOps for a discussion
why the feature should be explicitly enabled.
       "ls -lh /bin/cp" !
                        ^
-rwxr-xr-x 1 root root 128K Feb 22  2017 /bin/cp
res2: Int = 0

启动scala时 加个参数 -language:postfixOps
如已经启动了 可以 import scala.language.postfixOps
警告提示就没有了

使用管道

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
scala> "cat /etc/passwd" #| "grep /bin/bash" #| "wc -l" !
2
res0: Int = 0

scala> "ls /usr" #| "wc -l" !
8
res7: Int = 0

scala> val fileNum = "ls /usr" #| "wc -l" !!
fileNum: String =
"8
"

scala> println(s"文件数量为: $fileNum")
文件数量为: 8

整理后

1
2
3
4
"cat /etc/passwd" #| "grep /bin/bash" #| "wc -l" !
"ls /usr" #| "wc -l" !
val fileNum = "ls /usr" #| "wc -l" !!
println(s"文件数量为: $fileNum")

重定向

重定向可以支持文件对象

1
2
3
4
5
scala> new java.net.URL("http://www.baidu.com") #> new java.io.File("/tmp/baidu.html") !
res3: Int = 0

scala> root@a466b854e61f:~/hexdump# ls /tmp/baidu.html
/tmp/baidu.html