【问题标题】:How to implement a script interpreter in shell on Mac OS X?如何在 Mac OS X 上的 shell 中实现脚本解释器?
【发布时间】:2014-09-19 17:49:40
【问题描述】:

我正在尝试在 shell 中实现一个可以在 shebang 行中使用的脚本解释器。例如,这是我的解释器和使用该解释器的测试脚本:

-----
$ cat interp
#! /usr/bin/env bash

printf "interp called with args: %s\n" "$*"

-----
$ cat test
#! ./interp

printf "test script!\n"

当我在 Linux 系统上运行 ./test 时,interp 会使用我期望的参数调用:

$ ./test -a
interp called with args: ./test -a

但是当我在 Mac OS X 10.8.4 上执行相同操作时,我得到以下结果:

$ ./test -a
test script!

test 脚本的内容由 bash 执行,而不是interp 脚​​本以test 文件作为第一个参数执行。

我这样做是否正确,这样的事情根本无法在 Mac OS X 上运行?或者有没有更好的方法来做到这一点?

【问题讨论】:

  • 在 OSX 10.6.8 上可以与 zsh 一起正常工作,但不能与 macports bash 一起工作。
  • Mac OS X 要求 shebang 中命名的程序是二进制可执行文件,而不是脚本,AFAICR。解决方法 anubhava 建议运行 /usr/bin/env(二进制可执行文件)并请求它运行您的脚本。

标签: macos shell shebang


【解决方案1】:

是的,有一种方法可以让它在 OSX 上运行,这与您在第一个脚本中所做的相同,即使用 /usr/bin/env

./test 设为:

#!/usr/bin/env ./interp

printf "test script!\n"

【讨论】:

  • 这确实比你有用。知道为什么我的第一次尝试没有成功吗? (如果我使用绝对路径而不是 #!./interp 也会失败)
  • 是的,它在 OSX 上也不适用于 interp 的完整路径。我仍在研究为什么 OSX 需要 /usr/bin/env 而 Linux 不需要。找到东西我会更新的。
【解决方案2】:

OS X 建立在 UNIX 之上。应用程序终端将您从 OS X 的外部世界带到 UNIX 的内部世界。终端位于 Applications 文件夹内的 Utilities 文件夹中。要打开终端,请双击终端图标,您会看到一个如图所示的窗口。

【讨论】:

    猜你喜欢
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2011-05-27
    • 2010-11-26
    • 2011-06-03
    • 2011-03-02
    相关资源
    最近更新 更多