2012-04-08 79 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中。

相關問題