文件系统权限
在您的情况下,脚本可能由于file system permissions 不足而未执行。在Linux中,如果文件为当前用户或用户组设置了可执行位,则只需写入文件路径即可执行文件,例如:
~/scripts/abc.php
./script.sh
否则,您应该将文件作为参数传递给适当的程序,例如:
php ~/scripts/abc.php
/usr/bin/php ./script.php
bash ./script.sh
您可以使用ls或stat命令检查文件系统权限,例如:
$ stat --format='perm: %A | user: %U | group: %G' 1.sh
perm: -rwxr-xr-x | user: ruslan | group: users
$ ls -l 1.sh
-rwxr-xr-- 1 ruslan users 1261 Nov 26 11:47 1.sh
在上面的示例中,为用户ruslan 和组users 设置了可执行位,但未为其他人 (r--) 设置可执行位。其他人只能读取 (r) 文件,但不能执行或写入文件。
要设置可执行位,请使用chmod 命令,例如:
# For the user
chmod u+x file.sh
# For the group
chmod g+x file.sh
更好地控制命令执行
shell_exec 函数返回写入标准输出描述符的内容。如果命令不打印任何内容或失败,则返回NULL。例如:
$out = shell_exec("ls -l inexistent-file");
var_dump($out); // NULL
因此,您无法很好地控制 shell_exec 的错误情况。我建议改用prop_open:
$cmd = 'ls -l 1.sh inexistent-file';
// Descriptors specification
$descriptors = [
1 => ['pipe', 'w'], // standard output
2 => ['pipe', 'w'], // standard error
];
// Open process for the command
$proc = proc_open($cmd, $descriptors, $pipes);
if (!is_resource($proc))
die("failed to open process for $cmd");
if ($output = stream_get_contents($pipes[1])) {
echo "output: $output\n";
}
fclose($pipes[1]);
if ($errors = stream_get_contents($pipes[2])) {
fprintf(STDERR, "Errors: %s\n", $errors);
}
fclose($pipes[2]);
// Close the process
if (($status = proc_close($proc)) != 0)
fprintf(STDERR, "The command failed with status %d\n", $status);
射帮
考虑将shebang 用于可执行脚本。例子:
#!/bin/bash -
#!/usr/bin/php