Search code examples
swiftcommand-line-interfacezsh

How to run and print zsh commands in Swift Executables (like "vi")


I need to run commands that require dynamic output in my CLI made in Swift. I've tried things like ShellOut and other suggestions on Stack Overflow, but they print the output once the command is done, not while it is going.

What I'm hoping for is something like system("vi README.md") from C++, where it will run the command and print the outputs as it goes.

Without it, vi prints Vim: Warning: Output is not to a terminal then leaves a black screen and there is no way to exit the command.


Solution

  • Turns out, you can use the system() function for C++ in Swift!

    First, I created a new target in my package (to get past language mixing errors):

    .target(name: "CBridge", dependencies: []),
    

    Then, in the target's source folder, I put the following files:

    CBridge.cpp
    include/CBridge.h
    include/CBridge-Bridging-Header.h
    

    CBridge.cpp

    #include "include/CBridge.h"
    #include <iostream>
    using namespace std;
    
    void shellCMD(const char *cmd) {
        system(cmd);
    }
    

    CBridge.h

    #ifdef __cplusplus
    extern "C" {
    #endif
    
    void shellCMD(const char *cmd);
    
    #ifdef __cplusplus
    }
    #endif
    

    CBridge-Bridging-Header.h

    #include "CBridge.h"
    

    Simply call shellCMD(command) and it will run it, just like 'system(command)'!