macosswiftshellcommand-lineosx-yosemite

How to create my own "shell" command line program in Mac OS X


I wondering about how can I create my own command line or shell program like "cat", "git" etc... with Swift and Xcode?

For example:

rod -a "hello world!" 
rod --version
rod /list -e "bye world!"

Thanks in advance,


Solution

  • The easiest way to do this is probably the following:

    1. open a terminal window and navigate to the directory of your choice
    2. Create an empty swift file by entering the terminal command

      touch myFirstProgram.swift
    3. Make this file executable by entering the terminal command

      chmod +x myFirstProgram.swift
    4. Open this directory in finder by entering the terminal command

      open .
    5. Double-click on myFirstProgram.swift to open the empty file in Xcode. Then, inside Xcode, write the following lines into your first swift program. The first line starts the swift interpreter, anything after that is simple swift code.

      #!/usr/bin/env xcrun swift
      
      println("Hello world.")
      
    6. After saving your program, you can start this by entering the terminal command

      ./myFirstProgram.swift

    done.

    Once you have understood these steps, you can go out and explore freely. I found, for example, an excellent first tutorial at http://practicalswift.com/2014/06/07/swift-scripts-how-to-write-small-command-line-scripts-in-swift/. The only outdated information I found there was that the first line of the swift program should be as I detailed in point 5 (without a "-i" at the end of the line).

    Have fun!