完整示例:
- 转到某个目录,比如说
Desktop
- 创建一个名为
swsh 的文件,并添加到其中(纯文本,而不是 rtf 或 doc)
#!/usr/bin/env xcrun swift
import Foundation
func shell(launchPath: String, arguments: [String]) -> String {
let process = Process()
process.launchPath = launchPath
process.arguments = arguments
let pipe = Pipe()
process.standardOutput = pipe
process.launch()
let output_from_command = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: String.Encoding.utf8)!
// remove the trailing new-line char
if output_from_command.characters.count > 0 {
let lastIndex = output_from_command.index(before: output_from_command.endIndex)
return output_from_command[output_from_command.startIndex ..< lastIndex]
}
return output_from_command
}
let output = shell(launchPath: "/bin/date", arguments: [ ])
print(output)
保存,然后:
- 打开终端
- 输入
cd ~/Desktop
- 使用
chmod 755 swsh
- 并运行
swift script 为:./swsh
你会得到如下输出:
Sat Mar 25 14:31:39 CET 2017
编辑您的swsh 并将shell(... 行更改为:
let output = shell(launchPath: "/usr/bin/env", arguments: [ "date" ])
再次运行它会得到日期,但是现在:
-
swsh 执行了/usr/bin/env,(带有参数date)
- 和
/usr/bin/env 找到命令date
- 并执行它
现在,在~/Desktop 中创建另一个文件并将其命名为from_swift。
添加进去
echo "Today's date is $(date)"
更改文件swsh 将shell 行更改为:
let output = shell(launchPath: "./from_swift", arguments: [ ])
注意,./from_swift - 使用. 的相对路径(我们在~/Desktop 目录中)。运行 swift 程序:
./swsh
输出:
2017-03-25 14:42:20.176 swift[48479:638098] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'launch path not accessible'
当然,脚本from_swift 还不是可执行文件。所以执行:
chmod 755 from_swift
# and run
./swsh
又报错了:
2017-03-25 14:45:38.523 swift[48520:639486] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Couldn't posix_spawn: error 8'
这是因为from_swift 是一个脚本(不是编译后的二进制文件),所以操作系统需要知道哪个二进制文件应该解释脚本内容。因为这是 shell script,所以将 from_swift 脚本编辑为:
#!/bin/sh
echo "Today's date is $(date)"
注意添加的“shebang”行:#!/bin/sh。运行 swift ./swsh 会得到
Today's date is Sat Mar 25 14:50:23 CET 2017
Horay,你从swift 执行了你的第一个bash 脚本。 ;)
当然你可以在shebang中使用/usr/bin/env,所以现在把from_swift的内容改成:
#!/usr/bin/env perl
use strict;
use utf8;
use English;
binmode STDOUT, ":utf8";
printf "The $EXECUTABLE_NAME (ver:$PERL_VERSION) runs me: $0\n";
printf "I ❤️ perl!\n";
运行./swsh 会得到:
The /usr/bin/perl (ver:v5.18.2) runs me: ./from_swift
I ❤️ perl!
注意,我们在 ./swsh 文件中更改了 nothing,只更改了脚本文件 ./from_swift!
以上所有使用:
$ uname -a
Darwin nox.local 16.4.0 Darwin Kernel Version 16.4.0: Thu Dec 22 22:53:21 PST 2016; root:xnu-3789.41.3~3/RELEASE_X86_64 x86_64
$ swift --version
Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)
Target: x86_64-apple-macosx10.9
因此,很容易创建和执行任何脚本。所以,你可以输入你的~/Desktop/from_swift
#!/bin/sh
cd $HOME/Desktop/firebase-mac
npm start
可以直接从swsh 执行(Jens Meder 建议),但使用此方法,您可以轻松地执行给定脚本文件中的任何内容。
请记住:process.launch() 执行任一:
- 编译的二进制文件
- 或脚本文件,但脚本文件
-
必须有
shebang这一行
- 并且必须可以使用
chmod 755 /path/to/script.file 执行