execute shell internal commands from swift - swift

I am trying to execute shell commands from swift program. below is my program
func executeCommand(command: String, args: [String]) -> String {
let task = Process()
task.launchPath = command
task.arguments = args
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
return output
}
When I use the path as /bin and try to execute ls command it works and prints the output. but when i try to run
executeCommand(command: "export DEVELOPER_DIR=\"/Applications/Xcode.app/Contents/Developer/\"", args: [""])
it is not working. I tried to find the location of export but terminal says it is inbuilt. How do i execute the export DEVELOPER_DIR from my swift program?

Related

Open an http tunnel through a shell script programmatically in swift

I am trying to open either an Ngrok or Localtunnel as part of my swift program by using shell scripts. The problem is as neither shell script has a return, my main thread hangs. I could put it in a side thread that's permanently open, but I need to extract the url that gets outputted. Any ideas?
For reference this is how I am executing shell commands in swift.
func shell(_ command: String) -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.arguments = ["-c", command]
task.launchPath = "/bin/zsh"
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
return output
}
followed by either
shell("ngrok http 3000")
or
shell("lt --port 9726")

Running shell commands in a swift script

I am looking for a solutuion to run shell commands in a Swift script.
Here is my code:
func shellEnv(_ command: String) -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.arguments = ["-c", command]
task.launchPath = "/bin/zsh"
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
return output
}
It works with built-in commands but it cannot deal with commands like "brew", "node" and other commands that were installed manually.
So how can I solve it?
You need to set the PATH environment variable for the task. This has been set in your terminal, which is why you are able to do brew and node and other cool things directly, without specifying their full path.
You can see what this is set to in your terminal by doing:
echo $PATH
and it will print something like (for me it has a bunch more things. This is only an excerpt):
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
If you copy and paste the entire output of echo $PATH, and put it into the environment property of task, then you will be able to use the same commands in your swift script as in your terminal.
task.environment = ["PATH": "<paste the output here>"]
As Alexander said in the comments, another way is to add the l option. Here is a MCVE:
#!/usr/bin/swift
// main.swift
import AppKit
func shellEnv(_ command: String) -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.arguments = ["-cl", command]
task.launchPath = "/bin/zsh"
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
return output
}
print(shellEnv("brew list")) // assuming you have brew
To run, chmod +x main.swift then ./main.swift, and you will see all your homebrew packages listed.

macOS Swift Launch Location Not Accessible

I want to execute the following shell command from my macOS app:
/Users/macuser/Desktop/videos/ffmpeg -i /Users/macuser/Desktop/videos/vid1.mov -vf fps=1/1 /Users/macuser/Desktop/videos/images/out%0d4.jpg
The method I'm using to do this is:
func shell(_ launchPath: String, _ arguments: [String]) -> String?
{
let task = Process()
task.launchPath = launchPath
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8) ?? ""
task.waitUntilExit()
return output
}
I am passing the arguments to the method like this:
let command = ffmpegLocation
let arguments = [
"-i",
videoLocation,
"-vf",
"fps=1/1",
"\(outputLocation)/out%0d4.jpg"
]
resultsField.stringValue = shell(command,arguments)!
What I get is "launch path is not accessible". I have verified the command does work in Terminal. Do I need to use a different approach?

How to show real time result while using terminal command in a swift script

I am using Xcode Project Renamer to rename my Xcode project, after that I used the code below to install pod file.
It's working good but the terminal showing result after pod installed. I want to show result while installing the pod.
#discardableResult
private func shell(_ command: String) -> String {
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
// pipe.fileHandleForReading.readDataToEndOfFile()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
return output
}
let command = shell("pod install")
print(command)
Can someone help please.

How to use Process() in Swift 3 for Linux?

The following function executes a process in Swift 3 on macOS. But if I run the same code in Ubuntu I get the error that Process is an unresolved identifier.
How do I run a process / task in Swift 3 for Ubuntu and get its output?
import Foundation
// runs a Shell command with arguments and returns the output or ""
class func shell(_ command: String, args: [String] = []) -> String {
let task = Process()
task.launchPath = command
task.arguments = args
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String? = String(data: data,
encoding: String.Encoding.utf8)
task.waitUntilExit()
if let output = output {
if !output.isEmpty {
// remove whitespaces and newline from start and end
return output.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
return ""
}
I cannot test it myself currently, but according to the source code
https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSTask.swift,
the corresponding class is (still) called Task on Linux, not Process
as on Apple platforms.