Search code examples
mysqlbatch-filecmd

Having trouble with getting bat file to work, does anyone know what is wrong with this bat file


@echo off
cls
echo Date format = %date%
echo dd = %date:~0,2%
echo mm = %date:~3,2%
echo yyyy = %date:~6,4%
echo.
echo Time format = %time%
echo hh = %time:~0,2%
echo mm = %time:~3,2%
echo ss = %time:~6,2%
echo.
set timestamp=%date:~6,4%-%date:~3,2%-%date:~0,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%
F:\XAMPP\mysql\bin\mysqldump.exe -u root -pABC123 database >"C:\Users\Administrator\Desktop\backups\database_file_%timestamp%.sql"

The bat file breaks when I add the timestamp variable. I have tried a few different things but I am unsure why adding the timestamp variable would break it.


Solution

  • Your problem seems to be that you're extracting the wrong characters in the date variable. The date value includes a three-character day (Mon 12/04/2021) which you're not skipping, so you're extracting the wrong values for yyyy, mm and dd.

    Try this:

    cls
    echo Date format = %date%
    echo dd = %date:~4,2%
    echo mm = %date:~7,2%
    echo yyyy = %date:~10,4%
    echo.
    echo Time format = %time%
    echo hh = %time:~0,2%
    echo mm = %time:~3,2%
    echo ss = %time:~6,2%
    echo.
    set timestamp=%date:~10,2%-%date:~7,2%-%date:~4,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%
    F:\XAMPP\mysql\bin\mysqldump.exe -u root -pABC123 database >"C:\Users\Administrator\Desktop\backups\database_file_%timestamp%.sql"
    

    Note that the date format is dependent on locale (and possibly Windows version). Most obviously the day and month will be interchanged between US English and UK English. Other languages will need to be adjusted for their specific formats.