如果我正確理解你的問題,你要執行$command1
,然後執行$command2
只有$command1
成功。
您嘗試的方式,通過將命令加入&&
是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
是包含兩條命令的輸出的數組,分割在線上。
這不能解決我的問題 –