将参数传递给从 sh 脚本中调用的 php 脚本的问题

Problems with passing arguments to php scripts called from within sh scripts

我有以下 .sh 文件:

#!/bin/bash
php -f /test_folder/test.php dosomething
echo "test string"

var_dump($_SERVER['argv']) 里面 test.php returns 这个:

array(2) {
 [0]=>
  string(31) "/test_folder/test.php"
 [1]=>
  " string(12) "dosomething
}

这是有问题的,因为 " string(12) "dosomething 部分。引号不正确,参数被脚本错误地解析。

当我从 sh 文件中删除 echo "test string" 并再次 运行 时,我正确地得到了 string(11) "dosomething"。问题似乎是 php 行之后的换行符。 我在 Windows 上使用 Notepad++,编码是 UTF8 - 这些都会有问题吗?

如何在不破坏脚本的情况下换行?

您的问题是 Windows-style \r\n (CRLF) 行尾在您的 bash 脚本 - 可能只是 one,即包含 php 调用的行。[1]

我怀疑当您稍后将行 echo "test string" 添加到脚本时,您使用了与最初创建脚本时使用的不同的编辑器(或不同配置的编辑器)。

验证是否存在带有 cat -et script.sh 的 Windows 行结尾:如果您在输出中看到 ^M$,那么您确实有它们。

要解决此问题:

  • 将您的 *.sh 脚本转换为 Unix \n-only line endings,然后重试;你有几个选择:

    • 使用实用程序 dos2unix,如果您安装了它(可以通过许多平台的包管理器获得)。
    • 使用标准实用程序,例如 awk;例如:
      awk '{ sub("\r$", ""); print } script.sh > script-fixed.sh
    • 看看 Notepad++ 是否可以将现有文件转换为 Unix 行尾。
      • 更新:@Alan(OP)报告行尾可以通过Edit > EOL Conversion菜单项set/converted。
  • 以后,请确保您的编辑器在编辑 Unix shell 脚本时使用 Unix 风格的行结尾。


[1] 如果 all 行有 Windows 行结尾,则 shebang 行将不起作用,并且调用您的脚本 - 假设它被标记为可执行文件并直接调用 - 会因 /bin/bash^M: bad interpreter: No such file or directory

而根本失败