Thursday, April 7, 2022

[SOLVED] Using the output of a php script in a bash script

Issue

I have a working .bash_profile startup script like so:

if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

PATH=$PATH:$HOME/bin

export PATH

while true;
do
./xxx.php
echo "Program Restarting."
sleep 10
done

I need to edit it so that, depending on how the xxx.php script exits (probably using exit(1)), the script "breaks out" of its permanent loop, and actually exits the shell it's in (which should close the Putty window on the device I'm using).

The problem is, I don't know shell scripting, so I don't seem to be able to get the syntax right.

Trying

if [./xxx.php]; then
        exit
fi

gives me "-bash: [./xxx.php]: No such file or directory" (and I get the same error message if I just put in "xxx.php" or the full path of "/home/user/xxx.php")

Trying to save the returned code in a variable for later use ala

BreakVar = $(./xxx.php)

Just causes the putty window to freeze.

I've tried reading the questions in

Run PHP function inside Bash (and keep the return in a bash variable)

or

How can I assign the output of a function to a variable using bash?

don't help me much either, due to me not understanding how the specific syntax works sadly, so I can't convert those answers to my specific situation.

Note: Other than adding the short "exit(1)" clause to the xxx.php script, assume that I am not allowed to alter that script any farther :(.


Solution

The exit status is generically obtained with the variable $?. See here. So, assuming that you want to exit the loop when the exit status is 1, you write

while true;
do
  ./xxx.php
  if [ $? -eq 1 ]
  then
     break
  fi
done


Answered By - francesco
Answer Checked By - Willingham (WPSolving Volunteer)