Saket Krishna
Saket Krishna

Reputation: 31

how to handle space in variable batch script

I have batch file which is prompting user to provide file name. File can or can't have space. My batch is failing if my file name has space in it. For example:

SET TDSX=.txt    
SET /p DS=%1    
move C:\Working\YAHAMA\DEV\Script\%DS%%TDSX% C:\Working\YAHAMA\NEW_FO

Upvotes: 0

Views: 227

Answers (2)

Compo
Compo

Reputation: 38613

You need to protect the spaces in the resultant file and directory names using doublequotes too:

@Echo Off
CD /D "C:\Working\YAHAMA" 2>Nul || Exit /B
Set "TDSX=.txt"
Set /P "DS=%~1"
If Exist "DEV\Script\%DS%%TDSX%" (
    If Not Exist "NEW_FO\" MD "NEW_FO"
    Move "DEV\Script\%DS%%TDSX%" "NEW_FO"
)

Upvotes: 1

jwdonahue
jwdonahue

Reputation: 6659

Put quotes around variable assignment like this:

set /p "DS=%~1"

The squiggly ~ thing removes any quotes from the argument. The above assumes that the file name on the command line has quotes around, otherwise, it's not a single argument as far as cmd is concerned, you may need:

set /p "DS=%*"

Upvotes: 2

Related Questions