Reputation: 1201
#!/bin/bash
cd /maintenance;
for (( i=1;i<1000;i++)); do
php -q dostuff.php $i
done
I use this shell script to call the dostuff.php
script and pass the $i
as an agrv
to the script. The script connects to a webservice that returns results 50 items at a time. The $i
value is the page number... I have no way to know how many times it needs to be called (how many pages) until I get a response code back from CURL inside that script that I test for. I need to pass my own response code back to the shell script to have it stop looping... it will never get to 1000 iterations... it was just a quick loop I made.
If I use exec("php -q dostuff.php $i", $output, $return_var)
how do I tell the script to keep executing and passing the incremented $i
value until my php script exits with a response code of 0?
There has got to be a better way. Maybe a while? Just not that good with this syntax.
I have to start at page 1 and repeat until page XXX incrementing by 1 each iteration. When there are no more results I can test for this in the dostuff.php
and exit(0). What is the best way to implement this in the shell script?
Thanks!
Upvotes: 0
Views: 755
Reputation: 14629
You can check for the return value of the script, and break
the loop if it isn't what is expected.
Usually a script returns 0
when it ran successfully, and something else otherwise, so if I assume your script respect this condition you could do:
#!/bin/bash
cd /maintenance;
for (( i=1;i<1000;i++)); do
php -q dostuff.php $i
if [ $? -ne 0 ]; then break; fi
done
On the other hand, if you want your script to return 0 if the loop shouldn't continue then you should do:
if [ $? -eq 0 ]; then break; fi
Edit: to take the comment into account to simplify the script:
If your script returns 0 when it shouldn't be called again, you instead do:
#!/bin/bash
cd /maintenance;
for (( i=1;i<1000;i++)); do
if php -q dostuff.php $i; then break; fi
done
Upvotes: 1
Reputation: 32340
As already suggested in the comments, you might get way better control if you dont wrap the php script inside a bash script but instead use php-cli as the shell script (PHP is kinda shell):
#!/usr/bin/php
<?php
for ($i = 0; $i < 1000; $i++) {
// contents of dostuff.php integrated
}
You might also be interested in using STDOUT, STDIN and STDERR:
http://php.net/manual/en/features.commandline.io-streams.php
Upvotes: 0