Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve exit status from php script inside of shell script

I have a bash shell script that calls a few PHP scripts like this.

#!/bin/bash

php -f somescript.php

php -f anotherscript.php

I want to compose an error log and/or an activity report based on the results of those scripts.

Is there any way I can get the exit status of the php script in the shell script?

I could either use integer exit statuses or string messages.

like image 248
Buttle Butkus Avatar asked Sep 06 '13 00:09

Buttle Butkus


People also ask

How do I get exit status in shell?

To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command. $ echo $?

How do I return an exit code?

To get the exit code of a command type echo $? at the command prompt. In the following example a file is printed to the terminal using the cat command. The command was successful.

How do you check exit status in bash?

To display the exit code for the last command you ran on the command line, use the following command: $ echo $?

What is exit status in shell script?

The exit status of an executed command is the value returned by the waitpid system call or equivalent function. Exit statuses fall between 0 and 255, though, as explained below, the shell may use values above 125 specially. Exit statuses from shell builtins and compound commands are also limited to this range.


2 Answers

You can easily catch the output using the backtick operator, and get the exit code of the last command by using $?:

#!/bin/bash
output=`php -f somescript.php`
exitcode=$?

anotheroutput=`php -f anotherscript.php`
anotherexitcode=$?
like image 155
Emilio P. Avatar answered Oct 29 '22 01:10

Emilio P.


Emilio's answer was good but I thought I could extend that a bit for others. You can use a script like this in cron if you like, and have it email you if there is an error.. YAY :D

#!/bin/sh

EMAIL="[email protected]"
PATH=/sbin:/usr/sbin:/usr/bin:/usr/local/bin:/bin
export PATH

output=`php-cgi -f /www/Web/myscript.php myUrlParam=1`
#echo $output

if [ "$output" = "0" ]; then
   echo "Success :D"
fi
if [ "$output" = "1" ]; then
   echo "Failure D:"
   mailx -s "Script failed" $EMAIL <<!EOF
     This is an automated message. The script failed.

     Output was:
       $output
!EOF
fi

Using php-cgi as the command (instead of php) makes it easier to pass url parameters to the php script, and these can be accessed using the usual php code eg:

$id = $_GET["myUrlParam"];

like image 44
Bastion Avatar answered Oct 29 '22 01:10

Bastion