2012-04-08 76 views
12

我想了解这个斯卡拉脚本是如何工作的:在sh/Bash shell脚本中,##(bang-pound)是什么意思?

#!/usr/bin/env bash 
exec scala "$0" "[email protected]" 
!# 
object HelloWorld { 
    def main(args: Array[String]) { 
     println("Hello, world! " + args.toList) 
    } 
} 
HelloWorld main args 

在第3行,什么是 “#!” 在干什么?然后将文件的剩余部分提供给Scala程序的standard input?另外,'!#'记录在任何地方?

NB:我能找到最近的事情,虽然这是不以任何方式直接相关的是堆栈溢出问题Why do you need to put #!/bin/bash at the beginning of a script file?(约Bash脚本的开始)。

+2

Windows版本的这个问题:http://stackoverflow.com/questions/6671913/scala-scripts-in-windows-batch-files – 2012-04-08 22:58:14

回答

18

the original documentation

Script files may have an optional header that is ignored if present. There are two ways to format the header: either beginning with #! and ending with !#, or beginning with ::#! and ending with ::!#.

所以下面的代码仅仅是一个斯卡拉脚本头:

#!/usr/bin/env bash 
exec scala "$0" "[email protected]" 
!# 
+0

不错。那么在“!#”后面的脚本内容会发生什么? – 2012-04-08 04:51:05

+4

Scala运行它。 'exec'内建使得'scala'解释器*替换外壳,所以bash从不会看到'!#'行。 'scala'会忽略'#!'和'!#'之间的所有内容。 – cHao 2012-04-08 04:51:56

+0

我认为这是它的工作原理,但我无法在任何地方找到它的文档。谢谢! – 2012-04-08 05:02:13

2

当我在示例程序中BluesRockAddict's answer删除!#,我得到以下错误在控制台:

error: script file does not close its header with !# or ::!# one error found

从t他上面的错误信息,我明白了以下几件事:

  1. !#是头exec scala "$0" "[email protected]",这可能会告诉斯卡拉,无论来自后!#是要执行的Scala代码的结束标记。
  2. !#可替换为::!#
2

纯粹基于实验(我想这是什么地方描述):(#!)

使用Scala 2.10.0开始,非标(从POSIX脚本POV)磅砰没有在POSIX shell环境中需要更长时间(或允许)。下面一行的作品(但必须在脚本的第一行,没有前导空格):

#!/usr/bin/env scala 

然而,为了提供一个窗口批处理文件认领的唯一方法是将其诱骗到调用斯卡拉本身就是第一个论点。因此,Scala需要知道批处理文件最后一行的位置,因此需要使用closing ::!#行。这里有一个工作示例:

::#! 
call scala %0 %* 
goto :eof 
::!# 

更正:我本来#在/ usr/bin中/ env的scalav(注意尾随V),这是我的脚本,定义属性 “scala.script”,添加一些库! classpath,在'exec scala'之前。这样就可以确定正在执行的脚本的名称,尽管scalav必须位于PATH中。

相关问题