Search code examples
batch-filecmdbatch-processingyoutube-dl

How do i set variables literally in batch?


I want to set "var3=%(title)s.%(ext)s" But windows keeps on interpreting %(title)s.%(ext)s as (ext)s instead of %(title)s.%(ext) is there a way to "set" in a literal way without cmd interpreting it?

EDIT Somebody wanted to see the whole script

cd C:\youtube-dl
youtube-dl -U 
echo Remember to press enter only AFTER update is complete
pause
set /p "var1=Enter URL: " %=% pause
set "var2=%date:/=-%" 
set /p var3=%(title)s.%(ext)s
youtube-dl "%var1%" -ci -o C:\Users\Admin\Desktop\Music\Download_dl\%var2%\%var3% -f best -x --    no-mtime --add-metadata --write-thumbnail  
cd C:\Users\Admin\Desktop\Music\Download_dl\%var2%
del *.mp4

Solution

  • To preserve most special characters in batch, enclose them within quotations. This will prevent most from being lost or translated into their special meaning. However, for % in batch files, it must be escaped by itself %%.

    @echo off
    setlocal
    cd C:\youtube-dl
    youtube-dl -U
    echo Remember to press enter only AFTER update is complete
    pause
    set /p "var1=Enter URL: " %=% pause
    if defined var1 set "var1=%var1:"=%"
    set "var2=%date:/=-%"
    set "var3=%%(title)s.%%(ext)s"
    youtube-dl "%var1%" -ci -o "C:\Users\Admin\Desktop\Music\Download_dl\%var2%\%var3%" -f best -x --    no-mtime --add-metadata --write-thumbnail  
    cd "C:\Users\Admin\Desktop\Music\Download_dl\%var2%"
    del *.mp4
    endlocal
    

    Changes

    • scoped variables with setlocal/endlocal
    • removed poison character quotation from user input
    • enclosed literal strings in quotations