使用执行位运行 CLI php 脚本
这让我有点烦恼。
我知道你可以做
php foo.php
或者
php -f foo.php
没有办法只启动一个设置了执行位的脚本
./foo.php
给定以下内容:
#!/usr/bin/php
<?php
exit('hello');
我得到“无法打开输入文件”或“错误的解释器:没有这样的文件或目录”,具体取决于后面是否有空格“bin/php”。
This has been bugging me slightly.
I know you can do
php foo.php
or
php -f foo.php
Is there no way to just launch a script with the execute bit set
./foo.php
Given the folowing:
#!/usr/bin/php
<?php
exit('hello');
I get "Could not open input file" or " bad interpreter: No such file or directory" depending on if there's whitespace after "bin/php".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
#!/usr/bin/env php
代替#!/usr/bin/php
是更好的解决方案。这将在PATH
环境变量中查找 PHP 二进制文件。这更加更加强大并且更可靠。跨平台。例如,BSD 将 PHP 安装在/usr/local/bin/php
中。此外,您需要确保这是第一行,并且脚本设置了可执行位,以便为每个人设置它(通常可以)使用:
chmod a+x script .php
另外请确保您已启用 CLI SAPI。运行 php -v top verify,它应该显示如下内容:
Instead of
#!/usr/bin/php
, using#!/usr/bin/env php
is a better solution. This will look up the PHP binary in thePATH
environment variable. This is much more robust & crossplatform. BSD for example installs PHP in/usr/local/bin/php
.Further, you will need to make sure this is the first line, and that the script has the executable bit set, to set it for everyone (Generally OK) use:
chmod a+x script.php
Also make sure you have the CLI SAPI enabled. Run
php -v
top verify, it should show something like:您给出的示例代码看起来不错并且适合我(不过我添加了结束
?>
)如果您可以使用
/usr/bin/php foo.php 运行该文件
发生了一些奇怪的事情。只是一个大胆的猜测,但也许您的文本编辑器在文件的开头留下了 BOM(字节顺序标记),因此#!
不是该文件中的前两个字节。 (您可以通过执行hexdump -C foo.php | head
找到)The example code you've given seems OK and works for me (I added the the closing
?>
though)If you can run the file with
/usr/bin/php foo.php
there's something weird going on. Just a wild guess, but maybe you text editor leaves a BOM (byte order mark) at the beginning of the file, so that the#!
aren't the very first two bytes in that file. (you can find out by doinghexdump -C foo.php | head
)来自
php(1)
联机帮助页:所以,shebang 方法确实有效。如果我在 Vim 中将行结尾设置为“unix”以外的内容,则会收到“:没有这样的文件或目录”。您在脚本中使用 DOS 行结尾吗?
From the
php(1)
manpage:So, the shebang method does work. I'm getting ": No such file or directory" if I set line endings to something other than "unix" in Vim. Are you using DOS line endings in your script?