xXxrk04
xXxrk04

Reputation: 195

BATCH: FOR LOOP with IF ELSE , mysql and directory

I need some help. I want to get the database name in MySQL to make it as directory name. But my code is not correct . it fails.

e.g
DATABASE NAME 
- sample
- sample_test

i want to create a directory with the same name as database name.

my code is:

@echo off
SET path=C:\Users\neca\Desktop
cd C:\wamp\bin\mysql\mysql5.5.24\bin
SET UserName=root
SET UserPass=root

mysql -u%UserName% -r%UserPass% -N -B -e "SHOW DATABASES LIKE '%%sample%%'" |
FOR /F %%D IN ('C:\Windows\System32\findstr /V "information_schema performance_schema"') DO @echo %%D 
IF exist %path%\%%D (echo %%D exist) 
ELSE (mkdir %path%\%%D && echo %%D created)

i got this result: i add pause command to pause the terminal and the display is

sample IF exist C:\Users\neca\Desktop\sample (echo sample exist) 
ELSE  (mkdir C:\Users\neca\Desktop\sample sample created)
Press any key to continue . . .

when i test it just like this the output is correct

 @echo off
 SET path=C:\Users\neca\Desktop
 cd C:\wamp\bin\mysql\mysql5.5.24\bin
 SET UserName=root

 mysql -uroot -N -B -e "SHOW DATABASES LIKE '%%sample%%'" 
 pause

output:

 sample
 sample_test
 Press any key to continue . . .

Upvotes: 0

Views: 1072

Answers (1)

JosefZ
JosefZ

Reputation: 30123

Under next circumstances:

mysql -uroot -N -B -e "SHOW DATABASES LIKE '%sample%'" 
sample
sample_test
Press any key to continue . . .

this batch script should work:

 @echo off
 pushd C:\wamp\bin\mysql\mysql5.5.24\bin
 SET "pathxxx=C:\Users\neca\Desktop"
 SET "UserName=root"
 for /F "usebackq tokens=*" %%G in (
        `mysql -uroot -N -B -e "SHOW DATABASES LIKE '%%sample%%'"`
    ) do (
          echo processing "%%G"
          IF exist "%pathxxx%\%%~G" (
              echo %%G exist 
          ) ELSE (
              echo mkdir "%pathxxx%\%%~G"
              echo %%G created
          )
    )
 popd

Notes:

  • do not change the system environment variable path, not even temporarily; use another variable name, here pathxxx;
  • instead of chdir command used pushd .. popd pair: popd will change directory back to the path/folder most recently stored by the pushd command;
  • usebackq forces alternate quoting style in for /F command; essential as your command contains ' single quotes;
  • as a matter of general principle, used %%~G with the ~ argument modifier to remove surrounding quotes (") if any;
  • echo mkdir "%pathxxx%\%%~G" for debugging purposes only (get rid of the echo word when debugged.

Upvotes: 1

Related Questions