如果我正确理解您的问题,您希望执行$command1,然后仅在$command1 成功时执行$command2。
您尝试的方式,通过将命令与&& 连接起来是shell 脚本中的正确方式(它甚至可以使用PHP 函数exec())。但是,因为你的脚本是用 PHP 写的,所以我们用 PHP 的方式来做(其实是一样的,但是我们让 PHP 做逻辑上的AND 操作)。
使用 PHP 函数 exec() 运行每个命令并向其传递三个参数。第二个参数($output,通过引用传递)是一个数组变量。 exec() 将命令的输出附加到它。第三个参数($return_var,也是通过引用传递)是一个由exec()设置的变量,带有执行命令的退出代码。
Linux/Unix 程序的约定是返回 0 退出代码表示成功,返回一个(一个字节)正值 (1..255) 表示错误。此外,Linux shell 上的&& 运算符知道0 是成功的,非零值是错误的。
现在,PHP 代码:
$command1 = "ipcli -S 192.168.4.2 -N nms -P nmsworldcall ";
$command2 = "list search clientclassentry hardwareaddress 00:0E:09:00:00:01";
// Run the first command
$out1 = array();
$code1 = 0;
exec($command1, $out1, $code1);
// Run the second command only if the first command succeeded
$out2 = array();
$code2 = 0;
if ($code1 == 0) {
exec($command2, $out2, $code2);
}
// Output the outcome
if ($code1 == 0) {
if ($code2 == 0) {
echo("Both commands succeeded.\n");
} else {
echo("The first command succeeded, the second command failed.\n");
}
} else {
echo("The first command failed, the second command was skipped.\n");
}
代码结束后,$code1和$code2包含两个命令的退出代码;如果$code1 不为零,则第一个命令失败,$code2 为零,但第二个命令未执行。
$out1 和 $out2 是包含两个命令输出的数组,按行拆分。