I am creating a Swift package that has an executable that will run commands via Process
. Some of these commands will require user input, such as sudo
.
How can I ensure that the commands output is shown to the user, and also allow them to interact with the commands, such as typing in their password for sudo
?
I have a few ways of running the command, which all fail in different ways:
public func run(_ command: [String]) throws {
try Process.run(URL(fileURLWithPath: "/usr/bin/env"), arguments: command) { process in
print("Process terminated", process)
}
}
Fails without user input:
Password:
sudo: unable to read password: Input/output error
I've also tried:
public func run(_ command: [String]) throws {
let process = Process()
process.launchPath = "/usr/bin/env"
process.arguments = command
let standardError = Pipe()
process.standardError = standardError
print("Running \(command.joined(separator: " "))")
try process.run()
process.waitUntilExit()
if process.terminationStatus != 0 {
let errorData = standardError.fileHandleForReading.readDataToEndOfFile()
let error = String(data: errorData, encoding: .utf8)!
throw CommandError(message: error, exitCode: process.terminationStatus)
}
}
which will output Running sudo [command...]
and stall until ctrl+C is pressed, at which point the process exits and Password:
is output:
Running sudo [command...]
^CPassword:
Not setting process.standardError
does the same, but outputs:
Running sudo [command...]
^CPassword:
sudo: unable to read password: Input/output error
I've come across similar questions asking about running commands with sudo
via a GUI application, but I am trying to do this via an executable.
I'm assuming I need to pass stdin
somehow, but the documentation for standardInput
on Process
states If this method isn’t used, the standard input is inherited from the process that created the receiver
so I'm not sure why it's not working.