【问题标题】:Terminal test command is not working as expected in Swift终端测试命令在 Swift 中没有按预期工作
【发布时间】:2015-12-23 11:06:18
【问题描述】:

当我在终端或作为 shell 脚本运行以下 shell 命令时:

test -f test.dmg && rm test.dmg

输出:如果当前目录中存在 test.dmg,则删除它。

但是,在 swift 中运行相同的命令如下所示,它没有按预期工作:

#!/usr/bin/env xcrun swift
func shell(launchPath: String, arguments: [AnyObject] = []) -> String? {
        let task = NSTask()
        task.launchPath = launchPath
        task.arguments = (arguments as! [String])
        print(task.arguments)

        let pipe = NSPipe()
        task.standardOutput = pipe
        task.launch()

        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        let output = NSString(data: data, encoding: NSUTF8StringEncoding)
        print(output)
        return (output as! String)
    }

    let arguments = ["test", "-f", "test.dmg", "&&", "rm", "test.dmg"]
    shell("/bin/sh", arguments)

使用 swift 输出:test: test: is a directory

有人可以帮忙吗?

【问题讨论】:

  • 当前目录下是否有目录test?您是否应该使用-c 标志(然后将实际命令作为单个字符串参数传递给-c 标志)?
  • @EtanReisner 是的,我在当前目录中有测试文件夹。但是,尽管我需要将完整的命令作为单个字符串参数传递,但这个 -c 标志起到了作用。谢谢:)
  • 是的,我就是这么说的。

标签: swift macos shell cocoa


【解决方案1】:

这里有两个问题。

错误的原因是因为您在当前目录中有一个test 目录,并且(由于第二个错误)shell 试图将其作为脚本执行但失败了。

第二个错误是你没有将命令传递给 shell 以直接作为独立参数运行。

那是你不要这样做:

/bin/sh test -f test.dmg && rm test.dmg

您所做的是使用-c 标志到shell 并将整个 命令作为单个字符串传递给它:

/bin/sh -c 'test -f test.dmg && rm test.dmg'

这会让你的代码变成这样:

let arguments = ["-c" "test -f test.dmg && rm test.dmg"]
shell("/bin/sh", arguments)

【讨论】:

  • 是的,正确的。按照你的建议,我也是这样做的。谢谢
猜你喜欢
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 2012-03-14
  • 2023-03-17
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多