Saroj Kumar Moharana Saroj Kumar Moharana - 1 month ago 12
Bash Question

execute shell script code depends upon php return value

I haven't that much of knowledge in PHP, and I need to run a script that depends upon the PHP return value.

script



presentDir=`pwd`
success=$(php -f $presentDir/optimize.php $file)
echo echo "value:".$success


PHP code



<?php
try{
//code
} catch(Exception $e){
return 1
}
return 0


When executing the above shell script, success is empty.

Answer

PHP's return statement doesn't send any output to STDOUT, which is what you'd be catching with the $() construct. To see the exit value from a command you use the exit statement in PHP and the shell's $? variable. Maybe this is what you're looking for?

<?php
try {
    //code
} catch(Exception $e){
    exit 1;
}
exit 0;
?>

Followed by:

#!/bin/sh
php -f optimize.php "$file"
printf "PHP script returned %d" $?

# or you could just use if:
if php -f optimize.php "$file"; then
    do_stuff
fi

There's no need to include the current working directory in a script call. (Further to that, you could make the script executable and call it directly!)