如何在Mac OS X中创建自己的“shell”命令行程序

4

我想知道如何用Swift和Xcode创建自己的命令行或shell程序,类似于"cat"、"git"等。

例如:

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

谢谢!

1个回答

4
最简单的方法可能是以下步骤:
  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

完成。

一旦您理解了这些步骤,就可以自由地探索。例如,我在http://practicalswift.com/2014/06/07/swift-scripts-how-to-write-small-command-line-scripts-in-swift/上找到了一个很好的第一个教程。我发现那里唯一过时的信息是Swift程序的第一行应该如我在第5点中详细说明的那样(不要在行末加上“-i”)。

祝玩得开心!


谢谢,是否可以为./myFirstProgram.swift添加别名,以便例如键入“awe”来启动程序? - user5196496
在我的电脑上,我不熟悉 "awe" 这个程序。由于你在问题中提到了 "cat" 和 "git",你可能是指 "awk",这意味着我应该解释一些东西:这些命令就像 "myFirstProgram.swift" 一样都是程序。"cat" 显示文件的内容,"git" 是一个版本控制程序,"awk" 类似于编程语言。如果你首先输入这些关键字,那么其他所有内容都将成为该命令的参数(例如,"git clone ..." 意味着 "git" 是命令,"clone ..." 是参数)。祝好运! - barceloco
PS:如果你对这些东西感兴趣,我建议你完成几个Python教程。我相信上述概念会变得更加清晰。享受吧! - barceloco
抱歉造成误解,我的意思是我想创建自己的 shell 命令,例如 git、cat、ls、mkdir 等等。这样当我想要在终端中使用我的程序时,我可以使用自定义的名称,例如:$rod -h "doworknow"。 - user5196496
如果您将工作目录添加到path中,您只需编写myFirstProgram.swift。如果您真的想这样做,甚至可以将myFirstProgram.swift重命名为rod,然后您可以编写rod-whatever youDecide。请参考我发送给您的链接。干杯! - barceloco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接