繁体   English   中英

PHP exec() 命令:如何指定工作目录?

[英]PHP exec() command: how to specify working directory?

我的脚本,我们称之为execute.php,需要启动一个位于Scripts 子文件夹中的shell 脚本。 脚本必须被执行,所以它的工作目录是 Scripts。 如何在 PHP 中完成这个简单的任务?

目录结构如下所示:

execute.php
Scripts/
    script.sh

要么在 exec 命令( exec("cd Scripts && ./script.sh") )中更改到该目录,要么使用chdir()更改 PHP 进程的工作目录。

当前工作目录与 PHP 脚本的当前工作目录相同。

只需在exec()之前使用chdir()更改工作目录。

为了更好地控制子进程的执行方式,您可以使用proc_open()函数:

$cmd  = 'Scripts/script.sh';
$cwd  = 'Scripts';

$spec = array(
    // can something more portable be passed here instead of /dev/null?
    0 => array('file', '/dev/null', 'r'),
    1 => array('file', '/dev/null', 'w'),
    2 => array('file', '/dev/null', 'w'),
);

$ph = proc_open($cmd, $spec, $pipes, $cwd);
if ($ph === FALSE) {
    // open error
}

// If we are not passing /dev/null like above, we should close
// our ends of any pipes to signal that we're done. Otherwise
// the call to proc_close below may block indefinitely.
foreach ($pipes as $pipe) {
    @fclose($pipe);
}

// will wait for the process to terminate
$exit_code = proc_close($ph);
if ($exit_code !== 0) {
    // child error
}

如果您确实需要将工作目录作为脚本,请尝试:

exec('cd /path/to/scripts; ./script.sh');

除此以外,

exec('/path/to/scripts/script.sh'); 

应该足够了。

这不是最好的方法:

exec('cd /patto/scripts; ./script.sh');

将此传递给 exec 函数将始终执行 ./scripts.sh,如果cd命令失败,这可能会导致脚本无法使用正确的工作目录执行。

这样做:

exec('cd /patto/scripts && ./script.sh');

&&是 AND 逻辑运算符。 使用这个操作符,只有当cd命令成功时,脚本才会被执行。

这是一个使用 shell 优化表达式求值方式的技巧:由于这是一个 AND 运算,如果左侧部分的求值结果不为 TRUE,则整个表达式无法求值为 TRUE,因此 shell 不会进行事件处理表达式的正确部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM