2017-04-06 114 views
2

我試圖從用Swift編寫的Mac應用程序執行「history」命令。Swift進程 - 執行命令錯誤

@discardableResult 
func shell(_ args: String...) -> Int32 { 
    let task = Process() 
    task.launchPath = "/bin/bash" 
    task.arguments = args 
    task.launch() 
    task.waitUntilExit() 
    return task.terminationStatus 
} 

shell("history") 

,它總是返回我這個錯誤:

env: history: No such file or directory 

有什麼不對?真的有可能從Mac App使用用戶命令行歷史記錄?

回答

1

使用某些內建有NSTaskGNU命令(這被認爲是「互動」像history)通常需要環境變量設置爲使殼知道返回什麼,例如:

private let env = NSProcessInfo.processInfo().environment 

這可能很困難因爲並不是所有的用戶顯然都使用相同的環境變量或shell。另一種方法是在NSTask不需要獲得對使用bash命令/設置環境:

let task = Process() 
task.launchPath = "/bin/bash" 
task.arguments = ["-c", "cat -n ${HOME}/.bash_history"] 

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

let data = pipe.fileHandleForReading.readDataToEndOfFile() 
let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue) 

print(output!) 

輸出結果應該類似於實際殼歷史的編號格式。

+0

在同一個腳本中,我如何導出日期? 「export HISTTIMEFORMAT = \'%m /%d - %H:%M:%S:\'」返回相同的'沒有這樣的文件或目錄' – Marco

1

history命令是一個內部bash命令。因此,正確的語法是:

$ bash -C history 

在你shell功能:

task.arguments = ["-C"] + args 
+0

它返回相同的錯誤 – Marco

+0

@Marco有一個錯字...請現在再試一次。 –