为什么这个命令的行为会有所不同,具体取决于它是从terminal.app还是scala程序调用的?

时间:2016-06-26 21:27:43

标签: bash scala compression

所以我正在提取一个file.cbz来显示它的内容。

我希望用以下代码来解决这个问题:

println("7z x -y \"" + filePath + "\"" + s" -o$tempLocation")
         if (("7z x -y \"" + filePath + "\"" + s" -o$tempLocation").! == 0){ //I would have liked to do the whole thing with string interpolation, but I didn't work. Seems to be this bug https://issues.scala-lang.org/browse/SI-6476
             Some(new File(tempLocation))
         }else{
         println("Something went wrong extracting the file, probably an incorrect path. Path: " + filePath)
         null
     }

当我编译并运行它时,我得到以下输出:

7z x -y "/path/to/file/test.cbz" -o/tmp/CViewer-temporary-storage

ERROR: No more files
"



System ERROR:
Unknown error: -2147024872

7-Zip [64] 15.14 : Copyright (c) 1999-2015 Igor Pavlov : 2015-12-31
p7zip Version 15.14.1 (locale=utf8,Utf16=on,HugeFiles=on,64 bits,4 CPUs x64)

Scanning the drive for archives:
Something went wrong extracting the file, probably an incorrect path. Path: /Users/Matt/learning-scala/learning-GUI/test.cbz

Process finished with exit code 0

当我在terminal.app中运行命令时,它运行正常,我得到以下内容:

Matt$ 7z x -y "/Users/Matt/learning-scala/learning-GUI/test.cbz" -o/tmp/CViewer-temporary-storage

7-Zip [64] 15.14 : Copyright (c) 1999-2015 Igor Pavlov : 2015-12-31
p7zip Version 15.14.1 (locale=utf8,Utf16=on,HugeFiles=on,64 bits,4 CPUs x64)

Scanning the drive for archives:
1 file, 19587584 bytes (19 MiB)                   

Extracting archive: /path/to/file/test.cbz
--
Path = /path/to/file/test.cbz
Type = Rar
Physical Size = 19587584
Solid = -
Blocks = 33
Multivolume = -
Volumes = 1

Everything is Ok 

Files: 33
Size:       20400561
Compressed: 19587584

这似乎是7z被告知提取空目录时的结果。

1 个答案:

答案 0 :(得分:2)

您似乎认为Scala支持类似Bash的语法和unquoting规则。据我所知,当您在ProcessBuilder上调用!时,Scala的String没有语法可以取消字符串。它似乎做的是在空白上天真地分裂然后执行那些作为你的命令。如果您不需要在命令中嵌入任何空格,或者插值变量从不包含空格,那么这很有效。

修复是使用Seq,以便您可以单独定义每个参数,而不必担心转义或转义。所以你执行行:

"7z x -y \"" + filePath + "\"" + s" -o$tempLocation").!

变为

Seq("7z", "x" "-y", filePath, s"-o$tempLocation").!

注意:根据脚本最佳实践,您应始终使用正在执行的命令的完整路径。对我来说,这将是:

Seq("/usr/local/bin/7z", "x" "-y", filePath, s"-o$tempLocation").!