If I understand your question correctly, you want to execute $command1
and then execute $command2
only if $command1
succeeds.
The way you tried, by joining the commands with &&
is the correct way in a shell script (and it works even with the PHP function exec()
). But, because your script is written in PHP, let's do it in the PHP way (in fact, it's the same way but we let PHP do the logical AND
operation).
Use the PHP function exec()
to run each command and pass three arguments to it. The second argument ($output
, passed by reference) is an array variable. exec()
appends to it the output of the command. The third argument ($return_var
, also passed by reference) is a variable that is set by exec()
with the exit code of the executed command.
The convention on Linux/Unix programs is to return 0
exit code for success and a (one byte) positive value (1
..255
) for errors. Also, the &&
operator on the Linux shell knows that 0
is success and a non-zero value is an error.
Now, the PHP code:
$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");
}
After the code ends, $code1
and $code2
contain the exit codes of the two commands; if $code1
is not zero then the first command failed and $code2
is zero but the second command was not executed.
$out1
and $out2
are arrays that contain the output of the two commands, split on lines.