tags:

views:

40

answers:

1

I'm trying to remove all white space and code comments from my .php files by using the -W flag available from the PHP CLI. I'm using a batch file to recursively loop through each php file in my project. The batch command looks like:

FOR /F "tokens=*" %%G IN ('DIR /B /A-D /S *.php') DO "%php-exe-path%/php.exe" -w %%G > %%G 

This just produces blank .php files (using the '>' redirector), however using the appending redirector ('>>') works fine. I'm not sure if this is an issue with PHP locking the files or some problem with my batch command.

Can anyone help?

+2  A: 

Generally: Don't ever pipe the output of a command that works with a file into the file again. Instead pipe to a temporary file, delete the old one and rename the temporary one to the old name. Kinda like the following:

FOR /F "tokens=*" %%G IN ('DIR /B /A-D /S *.php') DO (
    "%php-exe-path%/php.exe" -w %%G > %%G.temp
    del %%G
    ren %%G.temp %%G
)

Side note: Please don't use for /f over the output of dir as that can introduce some subtle but nasty errors. Instead use the proper way of iterating over files which is just plain for, and recursively with the /r switch:

FOR /R %%G IN (*.php) DO (
    "%php-exe-path%/php.exe" -w %%G > %%G.temp
    del %%G
    ren %%G.temp %%G
)
Joey
+1. This is totally standard operating procedure when it comes to using the ">" redirection operator.
Frank Farmer
As this was returning the full path I needed to a change a couple of bits. Swapped the underscore with an appended '.temp' and changed the rename command to 'ren %%G.temp %%~NG.php'. Thanks for all the help.
CJD
Ah, right. I'm sorry. Corrected
Joey