views:

32

answers:

2

I'm writing a batch file on Windows which gets one argument: a zip file name that was created with 7-zip.

This file contains a single MySQL backup file inside, say backup.sql.

I would like to restore the database given this zip file.

So, first I extract it to a temporary directory like this:

path_to_7zip\7z e "%~1" -otemp_dir

And now is my question: How could I know the name of the extracted file (i.e. backup.sql) ?

I would like to write something like this:

path_to_mysql\mysql < extracted_file_name

(where extracted_file_name should be backup.sql)

What should I write instead of extracted_file_name if I don't know the file name that is inside the zip file ?

A: 

I think 7z has an “l” command to list contents of an archive. pipe this output to mysql.

Benoit
`l` option is nice but it prints a lot of information besides the file name itself. Are you sure I can pipe all this output to `mysql`?
Misha Moroshko
No, of course you need to parse it or to find proper options. Isn't 7z command line documented?
Benoit
If you need to parse we're back to square one, since we need to use FOR /F anyway.
Matteo Italia
+1  A: 

You could extract the file in an empty directory, where you could be sure that it's the only present file. Then you could use the for instruction to gather such name in a variable and use it as you prefer.

FOR /F "tokens=*" %%F IN ('dir /b *.sql') DO path_to_mysql\mysql < %%F

Notice that, if there's more than one SQL file in the archive, all of them will be processed. I think this could be a bonus, but it is undesirable I think you could simply jump out of the FOR with a GOTO.


Edit: using only the /F form of FOR I forgot that the "normal" FOR does already the job we need.

FOR %%F IN (*.sql) DO path_to_mysql\mysql < %%F

Notice that all this stuff works only if the current directory is the extraction directory, otherwise you have to change the expressions in the parentheses accordingly.

Bonus links: reference for FOR and FOR /F - the only commands that do something useful in batch - and that obviously have an impossible syntax. :D

Matteo Italia
How should I gather the name in a variable ?
Misha Moroshko
If the temp directory was initially empty, just use the 'for' command to execute the mysql command over every file in that directory. I don't know the exact syntax, but it's something like `for /f %s in (%tempdir/*) do mysql < %s`.
Jason R. Coombs
Added examples, see original answer.
Matteo Italia
Thank you very much for your time !
Misha Moroshko