I am trying to create a simple .bat file that will generate a .html file that contains image links to all the images in the current directory.
Usage:
C:> gallery
Output:
gallery.html
File contents:
<HTML><HEAD></HEAD><BODY>
<IMG SRC="C:/path/path/path/image1.gif">
<IMG SRC="C:/path/path/path/randomepic.gif">
<IMG SRC="C:/path/path/path/asdfsadfasd.gif">
</BODY></HTML>
Note the image files will have unpredictable names, but will always be .gif.
What I’ve got: (in gallery.bat)
@echo off
set file_start=<HTML><HEAD></HEAD><BODY>
set image_start=<IMG SRC="
set image_dir=`cd`
set image_end=">
set file_end=</BODY></HTML>
set file_name=gallery.html
echo %file_start% > %file_name%
for %%image in (*.gif) do @echo %image_start%%image_dir%%%image%image_end% >> $file_name%
echo %file_end% >> %file_name%
But it doesn’t work. I can’t get the less-than symbol to appear, because the batch file thinks it is an input redirect. If I quote the lines with the < symbol, then the quotes appear in the echo statements.
Also, I can’t get the cd command output to save to the variable %image_dir%
Lastly, the echo statement in the for-loop isn’t printing out correctly. This might be a symptom of the previous problems though.
I’m hoping its just minor syntax problems I am having. Does anyone know how to fix this? Thanks for your time!
Patrick Q
FOR variables must be a single character. You cannot use something like
%%image.You have problems with
<and>twice over. Once when you define your variables, and again when you echo the expanded variable. Those characters must either be quoted or escaped with^.You can use quotes during the assignment without including quotes in the variable –
set "var=value". The assignment ofimage_endis a bit tricky because of the embedded quote.You can avoid the problem with ECHO by escaping the problem characters in your original assignment.
You cannot use
CDto get the current directory. The proper syntax is%CD%. But you don’t need yourimage_dirvariable. You can use the~fmodifier to get the full path of the file name. Typehelp forfrom a command prompt for more information about FOR variable modifiers.It is more efficient to enclose all the commands that produce output in parentheses and redirect to your output file just once.
Another way to avoid problems while ECHOing unquoted characters is to use delayed expansion. But
!is valid in file names, and delayed expansion will corrupt expansion of FOR variables if they contain the!character. So delayed expansion must be toggled on and off within the loop.